I cannot display jSON data from a url in my browser using this script but I cannot find the source of the error.
The url (http://www.entertainmentcocktail.com/cp/index.php) contains what I understand is valid jSON data but there is nothing returned when I use this code:
<script type="text/javascript" src="cordova-2.3.0.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var output = $('#output');
$.ajax({
url: 'http://www.entertainmentcocktail.com/cp/index.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var name = '<h1>'+item.location+'</h1>'
+ '<p>'+item.id+'</br>';
output.append(name);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
</script>
EDIT: The target page with the jSON data generates the information from a database with this code:
<?php
header('Content-type: application/json');
$server = "SERVER";
$username = "USER";
$password = "PASS";
$database = "DB";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT id, name, location FROM table_name ORDER BY id";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . json_encode($records);
?>
Are you running this code from the same domain (www.entertainmentcocktail.com)? If not, you might be running into a XSRF issue.
What browser are you using to test? In Chrome you can right click and goto “Inspect Element” which then has a little red mark in the bottom right hand corner if there is a java script error. You should be able to find more information here.
http://cl.ly/image/261T3T360M34 – Screen shot of errors in bottom right hand corner.
How are you generating your json string? You should ideally use the built in PHP function:
http://php.net/manual/en/function.json-encode.php
Update:
From your comment, your issue is the ordering if your scripts. Change it to be like this: