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












1














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.










share|improve this question
























  • Most db writes are very fast. Do you have some long process running before you can write to db?
    – charlietfl
    Nov 22 at 18:33












  • After you send a response you usually can't send another response, however you may be able to broadcast something to a client through a socket. However they can be tricky to set up properly
    – apokryfos
    Nov 22 at 18:46










  • Could you not wait until after the write to send the response?
    – Ghostrydr
    Nov 22 at 19:41










  • You can send short messages in either direction through sockets, laravel is set up nicely for this, I highly recommend checkout out the related videos on laracasts for this.
    – wheelmaker
    Nov 22 at 21:02










  • How did u go???
    – adis
    Nov 24 at 8:31
















1














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.










share|improve this question
























  • Most db writes are very fast. Do you have some long process running before you can write to db?
    – charlietfl
    Nov 22 at 18:33












  • After you send a response you usually can't send another response, however you may be able to broadcast something to a client through a socket. However they can be tricky to set up properly
    – apokryfos
    Nov 22 at 18:46










  • Could you not wait until after the write to send the response?
    – Ghostrydr
    Nov 22 at 19:41










  • You can send short messages in either direction through sockets, laravel is set up nicely for this, I highly recommend checkout out the related videos on laracasts for this.
    – wheelmaker
    Nov 22 at 21:02










  • How did u go???
    – adis
    Nov 24 at 8:31














1












1








1







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.










share|improve this question















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.







javascript php jquery ajax laravel






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 22 at 19:53









Billal Begueradj

5,631132637




5,631132637










asked Nov 22 at 18:27









Alex Kerr

223118




223118












  • Most db writes are very fast. Do you have some long process running before you can write to db?
    – charlietfl
    Nov 22 at 18:33












  • After you send a response you usually can't send another response, however you may be able to broadcast something to a client through a socket. However they can be tricky to set up properly
    – apokryfos
    Nov 22 at 18:46










  • Could you not wait until after the write to send the response?
    – Ghostrydr
    Nov 22 at 19:41










  • You can send short messages in either direction through sockets, laravel is set up nicely for this, I highly recommend checkout out the related videos on laracasts for this.
    – wheelmaker
    Nov 22 at 21:02










  • How did u go???
    – adis
    Nov 24 at 8:31


















  • Most db writes are very fast. Do you have some long process running before you can write to db?
    – charlietfl
    Nov 22 at 18:33












  • After you send a response you usually can't send another response, however you may be able to broadcast something to a client through a socket. However they can be tricky to set up properly
    – apokryfos
    Nov 22 at 18:46










  • Could you not wait until after the write to send the response?
    – Ghostrydr
    Nov 22 at 19:41










  • You can send short messages in either direction through sockets, laravel is set up nicely for this, I highly recommend checkout out the related videos on laracasts for this.
    – wheelmaker
    Nov 22 at 21:02










  • How did u go???
    – adis
    Nov 24 at 8:31
















Most db writes are very fast. Do you have some long process running before you can write to db?
– charlietfl
Nov 22 at 18:33






Most db writes are very fast. Do you have some long process running before you can write to db?
– charlietfl
Nov 22 at 18:33














After you send a response you usually can't send another response, however you may be able to broadcast something to a client through a socket. However they can be tricky to set up properly
– apokryfos
Nov 22 at 18:46




After you send a response you usually can't send another response, however you may be able to broadcast something to a client through a socket. However they can be tricky to set up properly
– apokryfos
Nov 22 at 18:46












Could you not wait until after the write to send the response?
– Ghostrydr
Nov 22 at 19:41




Could you not wait until after the write to send the response?
– Ghostrydr
Nov 22 at 19:41












You can send short messages in either direction through sockets, laravel is set up nicely for this, I highly recommend checkout out the related videos on laracasts for this.
– wheelmaker
Nov 22 at 21:02




You can send short messages in either direction through sockets, laravel is set up nicely for this, I highly recommend checkout out the related videos on laracasts for this.
– wheelmaker
Nov 22 at 21:02












How did u go???
– adis
Nov 24 at 8:31




How did u go???
– adis
Nov 24 at 8:31












2 Answers
2






active

oldest

votes


















0














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"
}
}





share|improve this answer





























    0














    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!






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53436458%2fhow-to-handle-two-separate-responses-from-the-server-to-a-jquery-ajax-request%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      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"
      }
      }





      share|improve this answer


























        0














        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"
        }
        }





        share|improve this answer
























          0












          0








          0






          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"
          }
          }





          share|improve this answer












          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"
          }
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 22 at 18:47









          Banujan Balendrakumar

          512210




          512210

























              0














              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!






              share|improve this answer




























                0














                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!






                share|improve this answer


























                  0












                  0








                  0






                  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!






                  share|improve this answer














                  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!







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 22 at 19:44









                  Marius

                  867




                  867










                  answered Nov 22 at 19:06









                  adis

                  157114




                  157114






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53436458%2fhow-to-handle-two-separate-responses-from-the-server-to-a-jquery-ajax-request%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Contact image not getting when fetch all contact list from iPhone by CNContact

                      count number of partitions of a set with n elements into k subsets

                      A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks