I just need to know how to pass a array using ajax into a laravel controller and save those data in DB. I tried serveral ways. but the serve respond is Object { error: "No data received"}. API status code is 200.
This is my ajax code. function AddContactData() {
var contactData = [];
var table = document.getElementById('customer_contact'),
rows = table.getElementsByTagName('tr'),
i, j, cells, customerId;
for (i = 0, j = rows.length; i < j; ++i) {
cells = rows[i].getElementsByTagName('td');
if (!cells.length) {
continue;
}
var data = {
"name": cells[0].childNodes[0].value,
"designation": cells[1].childNodes[0].value,
"mobile": cells[2].childNodes[0].value,
"fixed": cells[3].childNodes[0].value,
"email": cells[4].childNodes[0].value,
"remark": cells[5].childNodes[0].value
};
contactData.push(data);
}
//console.log(contactData);
var contactDetails = JSON.stringify(contactData);
console.log(contactData);
$.ajax({
url: '/saveContact',
type:'POST',
data: contactDetails,
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function (response) {
console.log(response);
// $('#frmCustomer')[0].reset();
}, error: function (data) {
console.log(data)
}
})
};
and this is my laravel function to insert those data to DB
public function addContactDetails(Request $request){
try{
$data = json_decode($request->input('contactDetails'), true);
if(empty($data)){
return response()->json(['error' => 'No data received']);
}
foreach($data as $key =>$value){
if(is_array($value)){
foreach($value as $row){
DB::table('customer_contacts')->insert([
'customer_id' => 1,
'contact_person'=> $row['name'],
'designation'=>$row['designation'],
'mobile'=>$row['mobile'],
'fixed'=>$row['fixed'],
'email'=>$row['email'],
'remarks'=>$row['remark']
]);
}
}
return response()->json(["status" => true]);
}
}catch(Exception $ex){
if ($ex instanceof ValidationException) {
return response()->json(["ValidationException" => ["id" => collect($ex->errors())->keys()[0], "message" => $ex->errors()[collect($ex->errors())->keys()[0]]]]);
}
return response()->json(["error" => $ex]);
}
}