php - Laravel 5 access to ajax Post Data -
i'm trying receive data form through ajax on laravel 5.
javascript code:
event.preventdefault(); // disable normal behaviour of element (form) var formdata = { form: $("#newcustomerform").serialize() // transmit input data of form serialized } console.log(formdata); // log console input data $.ajax({ type: 'post', // post request url: 'save', // url of route (in case user/save not save) data: formdata, // serialized data datatype: 'json', // data type of transmit beforesend: function (xhr) { // function needed laravel because of csrf middleware var token = $('meta[name="csrf_token"]').attr('content'); if (token) { return xhr.setrequestheader('x-csrf-token', token); } }, success: function (data) { // successfuly called controler // check if logic successful or not if (data.status == 'success') { console.log('alles ok'); } else { console.log(data.msg); } }, error: function (data) { // error while calling controller (http response code different 200 ok console.log('error:', data); } });
route:
route::post ('user/save', 'customercontroller@createnewcustomer');
controller:
public function createnewcustomer (request $request) { $inputarray = $request->all(); print_r ($inputarray['form']); // set json response array (status = success | error) $response = array ('status' => 'success', 'msg' => 'setting created successfully',); // return json response return response ()->json ($response); }
in network tab can see how parameters like:
radio-inline-left=on&firstname=sdsd&private_lastname=&private_title=&private_birthdate=&private_email=&business_email=&private_phone=&business_phone=&private_mobile=&business_mobile=&brand=&business_job_title=&business_address_street=sdsd&business_address_po_box=&business_address_addon_1=&business_address_addon_2=&private_zip=&private_location=&business_address_street=&business_address_po_box=&business_address_addon_1=&business_address_addon_2=&private_zip=&private_location=&source=social_media&source=&availability=on&additional-info={"status":"success","msg":"setting created successfully"}
i tried access data $request->input('name of field')
it's empty.
does have idea i'm doing wrong?
the problem calling $("#newcustomerform").serialize()
, , method serializes form in url-encoded parameters , not json encoded body.
in question answer provided work.
Comments
Post a Comment