I\'m trying to get data from data.php
via jQuery ajax call.
My code looks like this:
var jsonData;
$.ajax({
url: \'data.php\',
PHP
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->query('SET NAMES utf8;');
$stmt = $dbh->prepare($sql);
//$stmt->bindParam("id", $_GET[id]);
$stmt->execute();
$advice = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo '{"items":'. json_encode($advice) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
Ajax
var temp;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: serviceurl,
data: "{'userName':'" + userName + "' , 'password': '" + password
+ "'}",
dataType: "json",
success: function(msg) {
temp = jQuery.parseJSON(msg.d);
},
error: function(xhr, ajaxOptions, thrownError) {}
});
You should be using header()
function in your PHP
to set the proper response header (content type and charset):
header('Content-type: application/json; charset=UTF-8');
You should also repeat this at the top of HTML pages:
<meta http-equiv="Content-type" value="text/html; charset=UTF-8" />
See also:
PHP UTF-8 cheatsheet
Try to put dataType: 'json'
in you ajax call:
var jsonData;
$.ajax({
url: 'data.php',
dataType: 'json',
success: function(response) {
jsonData = response;
}
});
Also you can use this mechanism:
$.getJSON( "data.php", function( response ) {
jsonData = response;
});
It is more clean if you want get only JSON :)
data.php
header('Content-type: application/json');
and
$.ajax({
url: 'data.php',
dataType: 'json',
success: function(response) {
jsonData = response;
}
});