Reputation: 1052
I am trying to show this json data in a javascript alert box, but it shows it twice (same content). It is working, but I do not know why it is displaying two alerts. (javascript is not my preferred language).
This is the response from the URL called:
{
"type": "error",
"response": {
"message": "Could not start app"
}
}
This is the code I am using:
<script type="text/javascript">
function call() {
const Http = new XMLHttpRequest();
const url='https://url_to_get_the_response';
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
if (Http.responseText) {
alert(Http.responseText);
}
}
}
</script>
And I get two alerts, both containing the same thing (the .json result). I only want one of them.
I have tried adding a return;
and break call;
in the if (Http.responseText)
section. Adding the return;
in the if
statement didn't do anything and adding the break call;
stopped it working.
Any advice on this? Thanks.
Upvotes: 0
Views: 966
Reputation: 365
You approach is correct. onreadystatechange
event is triggered multiple times, as the readyState
attribute changes from the beginning to the end of an API call.
On adding if condition for the appropriate readyState
and status
value that comes in the XMLHttpRequest
Object. Solves this issue.
You can read more about those attributes here readyState, status
function call() {
const Http = new XMLHttpRequest();
const url='https://jsonplaceholder.typicode.com/todos/1';
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
if (Http.readyState == 4 && Http.status == 200 && Http.responseText) {
alert(Http.responseText);
}
}
}
<button onclick='call()'>Call</button>
Upvotes: 2