Reputation: 197
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()));
}
}
Upvotes: 1
Views: 1994
Reputation: 197
I resolved my problem by adding
use Symfony\Component\HttpFoundation\JsonResponse;
in the controller.
Upvotes: 1