1

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...

2
  • 5
    This is a pretty vague question. People don't generally write manual ajax code anymore, they use a library or framework like jQuery to help them. I'd start by researching jQuery. Commented Aug 8, 2011 at 15:38
  • Also, your PHP application should send appropriate headers (Content-Type: application/json) in order for these frameworks suggested by @Jonathan to work. Commented Aug 8, 2011 at 15:41

1 Answer 1

4

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
   }
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for adding that link, Matt. I was going to link to it, but couldn't find it.

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.