Error404 Error404 - 5 months ago 10
Ajax Question

How to know which URL is being requested on AJAX function?

I have a

button
in which I call an AJAX function:

<button class="loadProduct" onclick="loadProduct(7)" type="button">Load product</button>


and this is my AJAX function:

var loadProduct = function (idProduct) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var product = JSON.parse(xhttp.responseText);

alert(product);

}
xhttp.open("GET", "http://localhost/product/loadProduct/" + idProduct, true);
xhttp.send();
};
};


in which it should send a request to the server and get the product but it does not show the alert.

I thought it was something related with the data response, but if I go directly to the link

http://localhost/product/loadProduct/7


I get the following response:

{"idProduct":"7","name":"product7"}


so I suspect that the AJAX function is not calling to this link because the response is being send correctly (if you access to it directly).


  • How can I know if the AJAX function is calling to the correct link?

  • Or is it an error with the AJAX function?



Thanks in advance!

Answer

You need to move your actual call outside of the onreadystatechange function:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
  if (xhttp.readyState == 4 && xhttp.status == 200) {
    var product = JSON.parse(xhttp.responseText);
  }
};
xhttp.open('GET', 'http://localhost/product/loadProduct/' + 1, true);
xhttp.send();