php - symfony2 ajax call always return null data -
i using symfony 2.7 , query information database , show on page want current values via api connection through ajax call clicking button null response 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 not ajax!', 400); }
console.log
object { sucess: true, data: null }
because data object has no data
key, cannot retrieve doing $request->request->get('data');
to whole object, use $data = $request->request->all();
there many errors in code.
pushing values in productnr
instead of productnr
.
have many elements same id (an id uniq, have use classes).
edit
the problem coming format of data sending. send object {"data":["1k0615301m1","1k0615301m2"]}
, use:
var productnr = { data: [] }; var ajaxrequest; $('.product').each(function() { var product = $(this).text(); productnr.data.push(product); }); ajaxrequest = $.ajax({ url: "/ajax", type: "post", data: json.stringify(productnr), processdata: false, success: function (data) { console.log(data); } });
use json.stringify
serialise data before send it.
see how post array of objects $.ajax (jquery or zepto)
Comments
Post a Comment