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