Solved

Update variable without page refresh?

Posted on 2011-03-14
7
963 Views
Last Modified: 2013-12-13
Hi there,

i have a page in php, that had a iframe that load's a page in perl. I have a mysql db that have one field call page that could 0 or 1.

If its 0 show the perl page if its 1 show a html page.

How to check this variable in the php page without refreshing the page or the iframe?

Best regards.
0
Comment
Question by:AndreMarques
  • 5
  • 2
7 Comments
 
LVL 11

Expert Comment

by:patsmitty
Comment Utility
Via AJAX. You want to have a separate php script (not page) that connects to the database and queries for that value and call it ajax.php. Then echo the value at the end of the script. Now in your main php page where you want to check w/o reloading, add this JavaScript at the end of your page just inside the </body> tag:
function doAjax() {
                            var url = "ajax.php";
                            var xmlhttp;
                            if (window.XMLHttpRequest)
                            {
                                // code for IE7+, Firefox, Chrome, Opera, Safari
                                xmlhttp=new XMLHttpRequest();
                            }
                            else if (window.ActiveXObject)
                            {
                                // code for IE6, IE5
                                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                            }
                            else
                            {
                                alert("Your browser does not support XMLHTTP!");
                            }
                            xmlhttp.onreadystatechange=function() {
                                if(xmlhttp.readyState==4)
                                {
                                   var val = xmlhttp.responseText;
                                   // val is your variable from the database
                                }
                            }
                            xmlhttp.open("GET", url, true);
                            xmlhttp.send(null);
                        }

Open in new window


On line 21, the variable var is the value from your database. You can return that there and then call the function anywhere in your php page to retrieve that value whenever you want. No page reloading or anything   :)
0
 
LVL 11

Expert Comment

by:patsmitty
Comment Utility
Here is a really good reference for what you are doing here: http://www.w3schools.com/PHP/php_ajax_database.asp

HTH
0
 

Author Comment

by:AndreMarques
Comment Utility
Ok,

but that script in ajax, ill do the refresh in how many minutes? what i have to do in the ajax.php? just check the variable?

0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 11

Expert Comment

by:patsmitty
Comment Utility
Yeah - when do you want to check? When the user clicks a button - or every so often or what?
0
 

Author Comment

by:AndreMarques
Comment Utility
every 5 seconds per example.
0
 
LVL 11

Expert Comment

by:patsmitty
Comment Utility
I'm away from my desk at the moment, but look into the setInterval function for JavaScript. It looks something like "setInterval('doAjax()', 5000);". But I'll post some example code when I get back to my desk. Cheers
0
 
LVL 11

Accepted Solution

by:
patsmitty earned 500 total points
Comment Utility
The contents of your ajax.php file should look like this:
 
<?php

$dbVar = null;
mysql_connect('db_server', 'db_user', 'db_pw') OR DIE('Unable to connect to database! Please try again later.');
mysql_select_db('db_name');
$sql = "SELECT perl_or_html FROM table";
$result = mysql_query($sql) or exit("QUERY FAILED!" . mysql_error());
if ($result):
    while ($row = mysql_fetch_array($result)):
        $o = $row['perl_or_html'];
    endwhile;
endif;
echo($dbVar);
?>

Open in new window


The following page checks the db every 10 seconds and stores the variable from the database into a JavaScript variable called 'dbVar' and then shows an alert box of the variable:
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>EE :: AJAX Example</title>
        <script type="text/javascript">
            var dbVar = null;
            setInterval("doAjax()", 10000);
        </script>
    </head>
    <body>
        <h2>An alert box with the variable from the database should pop-up every 10 seconds.</h2>
        <script type="text/javascript">
            function doAjax() {
                var url = "ajax.php";
                var xmlhttp;
                if (window.XMLHttpRequest)
                {
                    // code for IE7+, Firefox, Chrome, Opera, Safari
                    xmlhttp=new XMLHttpRequest();
                }
                else if (window.ActiveXObject)
                {
                    // code for IE6, IE5
                    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
                else
                {
                    alert("Your browser does not support XMLHTTP!");
                }
                xmlhttp.onreadystatechange=function() {
                    if(xmlhttp.readyState==4)
                    {
                        dbVar = xmlhttp.responseText;
                        alert(dbVar);
                    }
                }
                xmlhttp.open("GET", url, true);
                xmlhttp.send(null);
            }
        </script>
    </body>
</html>

Open in new window


Instead of showing the alert box, you'll want to do an IF statement to show the html or perl page.

Hope this is what you need...
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses how to create an extensible mechanism for linked drop downs.
In this tutorial viewers will learn how to embed an audio file in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: : The declaration should display (CODE) HTML5 is supported by the most recent versions of all major browsers…
The viewer will the learn the benefit of plain text editors and code an HTML5 based template for use in further tutorials.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now