Reputation: 153
I have the following problem. I have a PHP File, which should give me a JSON Object so I can display it in my HTML File. This works perfectly, I receive a output, which looks like a JSON Object, but although I will post the PHP File here:
<?php
header('Content-Type: application/json');
$erg = array (
"London" => array(
"Wetter" => "Regnerisch",
"Grad" => 12
),
"Manchester" => array(
"Wetter" =>"Sonnig",
"Grad" => 15
),
"Cambridge" => array(
"Wetter" => "Bewoelkt",
"Grad" => 5
)
);
echo json_encode($erg, JSON_PRETTY_PRINT);
?>
I have read something about $.ajax, but I don´t know if I can use it like this:
$(document).ready(function() {
var newHtml;
$.ajax({
url: 'Server2.php',
type: 'get',
cache:false,
success: function(json) {
$.each(json,function(i, item) {
newHtml += '<div>' + item.Wetter + '</div>'
})
$('#inhalt').html(newHtml);
}
});
});
But when I try to display it in the browser, I receive the following error:
So I want just to display the output of the PHP File in a div, which I insert into my div with the id inhalt in my HTML document.
I appreciate every help from you guys.
Upvotes: 1
Views: 87
Reputation: 605
Just tested this code. Try this code for the jQuery part:
$(document).ready(function() {
var newHtml;
$.ajax({
type: 'GET',
dataType: 'json',
url: 'Server2.php',
complete: function( json ){
//$.each( json.responseJSON, function(i, item) {
// newHtml += '<div>' + item.Wetter + '</div>'
//});
// Try this for the keys
for(var key in json.responseJSON) {
newHtml += '<div>' + key + '</div>'
}
$( '#inhalt' ).html( newHtml );
}
});
});
More Info
if you want to get the key and the Wetter
key for each location then try this
for(var key in json.responseJSON ) {
var wetter = json.responseJSON[ key ].Wetter,
grad = json.responseJSON[ key ].Grad;
// You can now use the wetter and grad vars wherever you want inside this function
newHtml += '<div>' + key + '</div>'
}
Upvotes: 2
Reputation: 2884
I see that the ajax response contains the entire PHP file, this means there could one of the two possible issues here -
It seems like you're not running the html file via apache. What's the URL in your browser? Does it start with file://C:/www/html/test.html
, if so you should load that file via Apache, so should be something like http://localhost/test.html
Apache is not parsing PHP files, in which case you need the php module installed. You might want to install/enable the php module but since you said the response is being received, I'd say you have it installed.
Can you tell me what URL you are typing to access the html page in the browser? In addition please check the Network tab in Chrome to see the AJAX call in realtime.
Upvotes: 1