Ted Logan
Ted Logan

Reputation: 414

OctoberCMS callback for successful DB action after AJAX request

Im sending data via AJAX from my Chrome-extension to my OctoberCMS controller. How can I recognize in my Chrome-extension that the database operation was successful? So the goal is that I can use the done() in my AJAX call after a successful database update. Do I have to return something from my controller?

Ajax from extension

$.ajax({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    url: "/saveData",
    type: "POST",
    dataType: "JSON",
    data: { "data": data}
}).done(function((){//does nothing});

OctoberCMS Controller

  function saveData(Request $request)
{
    $data = post('data');

    //do some actions with the data;
    
    DB::table('users')->where(['id' => Auth::getUser()->id])->update(['data' => $data]);
}

Upvotes: 0

Views: 213

Answers (1)

Hardik Satasiya
Hardik Satasiya

Reputation: 9715

You can check for response

From server side

function saveData(Request $request)
{
    $data = post('data');

    //do some actions with the data;
    
    DB::table('users')->where(['id' => Auth::getUser()->id])->update(['data' => $data]);

    // if all good return success
    return ['success' => true];
    // if something is not correct
    // return ['success' => false];
}

Client side

$.ajax({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    url: "/saveData",
    type: "POST",
    dataType: "JSON",
    data: { "data": data}
}).done(function((data){
    if(data.success == true) {
       // yes all good data is updated
    }
    else {
       // data is not updated some error handling 
    }
}).fail(function() { 
    // data is not updated some error handling 
    // failed in case server is not able to answer or error 
});

if any doubt please comment.

Upvotes: 2

Related Questions