0

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!

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

You are the best! Thank you very much! What a mistake!
2

Just open the console and check the request...

2 Comments

It is not being shown any AJAX call or maybe I am searching in the wrong place. I am using Google Chrome and go to Network tab.
Most browsers has a developer console you can use to see these thing. Here is Mozilla Firefoxs: link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.