AJAX + PHP = Not Updating MySQL DB ... code inside

The JAVASCRIPT I’m using:

<script type="text/javascript">

  function GetXmlHttpObject(){
  		if (window.XMLHttpRequest){
  		  // code for IE7+, Firefox, Chrome, Opera, Safari
  		  return new XMLHttpRequest();
  		  }
  		if (window.ActiveXObject){
  		  // code for IE6, IE5
  		  return new ActiveXObject("Microsoft.XMLHTTP");
  		  }
  		return null;
  }


	function rating(val){
		ratequest=GetXmlHttpObject();
		if (ratequest==null){
		  alert ("Your browser does not support AJAX!");
		  return;
		  }
		var url="rate_time.php";
		url=url+"?id=" + val;
    url=url+"&sid="+Math.random();
		ratequest.open("GET",url,true);
		ratequest.onreadystatechange = handleRequestStateChange;
		ratequest.send(null);
	}

</script>

As you can see it calls a .php file called rate_time.php … and that file is:


<?php
session_start();
include_once("db.php");
$id=mysql_real_escape_string($_GET['id']);
mysql_query("INSERT INTO log SET rating='1', book_id='$id'");
?>

db.php connects to the database.

I’m using the following HTML to call it:

<a href="#" onClick="rating(23)">1</a>

However the issue is that I cannot get the script to insert the rating into the MySQL DB.

I can run the rate_time.php file via the browser and it inserts everything, but just not via JS/AJAX.

Anyone see any errors in the coding?

Good first steps to debug.

Check the browsers error log.

Add some code to your php script which will log debugging statements to a file. This way you can see if the request is received by php, and if so, you can log messages to inspect the values of variables, and function return values to help you debug.

Optionally, use a browser addon or debugger (like firebug) to see what data is sent to the server.