2

I have a mysql database that stores data such as usernames. I have a PHP file called result which retrieves the results from the database and encodes them into a JSON string. I then want the same PHP file to output the results without a page reload (via ajax). Effectively I want the same page to get the JSON string as a HTTP request, how do I go about this

this is results.php so far

            <?php

        $link = mysql_connect('', '', '');
        if (!$link) {
            die('Could not connect: ' . mysql_error());
        }

        $db_selected = mysql_select_db('test', $link);
        if (!$db_selected) {
            die ('Can\'t use test : ' . mysql_error());
        }

        $result = mysql_query("SELECT user_name FROM users");
        if (!$result) {
            die('Invalid query: ' . mysql_error());
        }


        $names = array();

        while ($row = mysql_fetch_assoc($result)) {

            foreach ($row as $key => $val) {

                $names[][$key] = $val;
            }
        }

        if ($_GET['myvar'] == "done")
        {
            $ennames = json_encode($names);
            echo $ennames;
            exit();
        }




        ?>
         <script src="jquery-1.7.1.min.js">

         function getJSON()
         {
            $.getJSON("results.php", { myvar: "done" }, function(data) {
               var namesHTML = "";

               $.each(data, function(key, val) {
                   namesHTML = namesHTML + val + "<br/>";
                 });

               $("#divForNames").html(namesHTML);
            });
            setTimeOut(getJSON, 5000); //the 5000 here means 5 seconds
         }
        </script>

         <div id="divForNames">

         </div>

1 Answer 1

2

The only adjustment that your PHP will need for this is to add an if statement immediately after the assignment of $ennames:

if ($_GET['myvar'] == "specific-value-that-you-choose")
{
   echo $ennames;
   exit();
}

For the polling, you will need to do some kind of client-side script - most likely javascript, and most easily written in jQuery. Look into the .getJSON() jQuery function and the setTimeOut() to create logic to do this polling. It will probably look something like this:

function getJSON()
{
   $.getJSON("result.php", { myvar: "specific-value-that-you-choose" }, function(data) {
      var namesHTML = "";

      $.each(data, function(key, val) {
          namesHTML = namesHTML + val + "<br/>";
        });

      $("#divForNames").html(namesHTML);
   });
   setTimeOut(getJSON, 5000); //the 5000 here means 5 seconds
}

Then somewhere in the HTML for the non-JSON page, you need to include a <div> with the id set to match the one you using inside the $.getJSON() function (in this case, I'd need an empty <div id="divForNames"> but you can change the names to fit your preferences.

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

5 Comments

what is myvar all about? what would I pass in that varible?
myvar is just a variable you can use to pass data to the php page. You could use this to adjust what results are given in the output. If there is nothing that you need to pass, then just pick some value to indicate that you want to render JSON instead of HTML. So instead of myvar, you might use renderMethod and instead of "specific-value-that-you-choose" you might use "JSON"
I am going to edit my question to better explain what I am trying to acheive
Still not working, I am going to edit my question again with the changes I have added from your edit.
You need to call the getJSON(); function somewhere in the javascript in order for it to start polling. Beyond that, add in some alert("abcd"); messages for debugging to see where the execution is failing; replacing "abcd" in that with variables to check their values at different points.

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.