简体   繁体   中英

How to handle two separate responses from the server to a JQuery AJAX request?

I need to use AJAX to read and write some data from my server, in one operation. I don't want the write to hold up the read, so of course on the server I could read first and respond with that data, but then how do I alert the front end to an error with the write?

Front end is Javascript and JQuery, backend is PHP - or Laravel to be precise (tho I think this question is language agnostic).

My standard JQuery AJAX request:

    $.ajax({
    type: 'POST',
    url: 'savedata',
    dataType: 'json',
    data: { data_to_save: JSON.stringify(mydata) }, // JSON encoded data
    success: function (data_from_server)
        {
        // Update UI with data_from_server
        },
    error: function (data)
        {
        console.log('Error:', data.responseText);
        }
    });

}

Server side (psuedocode):

1. Read requested data from database (using a key in the POST params)
2. Reply to front end with requested data
3. Write data_to_save to the database
4. If there was an error in saving, how to notify the frontend as response has already been sent?

Or I could do two separate AJAX requests on the front end, one to read, one to write, but do I just list them one after the other in the code, or do I only fire the second in the success block of the first? Two AJAX requests also seems much more inefficient on both front and back end.

Well..... You can do it with 2 methods.

1. Splitting process.

I means first Ask for data. If error, Show error. If success request to Write data, get response If error show error.

2. send response after both operation

first read data, then write data. Send your response like,

{
"read":{
  "status":1
},
"write":{
  "status":0,
  "error":"the error message"
}
}

What you can do is, in the controller action of saving the data, use a try catch block.

PHP File

try
{
    save_data()
}
catch(Exception $e)
{
    return response->json(['message' => $e->getMessage() ], 500);
}

500 means server error status. You can define it yourself or get it from the Exception object. Using a try catch block ensures the ajax call to know that a success/ error has occured.

JS File

In the error function of ajax, you can add data argument, and console.log(data) , it will catch the error from server side.

Goodluck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM