-1

I don't want to seem like I haven't done my research. I was using this as an example: Pass arguments into ajax onreadystatechange callback?

However, I'm afraid my problem is with defining the new function. I was not sure how to even search for this problem, so I decided to ask instead.

Thanks.

The following is saying that doSomething is not a function when I call getOwnerList(). The goal is to have getData() be reusable, and to pass any function I want to act upon the data.

function updateOwnerList(data) {
    alert(data);
    return;
}

function getOwnerList() {
    getData(updateOwnerList, "getOwnerList.php");
}

function getData(doSomething, url) {
    var ajax = new XMLHttpRequest();

    ajax.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            var data = JSON.parse(this.responseText);
            console.log(data);
            doSomething(data);
        }
    }
    ajax.open("GET", "getOwnerList.php", true);
    ajax.send();
}

Edit: Actually, the response does come as expected. When I print the data, it is what I wanted it to be. The problem is when I call doSomething() inside or outside of the onreadystatechange function, it says that the function doSomething() does not exist.

  • Can you show the `doSomething` function? – Andrew Apr 07 '18 at 23:52
  • Do something is just the function that gets passed. Inside of getOwnerList() I pass a function to it. Am I doing that wrong? The goal is to have getData() be reusable, and allow me to pass any function to it. – Cody Lakin Apr 07 '18 at 23:54

1 Answers1

0

It's not an error with the passing of the function. The function passes properly and does what it is asked to do. Make sure your ajax call get the correct response.check the following console logs. It doesn't log the string in if (this.readyState == 4 && this.status == 200) { block, which means it's status is not 200 or readyState is not 4.(In this example that makes sense since we don't have the "getOwnerList.php" file). I guess in your case also it could be the problem. Check whether you actually get the response.

function updateOwnerList(data) {
    alert(data);
    return;
}

function getOwnerList() {
    getData(updateOwnerList, "getOwnerList.php");
}

function getData(doSomething, url) {
    doSomething('I\'m ok');
    var ajax = new XMLHttpRequest();

    ajax.onreadystatechange = function () {
        console.log('I came here');
        if (this.readyState == 4 && this.status == 200) {
            console.log('I came here too!');
            var data = JSON.parse(this.responseText);
            console.log(data);
            doSomething(data);
        } else {
            console.log("Something wrong");
        }
    }
    ajax.open("GET", "getOwnerList.php", true);
    ajax.send();
}

getOwnerList();
Kavindra
  • 1,697
  • 2
  • 14
  • 19