简体   繁体   中英

XMLHttpRequest does not working sometimes

I've created a ClickListener which is supposed to make a POST request to my server. Most of the times, the POST request is made but sometimes, it fails to make a POST request no matter how many times I try. Can anyone help me understand what the issue is and how to resolve it? This is my code where I'm handling that:

$("#Button11").on("click", function() {
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "/addtolist", true);
  xhr.setRequestHeader(
    "Content-type",
    "application/x-www-form-urlencoded",
    "Access-Control-Allow-Origin",
    "*"
  );
  var parameter = "dc=deal1";
  xhr.send(parameter);
  window.location.href = "/final_page.ejs";
});

The issue

XMLHttpRequest.send() is an asynchronous method, that mean this method only ask the request to be sent but it will not be done instantly. Most of the time, this does not matters, but in your script, you redirect the user right after it, so, sometime, the user is redirected before the request is sent.

The solution

You have to wait the request to be done before redirecting the user, thankfully, XMLHttpRequest have a method to achieve it. It is the XMLHttpRequest.onload() method. So you can update your script to :

$("#Button11").on("click", function() {
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "/addtolist", true);
  xhr.setRequestHeader(
    "Content-type",
    "application/x-www-form-urlencoded",
    "Access-Control-Allow-Origin",
    "*"
  );
  var parameter = "dc=deal1";
  xhr.send(parameter);
  xhr.onload = function(){
    window.location.href = "/final_page.ejs";
  };
});

As mentioned in the comments, JQuery also have an integrated solution for making request, I recommend you reading it's documentation to have an even better solution.

Your location change is killing your Ajax before it finishes

Also why not use the much simpler $.post now you have it?

None of your headers are needed and the auth header is not even allowed to be set by you

$("#Button11").on("click", function() {
  $.post("/addtolist",{"dc":"deal1"},function() {
    window.location.href = "/final_page.ejs";
  })  
});

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