Daniël van Dijken Daniël van Dijken - 3 months ago 15
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:

api.php:

$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
PDO
, but this is just for testing.)

The jquery script:

<script language="javascript" type="text/javascript">
$(function () {
$.ajax({
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() {
alert("Fail");
}
});
});
</script>


When I visit
api.php
this is what I get:

["161","true","werken\n","12"]


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 …]
0
:
Object
1
:
"parsererror"
2
:
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)
callee
:
(err)
length
:
3
Symbol(Symbol.iterator)
:
values()
__proto__
:
Object


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.

Edit:

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

Answer

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) {
                console.log(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.