TheBandit
TheBandit

Reputation: 109

Ajax call failing

I am using Ajax to send information to a server and return a JSON string. This is the code I am using:

function getRequests(folder, mode) {
xhr = new XMLHttpRequest();
xhr.onreadystatechange = singleBook(folder, mode);
xhr.open("GET", "bestreads.php?mode=" + mode + "&title=" + folder, true);
xhr.send(null);
}

function singleBook(folder, mode) {
alert(xhr.responseText);
if (mode == "info") {
    var json = JSON.parse(xhr.responseText);
}
}

I have tested my PHP script and I am 100% certain that it properly prints out the correct JSON string for every possible folder name. I have validated the JSON string it creates to confirm this. However, this code leaves xhr completely empty. I have tried checking the status with xhr.stats but it returns 0, which doesn't make sense to me since I thought it is supposed to return 404 or 200.

This is a school project and I am not allowed to use JQuery, so I need a solution to this that does not use it. I make an Ajax call earlier in my call the same way and it works without any issues, but returns an XML string instead of JSON which makes me think I need to do something else to return the JSON string, but I have no idea what that may be.

PHP code:

function createJson($folder) {
$path = "books/" . $folder . "/info.txt";
$infoFile = file($path);
$info = '{"title":"' . $infoFile[0] . '","author":"' . $infoFile[1] . '","stars":"' . $infoFile[2] . '"}';
print $info;
}

Upvotes: 0

Views: 57

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You need to assign a function reference to onreadystatechange instead you are invoking the singleBook function and is assigning the value returned by that to onreadystatechange.

Also need to wait for the ajax request before processing it

function getRequests(folder, mode) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = singleBook(xhr, folder, mode);
  xhr.open("GET", "bestreads.php?mode=" + mode + "&title=" + folder, true);
  xhr.send(null);
}

function singleBook(xhr, folder, mode) {
  return function() {
    if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
      console.log(xhr.responseText);
      if (mode == "info") {
        var json = JSON.parse(xhr.responseText);
      }
    }
  }
}

Upvotes: 2

Related Questions