Daniël van Dijken Daniël van Dijken - 1 year ago 98
Ajax Question

Ajax jquery post script not working

I am following this tutorial https://openenergymonitor.org/emon/node/107.
What i am trying to do is, use jquery and php to get data from a mysql database.
I exactly did what the tutorial said, but I am unable to make it work.
I get the fail alert when I load the page.

This is what I did:


$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");

$selected = mysql_select_db($db,$dbhandle)
or die("Could not select examples");

$result = mysql_query("SELECT * FROM todolist");
$array = mysql_fetch_row($result);

echo json_encode($array);

(I know that it is better to use
, but this is just for testing.)

The jquery script:

<script language="javascript" type="text/javascript">
$(function () {
url: 'api.php', data: "", dataType: 'json',
success: function(data) {
var id = data[0];
var description = data[1];
$('#output').html("<b>id: </b>"+id+"<b> description: </b>"+description);
error: function() {

When I visit
this is what I get:


when i use console.log(arguments) this shows up:

[Object, "parsererror", SyntaxError: Unexpected token < in JSON at position 0 at Object.parse (native) at parseJSON …]
SyntaxError: Unexpected token < in JSON at position 0 at Object.parse (native) at parseJSON (https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js:16:11709) at b$ (https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js:16:1382) at w (https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js:18:8326) at XMLHttpRequest.d (https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js:18:14247)

I am trying to make this work for about 3 hours now, and it drives me pretty crazy. I hope someone can explain the problem with my script.


I fixed it. There was a problem with a page i included in api.php.

Answer Source

It's probably because of the url not using absolute path. Are you running this on your local machine ? Are the 2 scripts (html and php) on the same directory ?

You should try to use the Developer Tool of your browser to check and track the network ajax call. You're probably getting a 404 error.

You could get more info on the error by doing this :

error: function(err) {

The details of the errors will appear on your developer tool console. Most of the time, opening the developer tools is done by pressing Ctrl+Shift+I on PC, or by using browser menu.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download