0

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]);

   }


}

1 Answer 1

0

I think you don't need JOSN decode in this case because laravel will convert the object to PHP array automatically try this

$validator = validator($request->all(), [
'ids' => 'required|array',
]);

if ($validator->fails()) {
return [
'errors' => $validator->errors()->toArray()
];
}
dump($validator->validated()['ids']);

and to see the data in your console i advice you to use this package laravel-dump-server/installation

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.