I have a ajax connection to my json.php file and its not working... do you have any idea what is going on? is it my $output variable is it not convertible to json can it be my ajax?! any help will be greatly appreciated. PS: when i click on a city that does not exist.. it does output the $output variable.When i click on a city that doe exist I get nothing. It`s killing me. var_dump($output) {if it is not encoded} is:
array (size=1)
0 =>
array (size=4)
0 =>
object(SimpleXMLElement)[9]
1 =>
object(SimpleXMLElement)[8]
2 =>
object(SimpleXMLElement)[7]
3 =>
object(SimpleXMLElement)[10]
json.php file:
<?php
if(isset($_POST['city'])){
$city = $_POST['city']; //checks if variable city is set if not it will be set as default
var_dump($city);
}else{
$city = 'New York';
}
//loads data as simple xml
$result = "http://api.wunderground.com/api/KEY/geolookup/conditions/q/ro/$city.xml";
$xml = simplexml_load_file($result);
#echo htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
$place = $xml->location->city; //gets the city name
#var_dump($place);
if(!empty($place)){ //checks if city exits
foreach($xml->current_observation as $item){
$current = (string)$item->weather;
$temperature = (string)$item->temp_c;
$time = (string)$item->local_time_rfc822;
$wind = (string)$item->wind_string;
$humidity = (string)$item->relative_humidity;
$output[] = array($time, $temperature, $current, $wind);
}
}
}else{
$output = 'No results found, please try a different city.'; //if variable $place is empty it will print this
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('data' => $output),true);
?>
And jQuery file:
$(document).ready(function() {
$('li').click(function(){
var city = $(this).text(); //get the li content as variable city
$.ajax({
type : 'POST', //sending data method
url : 'json.php',
data : {city:city}, //data to be sent
dataType: 'json',
success : function(data){
$("#result").html(data);
}
});
});
});
EDIT 1: I have updated my code in such a way that my output is json encoded and equal to
{"data":[["Thu, 24 Sep 2015 02:00:58 +0300","19.3","Clear","From the West at 1.6 MPH Gusting to 2.5 MPH"]]}
I think the problem now is in my AJAX(I am a new user of jQuery) I get no info printed when I Click on a city.
Take a look at the following tutorial: https://lostechies.com/seanbiefeld/2011/10/21/simple-xml-to-json-with-php/
You'll do str_replace
and trim
then encode the data for the web.
Many Times it occurs when our content of the array is not Encoded. Generally we use UTF-8 Encoding.
So, To Solve this issue you need to add this,
mysqli_set_charset($con, 'utf8');
Just after the connection.