I am using Symfony 2.7 and I query the information from the database and show it on the page however i want to get the current values via api connection through Ajax call by clicking the button but I always get the null response from Ajax Controller.
<div>
<p id="product">1K0615301M1</p>
<p id="product">1K0615301M2</p>
<input type="button" id="submit" value="Check"/>
</div>
<script>
$(document).ready(function(){
$('#submit').click(function(event) {
var productNr = [];
$('#product').each(function() {
productNr.push($(this).html());
});
console.log(ProductNr); // value of ProductNr
var ajaxRequest;
event.preventDefault();
ajaxRequest = $.ajax({
url: " {{ path('frontend_api_product') }}",
type: "post",
processData: false,
contentType: 'application/json; charset=UTF-8',
data: ProductNr,
success: function (data) {
console.log(data);
}
});
});
});
</script>
My Controller:
public function AjaxAction(Request $request)
{
$sparepart = $request->request->get('data');
if ($request->isXMLHttpRequest()) {
return new JsonResponse(array(
'sucess'=> true,
'data' => $sparepart
));
}
return new Response('This is not ajax!', 400);
}
Console.log
Object { sucess: true, data: null }