Luke Danger Kozorosky
Luke Danger Kozorosky

Reputation: 226

Sending PHP variables to JavaScript through AJAX

I'm writing a program that will generate random numbers on both JavaScript and PHP pages and display them on the JavaScript/Html page.

So far I have both pages successfully generating the numbers, but I don't know how to reach out from the JavaScript page to the external PHP page to retrieve the number and store it into a JS variable.

Here's what I have so far.

JavaScript:

function roll()
    {
        var rollOne; //= Math.floor((Math.random() * 6) + 1);
        var rollTwo;
        var request = new XMLHttpRequest();

        request.open("GET", "filename.php", true);
        request.send();                 
    }

I know the JS random is commented out, that's not important right now.

PHP:

<?php
    sleep(5);
    $random =(rand(1,6));
    echo $random;
?>

So how do I take $random from the php document, send it over to the JavaScript page, and store it into a variable to access later?

I'm sure a similar question has been asked thousands of times before on this site, but from what I have searched I haven't found anything that made sense to me.

Upvotes: 1

Views: 111

Answers (2)

Matt S
Matt S

Reputation: 15394

The Mozilla docs on AJAX explain it well. Before calling .open and .send, set up a function for XMLHttpRequest to run when the response comes back from the server:

request.onreadystatechange = function() {
  if (request.readyState === XMLHttpRequest.DONE) {
    // The request is complete
    if (request.status === 200) {
      // Server responded with HTTP status code 200 (OK)
      // Here's your server's random value
      random = request.responseText;
    } else {
      alert('There was a problem with the request.');
    }
  }
}

Upvotes: 2

asugrue15
asugrue15

Reputation: 65

You can access the responseText value of the returned data. In other words, the data that you echo from php can be accessed in your javascript using responseText and stored in a variable.

Upvotes: 0

Related Questions