0

I have a div that calls a variable. When that variable changes, users need to refresh the page to see the new value. The variable is pulled from a separate PHP file.

I'm wondering if there's a way to use ajax to automatically update the div without the user refreshing the browser when it sees the PHP variable has been updated.

2
  • I assume by "calls a variable" you mean "displays the result of some calculation". This is basically what every AJAX script is for: ask the server for the result of some calculation, and update something on the page based on the result. Commented Mar 29, 2013 at 1:10
  • If something changes on server side and user should know about that you should periodically "ask" server for update and then let user know if last two results are different. So yes, it's possible:) Commented Mar 29, 2013 at 1:11

1 Answer 1

3

You could periodically check if there have been any change to the variable using ajax and if that is the case you could update the div.

var previousValue = null;

function checkForChange() {
    $.ajax({
        url: 'http://example.com/getVariableValue.php',
        ...
        success: function(data) {
            if (data != previousValue) { // Something have changed!
                //Call function to update div
                previousValue = data;
            }
        }
    });
}

setInterval("checkForChange();", 1000);

I havn't tested the code, but it should be something like that. Will get data from http://example.com/getVariableValue.php, you'll have to fill in some information about the AJAX request. I'm assuming you know how to modify the code for your specific data format, be it XML, JSON or text.

Sign up to request clarification or add additional context in comments.

4 Comments

This is exactly what I would need! I'm very new to ajax though, so I'm not sure how to format the data. The variable is a plain-text value though. Also, what code would I use to update the div? thank you for your time
If your data is plaintext then you should use dataType: 'html', as for updating the actual div you should have a look at selectors (api.jquery.com/category/selectors) and the html() method in jQUery (api.jquery.com/html). Check out the jQuery API, it's a great reference with examples and detailed descriptions.
Thanks very much for the start :) My rep isn't high enough to give you points, but thank you!
Just for your info, I got this working rather easily after some minor research! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.