0

I have an experimental task implemented in javascript that posts its data to the server via an ajax POST request. This POST request is mandatory for compatability with other tools.

Saving data works fine when the task is finished quickly but over a certain time the server times out and when the tasks tries the POST request, I get a 400 error and nothing gets saved.

My question is can I combine this with a WebSocket and use it to reconnect to the server occasionally and still post my data with an ajax POST request? If so, how do I do this?

This is what my POST function looks like:

  $.ajax({

      type: 'POST',
      url: '/save',
      data: {'data': JSON.stringify(mainData)},

      success: function() {
          console.log('success');
          document.location = '/next'
      },

      // Endpoint not running, local save
      error: function(err) {

          if (err.status == 200) {
              document.location = '/next'
          }        

        }
    }); 

Optimally I would like to have something like this

      if (err.status == 200) {
          document.location = '/next'
      }  else if (err.status == 400) {
            // RECONNECT TO SERVER 
            // call ajax function again
      }      

I don't really have any experience with these tools, so any info will be much appreciated!

///////////////////// EDIT: ///////////////////////

I've been told that a more preferable option is to keep the connection constantly open with regular websocket requests. So a suggestion on how to do this would be appreciated as well.

terraregina
  • 113
  • 1
  • 10
  • If you were going to remove the reliance on AJAX completely, then yes Websockets would be the best solution. As you're not doing that I don't think websockets fit here. If you want to keep retrying the request after a failure response, I'd suggest simply retrying the request after a certain delay (using `setTimeout()`) for a given number of attempts, something like this: https://stackoverflow.com/a/10024557/519413 – Rory McCrossan Jan 12 '21 at 11:57
  • Thank you for the response! I don't think this would help though. The problem is performing a successful POST request upon timeout, not repeating the request. I don't see how this solution would reconnect the server. Or did I misunderstand your suggestion? – terraregina Jan 12 '21 at 12:25
  • Why do you need to reconnect anything? You're making an AJAX request over a transient connection – Rory McCrossan Jan 12 '21 at 12:54
  • yeah, you are right, I had misunderstood how the whole process works. Ultimately the issue was solved in a completely unrelated manner, thank you! – terraregina Jan 16 '21 at 16:55

0 Answers0