Tutorial :JQuery Ajax bring in responses as they are created



Question:

I'm sending a post request to a php file that makes an MySQL query and iterates through the responses. During the iteration it echo's out a string that I want to bring into jquery one-by-one for each iteration.

So for each echo I would like one success value so that the user does not have to wait for all the iterations to finish.

The class compSelect is a select element.

I'd like for the option to be appended as the echo's come in msg by msg, not all in one msg.

Right now the msg on success looks like name1name2name3

I would like each msg to be an individual name.

The JavaScript

$.ajax({                 type: "POST",                 cache: false,                 url: "class.GetMiscInfo.php",                 data: "getNames=1&name=Jack",                 dataType: "html",                 success: function(msg) {                        $('.compSelect').append("<option value='" + msg +"'>" + msg +"</option>");                   }               });  

The PHP/MySql

class GetMiscInfo      {                  public static function getNames($name)          {              $res = mysql_query("SELECT names.name FROM names WHERE names.name='$name'");                while($row = mysql_fetch_assoc($res))              {                  echo $row['name'];              }          }             }        if(isset($_REQUEST['getNames']))          GetMiscInfo::getNames($_REQUEST['name']);  

I know I can separate them with a string like ~ and then just split the responses, but for more complicated queries I would like to not have to wait.

I think I'm just missing some knowledge related to Ajax to get what I want.


Solution:1

Instead of echoing out each name at each iteration, store them up in an array:

$data = array('names' => array());  while($row = mysql_fetch_assoc($res))  {      $data['names'][] = $row['name'];  }    // Once the loop has completed, `json_encode` the array and send it to the client  // optionally, set an 'error' offset if there is no data, or something bad happened  if(empty($data['names'])) {      $data['error'] = 'No data to return';  }  echo json_encode($data);  

Handle it on the client like this:

$.ajax({     type: "POST",     dataType: "json", // the data we are expecting is JSON     cache: false,     url: "class.GetMiscInfo.php",     data: "getNames=1&name=Jack",     success: function(json) {         if(json.error) {             alert('error: ' + json.error);         }         $.each(json.name, function(Index, val) {            $('.compSelect').append("<option value='" + val +"'>" + val +"</option>");         });     }   });  


Solution:2

What you are requesting is streaming data from the server. That is not the way jQuery architects it's AJAX methods. It's not the way most do for that matter.

With that said, what you doing is rather trivial in terms of data. I think streaming would be overkill. My suggestion would be to have the PHP script return JSON and change your jQuery code to use getJSON.

Check out the PHP JSON functions and jQuery's JSON methods.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »