简体   繁体   中英

Jquery AJAX Post: 500 (Internal Server Error)? in Symfony 3

I am trying post an id to Controller action but I am getting this error : (I am using Symfony 3).

jquery-1.11.0.min.js:4 POST http://localhost/plate/web/app_dev.php/province_ajax_call?province_id=2 500 (Internal Server Error)

Here is my ajax code :

 <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
{{ form(form_account) }}


<script>
$(document).ready(function(){
    $('#appbundle_account_Province').change(function(){
        var val = $('#appbundle_account_Province').val();
        $.ajax({
            type: "POST",
            url: "{{ url('province_ajax_call') }}?province_id=" + val,
            success: function(data){
                $('#appbundle_account_City').html('');
                $.each(data, function(key, value){
                    $('#appbundle_account_City').append('<option value="'+ key +'">'+ value +'</option>');
               })
               console.log('succes');
            }
        })
    })
})

Here is My controller code :

public function provinceAjaxCallAction(Request $request)
{

    if (!$request->isXmlHttpRequest())
    {
        throw new NotFoundHttpException();
    }

    $id = $request->query->get('province_id');
    var_dump($id);

    $cities = $this
              ->getDoctrine()
              ->getManager()
              ->getRepository('AppBundle:City')
              ->findByProvinceId($id);

    $result = array();
    foreach($cities as $city){
        $result[$city->getId()] = $city->getName();
    }
    return new JsonResponse($result);
}

public function indexAction(Request $request)
{
    $account = new Account();

    $form = $this->createForm(AccountType::class, $account);
    $form->handleRequest($request);

    if($form->isValid())
    {
        $this->getDoctrine()->getManager()->persist($account);
        $this->getDoctrine()->getManager()->flush();

        return $this->redirectToRoute('test_registration_homepage');
    }

    return $this->render('default/index.html.twig', array('form_account' => $form->createView()));


}
}

I resolved my problem by adding

use Symfony\Component\HttpFoundation\JsonResponse;

in the controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM