user559142
user559142

Reputation: 12517

Javascript, AJAX and PHP Help

I have the following table in a MYSQL database:

Messages
MessageId (PK) int(10) - auto_inc
Message varchar(100)

I have the following PHP that echos a particular message:

<?php

//..connect to database
$query = "SELECT Message FROM Messages WHERE MessageId = '1'";
$result = mysql_query($query);
$num = mysql_num_rows( $result );
if ($num == 1){
  $row = mysql_fetch_assoc($result);
  echo json_encode($row);
}else{
  echo('Invalid');
}

?>

Can anyone advise me on how best to integrate jQuery in order to allow the document browser window to write the response...

Upvotes: 1

Views: 89

Answers (1)

Kyle
Kyle

Reputation: 4449

If you use jQuery, you can easily use jQuery.getJSON()[DOCS] as follows:

$.getJSON('mypage.php', function(data) { 
   //Do somewith with JSON data
});

For normal Javascript, use

var xmlhttp;
if(window.XMLHttpRequest)
   xmlhttp = new XMLHttpRequest();
else//IE5, IE6
   xmlhttp = ActiveXObject("Microsoft.XMLHTTP");

xmlhttp.onreadystatechange = function()
{
   if(xmlhttp.readyState == 4 && xmlhttp.Status == 200)
   {
      var response = JSON.parse(xmlhttp.responseText);
      //Do something with JSON Data
   }
};

Upvotes: 4

Related Questions