Hi am using a Jquery to call a php script. The php script is located at http://localhost:8080/getData.php and it accesses a MySql database.
I am using a tomcat server setup on my pc with the server address of localhost:8080
I have looked at the ajax response data.status and it is 0
I have read about cross domain requests and know that this should not be a problem if i am using JSONp.
Any help would be much appreciated.
The jquery part inside of my HTML i use to call an ajax function is below:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type:'GET',
url:'http://localhost/getData.php',
datatype:'jsonp',
timeout: 5000,
success: function(data){
//data loaded
alert('loaded');
},
error: function(data){
// error on loading data
alert('error');
}
});
});
</script>
The actual getData.php code is below:
<?php
header('Content-type: application/json');
$server = "127.0.0.1";
$username = "root";
$password = "";
$database = "deals";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT area_id, name AS area_name, sector AS area_sector FROM deals.areas ORDER BY name";
$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) . ');';
?>
I’m seeing three issues:
Your PHP script is looking for a GET parameter called
jsoncallback, but that’s not the name that jQuery sends by default, which iscallback. Either change your PHP to usecallbackinstead:…or add this option to your
ajaxcall to tell jQuery to usejsoncallbackinstead:You can use the Network tab in your browser’s development tools to inspect the call and see what the query string looks like, to make sure they match up.
You have a typo in your ajax options, you have
datatype:'jsonp'instead ofdataType:'jsonp'(theTindataTypemust be upper case), so jQuery won’t have been trying to do a JSON-P call at all, it will have tried XHR.You’ve said in your question that the PHP page is at
http://localhost:8080/getData.php, but theurlyou’ve given jQuery ishttp://localhost/getData.php(without the port).