user2027231
user2027231

Reputation: 169

Advanced Call Php Function From Javascript

Here is my code.

<script>
  function test(div_id) {
    var newMail = '<?php echo count_new_mail($id); ?>';
    setTimeout(test, 10000);
  }
  test();
</script>        

What I want to do is call the php function count_new_mail every 10 seconds. When the javascript is made by the php the result looks like this.

var newMail = 1;

I know this is because it ran the php and count_new_mail gave a value of 1. How do I get this javascript to call the function every 10 seconds and not just keep the same value? Or will I have to write the php function as a javascript function and call that to get the results I want?

Upvotes: 0

Views: 171

Answers (1)

icktoofay
icktoofay

Reputation: 129109

PHP always works before the JavaScript, so the only way you can get JavaScript to get the PHP to run again is to start another request. JavaScript can start requests without going to a new page by using XMLHttpRequest, more commonly known as AJAX. The JavaScript code would look something like this:

// For old versions of Internet Explorer, you need to catch if this fails and use
// ActiveXObject to create an XMLHttpRequest.
var xhr = new XMLHttpRequest();
xhr.open("GET" /* or POST if it's more suitable */, "some/url.php", true);
xhr.send(null);  // replace null with POST data, if any

That'll send the request alright, but you probably want to get the resulting data, too. For that, you'll have to set up a callback (probably before you call send):

xhr.onreadystatechange = function() {
    // This function will be called whenever the state of the XHR object changes.
    // When readyState is 4, it has finished loading, and that's all we care
    // about.
    if(xhr.readyState === 4) {
        // Make sure there wasn't an HTTP error.
        if(xhr.status >= 200 && xhr.status < 300) {
            // It was retrieved successfully. Alert the result.
            alert(xhr.responseText);
        }else{
            // There was an error.
            alert("Oh darn, an error occurred.");
        }
    }
};

One thing to note is that send only starts the request; it does not wait until it has completed. Sometimes you'll have to restructure your code to accomodate that.

Upvotes: 3

Related Questions