I'm doing an ajax post with jQuery to a php file and am trying to get the success function data to come in correctly. Here are my files:
JAVASCRIPT
$.ajax({ url: "ajax/chart-kpi-trend.php",
data: {
data_kpi: kpi,
data_goal: goal,
data_year: year,
data_month: month
},
type: 'POST',
success: function(data) {
alert(data);
},
error: function() {
alert('error');
}
});
PHP
$goal = $_POST["data_goal"];
$kpi = $_POST["data_kpi"];
$year = $_POST["data_year"];
$month = $_POST["data_month"];
$return = array(
goal => $goal,
kpi => $kpi,
year => $year,
month => $month
);
echo json_encode($return);
Now the success function is called, however the data passed into it is this...
<html>
<head>
<meta name="author" content="Kai Oswald Seidler">
<meta http-equiv="cache-control" content="no-cache">
<title>XAMPP for Mac OS X 1.7.3</title>
<frameset rows="74,*" marginwidth="0" marginheight="0" frameborder="0" border="0" borderwidth="0">
<frame name="head" src="head.php" scrolling=no>
<frameset cols="150,*" marginwidth="0" marginheight="0" frameborder="0" border="0" borderwidth="0">
<frame name="navi" src="navi.php" scrolling=no>
<frame name="content" src="start.php" marginwidth=20>
</frameset>
</frameset>
</head>
<body bgcolor=#ffffff>
</body>
</html>
Which is completely different from the array I've constructed in the PHP file. I'm developing on localhost with XAMPP, could that be a problem, or is it somewhere in my code?
Cheers!
If your PHP file is located at www.yourdomain.com/ajax/chart-kpi-trend.php then you need to add another leading / to the URL in your Jquery ajax request, so your javascript would be:
$.ajax({ url: "/ajax/chart-kpi-trend.php",
data: {
data_kpi: kpi,
data_goal: goal,
data_year: year,
data_month: month
},
type: 'POST',
success: function(data) {
alert(data);
},
error: function() {
alert('error');
}
});
Without the leading / the Javascript is looking for www.yourdomain.com/whereverYourJavascriptIs/ajax/chart-kpi-trend.php. Looks like your XAMPP is just catching the fact that there is no page found at the URL that it is being given and showing a generic XAMPP page. That is why you are getting back that information (the page's html) instead of the information that you expected to receive.
$.ajax({ url: "ajax/chart-kpi-trend.php",
data: {
data_kpi: kpi,
data_goal: goal,
data_year: year,
data_month: month
},
type: 'POST',
dataType: 'JSON',
success: function(data) {
alert(data);
},
error: function() {
alert('error');
}
});
if you called the correct URL, just add the "dataType: json" parameter in ajax object to ge the json response
try something like this
$return = array(
'goal' => $goal,
'kpi' => $kpi,
'year' => $year,
'month'=> $month
);
echo json_encode($return);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.