In this project I try to use a url in Javascript in main php to Ajax to a backend php call getWeather.php. And it will get the data from the url and return it to Javascript However I keep losing variable (undefined) after Ajax post. So I print out the result to see, and I found out the Ajax return value is not finish yet when I try to assign the php return result to a Javascript variable.
In my script when a button is click:
function post (inputString) {
var result;
var url ="http://api.openweathermap.org/data/2.5/weather?lat=42.5559287&lon=-92.84954249999998&lang=en&units=metric&appid=MY_API_KEY";
$.post("getWeather.php",
{
postData: url,
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
// console.log("Data: " + data + "\nStatus: " + status);
//CONSOLE #1
console.log("url Input: \n" + url + " \n\ndata : \n" + data);
result = data;
});
//CONSOLE #2
console.log("url Input: \n" + url + " \n\nResult : \n" + result);
}
And in PHP where the postData is get:
$s = $_REQUEST['postData'];
echo getWeather_PHP($s);
function getWeather_PHP($url) {
$contents = file_get_contents($url);
$clima=json_decode($contents);
$temp_max=$clima->main->temp_max;
$temp_min=$clima->main->temp_min;
$icon=$clima->weather[0]->icon.".png";
//how get today date time PHP :P
$today = date("F j, Y, g:i a");
$cityname = $clima->name;
$date = $cityname . " - " .$today . "<br>";
$max = "Temp Max: " . $temp_max ."°C<br>";
$min = "Temp Min: " . $temp_min ."°C<br>";
$output = $date." ".$max." ".$min;
$output = (string)$output;
// echo $output;
return $output;
}
Finally the result is : Finally the result is : ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //CONSOLE #2 url Input: http:/..........
Result : undefined
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//CONSOLE #1 ajaxTest.php:24 url Input: http:/..........
data : Aplington - October 1, 2018, 8:12 pm Temp Max: 13.9c Temp Min: 12c
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
So CONSOLE #2 completed earlier than CONSOLE #1 So it seem the bug that I cannot get result correctly ??? How do I solve that? Or is there any papular way to do the same thing?
Thank you for helping