ChainFuse
ChainFuse

Reputation: 827

How to print JavaScript based on Ajax request?

Allow me to elaborate. I have this Ajax script which is fetching for one thing. The refresh_on. What does it do? It either returns 0 OR 1.

 function startRefresh() {
        setTimeout(startRefresh, 60000);
        $.ajax({
            url: 'refresh.php',
            type: 'POST',
            dataType: 'JSON',
            data: {task: "reload"},
            success: function(data) {
                $.each(data, function(i, attr){
                    if (attr.refresh_on == 0) {
                        //this doesn't work 
                        /*Write/return this in JavaScript:*/ line[1]="Offline.";
                    } else {
                        //this doesn't work
                        /*Write/return this in JavaScript:*/ line[1]="Online.";
                    };
                })
            }
        });
    }

If the ajax returns with refresh_on == 0 OR refresh_on == 1 - I want it to print its respective array item. It must be an array item.

</head>
  <body>
    <script type="text/javascript">
      var line=new Array()
      startRefresh();
      //output either "line[1]=\"Offline.\""; or "line[1]=\"Online.\"";
    </script>
  </body>

This is the PHP file:

if (isset($_POST['task']) && $_POST['task'] == "reload") {
    $stmt = $connection->prepare("SELECT refresh_on FROM refresh");
    $stmt->execute();

    $result = $stmt->get_result();

    $encode = Array();
    while ($row = $result->fetch_assoc()) {
        $encode[] = $row;
    }
    echo json_encode($encode);  
}

If it matters - this is the JSON response:

[{"refresh_on":1}]

Is there a way to insert/output/print the array item using the function?

Any help would be appreciated.

Upvotes: 1

Views: 181

Answers (2)

James Lai
James Lai

Reputation: 2071

So there's a couple things that might be going on here, but to begin, you're wrapping your variable in a quote, so all that is happening is a string is being made and immediately being dropped to the floor. Let's start off by doing something like the following:

 function startRefresh() {
        setTimeout(startRefresh, 60000);
        $.ajax({
            url: 'refresh.php',
            type: 'POST',
            dataType: 'JSON',
            data: {task: "reload"},
            success: function(data) {
                $.each(data, function(i, attr){
                    if (attr.refresh_on == 0) {
                        //this doesn't work 
                        line[1] = "Offline.";
                    } else {
                        //this doesn't work
                        line[1]= "Online.";
                    };
                })
            }
        });
    }

Now, if I recall correctly, the ajax function is going to be calling your success callback, which is going to take over your local scope. I don't believe line is going to be accessible to that callback, so we should/could actually move that callback to its own function within a closure:

<script type="text/javascript">

(function() {                                                                                                                                                                                                                      

  var line = []; 
  startRefresh();

  function startRefresh() {
    setTimeout(startRefresh, 60000);
    $.ajax({
      url: 'refresh.php',
      type: 'POST',
      dataType: 'JSON',
      data: { task: "reload" },
      success: refreshResponse
    }); 
  }

  function refreshResponse(data) {
    $.each(data, function(i, attr) {
      if (attr.refresh_on == 0) {
        line[1] = "Offline.";
      } else {
        line[1] = "Online.";
      }   
    }); 
  }

})();

</script>

We've wrapped that in a self executing function to give us some nice encapsulation to work with, and because line is in a function which refreshResponse is found, that variable should be accessible to it.

But we're not done yet!

For one, we could easily make that variable assignment a little easier, like so:

line[1] = (attr.refresh_on == 0) ? "Offline." : "Online.";

...and we're also going to want to triple up on that equality statement, just to avoid variable coercion:

line[1] = (attr.refresh_on === 0) ? "Offline." : "Online.";

Give that a shot and let's see where we're at.

Upvotes: 1

Rob M.
Rob M.

Reputation: 36521

Not sure what you are expecting "line[1]=\"Offline.\""; to do, but it's not going to do anything. Perhaps you mean: line[1]= "Offline";? Try putting this line of code there instead to test that it's working: console.log('Offline');

If the line is getting executed and you see the output in your console, you would just have to target some HTML element that you want to put the "Offline" string into, for instance:

<div id="status"></div>
<script>
....
var status = document.getElementById("status");
if (attr.refresh_on == 0) {
   status.textContent = "Offline";
} else {
    status.textContent = "Online";
};
....
</script>

Upvotes: 0

Related Questions