0

So I have been playing around with javascript and XMLHttpRequest, and I am trying to send a request to check if a file has been saved (C#) and if it has, it returns 0 and if it hasn't saved, then it returns -1.

What I want to do with Javascript is that if it reuturns 0, I want to alert the user that it has been 'successful' and if it returns -1 then I want it to alert the user saying 'Not saved'. What I have tried is:

var data = {'namn': 'Helloworld'}

var json = JSON.stringify(data) /** Konventera till JSON **/

let req = new XMLHttpRequest();

req.onreadystatechange = function() {
    if (this.readyState == 4) {

      if (this.status == 200) { /** Kollar ifall request response är 200 = OK **/
        console.log("Response is looking good! [" + this.status + "]");

      } else { /** Om det är inte OK. Skicka meddelande till användaren.  **/
        console.log("Response is bad! [" + this.status + "] - Check if the server is on and connected!");
        document.getElementById("toggle").innerHTML = "Gick ej att beställa!";
        document.getElementById("toggle").disabled = true;
      }
    }
    };

req.open("post", "https://localhost:44363/api/values"); 
req.setRequestHeader("content-type", "application/json");
req.send(json);

and here is where I am stuck. basically I want to check if req.send(json); returns 0 or -1. Alert if 0 SUCCESSFUL or -1 UNSUCCESFUL.

DigitalJedi
  • 1,577
  • 1
  • 10
  • 29
Thrillofit86
  • 599
  • 2
  • 7
  • 20
  • I think the returned data are available with `req.response`. – Kévin Bibollet May 10 '19 at 14:19
  • _“basically I want to check if req.send(json); returns 0 or -1”_ - no you don’t, because that method call doesn’t return anything to begin with. You want to check the response inside your readystatechange callback handler. – 04FS May 10 '19 at 14:20
  • do you have a reason as to why you're using `XMLHttpRequest` instead of `fetch`? – Olian04 May 10 '19 at 14:23
  • Not particle reason honestly. I founded a youtube tutorial and followed it @Olian04 – Thrillofit86 May 10 '19 at 14:30

0 Answers0