Can someone tell me a good way to debug my php + ajax scripts? I've got some php code that works fine if called directly, but not if called via Ajax. The flow: 1) Check if a cookie exists 2) If it doesn't, or it does but it's not in my database, create a new one 3) save some posted data to a table The code function createNewUser() { $uid = makeCookie(); setcookie('uid', $uid, $decadeFromNow); $query = 'INSERT INTO users (cookieid) VALUES ("'. $uid . '")'; if (!($result = mysql_query($query))) return 'failed to insert new user: ' . $query; $query = 'INSERT INTO notes (user, note, editor, lastupdate) VALUES ("' . mysql_insert_id(). '", "' . htmlentities($_POST[$_POST['editorName']]) . '", "' . $_POST['editorName'] . '", CURDATE())'; if (!($result = mysql_query($query))) return 'Could not insert notes for new user: ' . mysql_error(); } // check for the cookie if (!$_COOKIE['uid']) { createNewUser(); } else { // user exists, insert or update data // get user id $query = "SELECT user FROM users WHERE cookieid='" . $_COOKIE['uid'] . "'"; if (!($result = mysql_query($query))) return 'could not select user id: ' . $query . '<br>' . mysql_error(); if (mysql_num_rows($result) > 0) { $row = mysql_fetch_array($result, MYSQL_ASSOC); $query = 'UPDATE notes SET note = "' . htmlentities($_POST[$_POST['editorName']]) . '", ' . 'lastupdate = CURDATE() ' . 'WHERE user = ' . $row['user'] . ' AND ' . 'editor = "' . $_POST['editorName'] . '"'; if (!($result = mysql_query($query))) return 'Could not insert known user: ' . $query . '<br>' . mysql_error(); } else { // they have a cookie but are not in a table createNewUser(); } // make sure there was an affected row if (mysql_affected_rows() == 0) { // no prior not existed to edit, create the new one $query = 'INSERT INTO notes (user, note, editor, lastupdate) VALUES ("' . $row['user'] . '", "' . htmlentities($_POST[$_POST['editorName']]) . '", "' . $_POST['editorName'] . '", CURDATE())'; if (!($result = mysql_query($query))) return 'Could not insert notes for new user: ' . mysql_error(); } } return $result; } Code (markup):
I checked the error log, and the call to setcookie is at fault, so it looks like this is a problem on the php side of things, not the javascript. Any help would still be appreciated, but it looks like I'm in the wrong subforum.
If you're using Firefox, get the extension called Firebug. It greatly helps when coding. It can show you the entire structure of the page, all the files it loads, and shows AJAX requests and what's returned, etc. It will also point out JS errors when they occur.
Are you SURE it works fine when when called normally? How do you know it is not working, are you getting an error?