Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: call a blocking HTTP POST [duplicate]

I have a caller function that invokes another function that send a HTTP POST with parameters. Now i want that this called function blocks execution until there is its "success" (so when its HTTP POST has been done).

This is my logical code:

var fingerprint = null;
var janus_session = null;
var inserted = "false";

$(document).ready(function() {
      //stuff
      fingerprint = FindFingerprint(jsep);

      janus_session = janus.getSessionId();
      inserted = SendSDPLine(fingerprint, janus_session);
      console.log("**in MAIN: inserted= " + inserted);

      //other stuff
    }

function SendSDPLine(fingerprint, janus_session) {
  var sdp = fingerprint;
  //    var url = "http://localhost:8484/Shine/AccountController";
  var action_type = "InsertSDPLine";
  var sessionid = janus_session;

  $.ajax({
    type: "POST",
    url: url,
    xhrFields: {
      withCredentials: false
    },
    data: {
      "action": action_type,
      "sdpline": fingerprint,
      "sessionid": sessionid
    },
    success: function(data) {
      if (data == "INSERTED") {
        inserted = "true";
        console.log("in SENDSDPLINE: inserted= " + inserted);
      }
      return inserted;
      //        return checkFingerprint (fingerprint);
    },
    // vvv---- This is the new bit
    error: function(jqXHR, textStatus, errorThrown) {
      console.log("Error, status = " + textStatus + ", " +
                  "error thrown: " + errorThrown);
    }
  });

}

In few words, i want that other stuff has been executed after that HTTP POST response has been checked. I've already seen another problem: initially, inserted has false value. In success(data) in HTTP POST response, it has true value. But, in the caller function, in the following console.log has undefined value.

So, i have two question:

  1. how to return this value to the caller function
  2. how to stop execution of the caller function until HTTP POST response has been received?
like image 693
pier92 Avatar asked Oct 30 '22 08:10

pier92


1 Answers

If you need to block the execution until AJAX returns, you can specify async:false in ajax parameters, as per jQuery documentation.

like image 169
Sergey Kudriavtsev Avatar answered Nov 15 '22 05:11

Sergey Kudriavtsev