2

I'm pretty new to ajax (via jQuery) and JavaScript. What I would like is to execute a php script periodically (and asynchronously) that fetches some SQL data. However I will present this data in a JavaScript graph, so I need it to get back into my JavaScript.

I tried an embedded php script inside the JavaScript that pushes the SQL data into an array, and then simply fetches the page itself with .ajax call, but this did not work (even though I could see in the page source that the JavaScript was changed, the graph did not respond to the changes):

ajax.php (not working):

$(function () {        
   function fetchData() {            
   $.ajax('ajax.php');
   <?php        
   try
   {
      $now = time();
      $query = "select * from jet_pressure;"        
      $result = $db->query($query);
      foreach ($result as $row)
      {                                      
         print "d1.push([".$row['timestamp'].",".$row['unknown']."]);";            
      }                                
   }
   catch (Exception $e)
   {
      print 'Exception : '.$e->getMessage();
   }
   ?>           
   $.plot($("#placeholder"), [ d1]);
   setTimeout(fetchData, 5000);
   }    
    setTimeout(fetchData, 500);    
   });       

What is the recommended way to do this?

2
  • not clear what exactly you are doing, if you want to update the contents of the placeholder using ajax then that line should be in the success: method of your ajax call. i recommend you to read ajax docs a bit on jquery.com Commented Jun 8, 2011 at 9:41
  • You are mixing server side php with client side script. The ajax.php is what can be run - the php in the middle of your script is only executed before the first time you load the page Commented Jun 8, 2011 at 9:43

2 Answers 2

3

I think you are mixing up your concepts. PHP only runs on the webserver. Javascript runs on the client (ie the web browser)

If you create a page with the .php extension as in your ajax.php, it will be served from you web server once and everything it contains that's a in the <?php ?> block will be parsed by the server - it not dynamic.

The resultant page contains parsed values from your php script, but not the script itself.

Javascript operates on the users computer, and therefore handles the user interaction and events on the web page. You can use Javascript to call a server script (in this case php) when you need to get data from the server. That is basically what AJAX is all about. But generally the javascript is contained in files ending .js which tend not to be parsed by your webserver, unless the javascript is actually included in your page, but that's not really how to do things these days.

I have no idea what you are tring to do by mixing javascript with php. This is not AJAX.

I suggest you use something like JSON. This rough php script first to compile your results into JSON, then the javascript ajax call. You'll need to have included the JQUERY library and save the whole php script as a seperate file called getdata.php.

<?php
// You'll have to do all the database select stuff here


    while ($Row = mysql_fetch_array($params)) 
{      
    $jsondata[]= array('jsobjectfield1'=>$Row["dbtablefield1"],
        'jsobjectfield2'=>$Row["dbtablefield2"],                       'jsobjectfield3'=>$Row["dbtablefield3"],                      'jsobjectfield4'=>$Row["dbtablefield4"]); 
};  
echo("{\"TableData\": ".json_encode($jsondata)."};");

?>

Javascript:

$.ajax({
    url: 'getdata.php',
    type: "POST",
    data: entereddata,
    dataType: "json",
    timeout: (7000),
    //wait 7 seconds          
    error: function(data)          
    {                     

    }, //end of ERROR handling          
    success: function(data)          
    {  
        // you'll find the data returned here:
    data.jsobjectfield1   
    }; // end of SUCCESS handling 

}); // end AJAXcall 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this works. But I think what I did should generate something similar, as I asynchronosly update the page itself (ajax.php) and therefore the server should re-genereate the php page, thereby filling it with new data. This is also what I saw when viewing page source. Well however didnt work so doesnt matter now.
0

HI I dont think you can do that directly.... If you want to pass data back and forth between PHP and JS u need to use xml http request .. you could find a very good tutorial that will help you a lot here ...... http://www.tizag.com/ajaxTutorial/ajaxxmlhttprequest.php hope that helps ... it sure helped me when I was starting .... I was trying to do the same thing that you are trying to do and then I knew that I was trying to mix up server and client side scripting

what you do here is following ....

1 pass a list of parameters to php

2 php does some processing (in your case query database) and echoes the desired output variables

3 that are returned to JS

If you are looking for direct code ... there you go .... the credit goes to the site I have mentioned above its not my code ... I really recommend you go to that site ... you will learn a lot in a short time .... hope that helps

<html>
<body>

<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
    var ajaxRequest;  // The variable that makes Ajax possible!

    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            document.myForm.time.value = ajaxRequest.responseText;
        }
    }
    ajaxRequest.open("GET", "serverTime.php", true);
    ajaxRequest.send(null); 
}

//-->
</script>



<form name='myForm'>
Name: <input type='text' onChange="ajaxFunction();" name='username' /> <br />
Time: <input type='text' name='time' />
</form>
</body>
</html>

serverTime.php

<?php
echo date("H:i:s"); 
?>

1 Comment

I agree. I'd forgotten about this site, techniques are explained very well, although now of course stuff like JQuery make life easier - but only if you understand the underlying concepts described by this site.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.