简体   繁体   中英

JSON Object returned from PHP is NULL

I am trying to send a javascript variable (placeid) to PHP using AJAX. I use this variable to retrieve a JSON Object. The JSON returned to Javascript is NULL. How do I fix this?

function sendToPhp(placeid){
var url = "finals.php?placeid="+placeid;
var getJSONObj=function(url,callback){
var httpc = new XMLHttpRequest(); 
httpc.open("GET", url, true);
httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpc.responseType='json';
httpc.onload= function(){
    var status=httpc.status;
    if(status==200){
        //alert(httpc.response);
        callback(null,httpc.response);
    }
    else{
        callback(status,httpc.response);
         }
   };
httpc.send();
 };

  getJSONObj(url,function(err,jsonObjectReturned){

    if(err!==null){
        alert("something went wrong"+ err);
    }
    else
    {
        alert("success");
        alert(jsonObjectReturned);   // **returns NULL**
    }
});
}  // end of function

The PHP script uses the placeid to return a JSON file as shown:

    if(isset($_GET['placeid']))
    {
        $placeid= $_GET['placeid'];
        $apikey="someKeyValue";
        $url="https://maps.googleapis.com/maps/api/place/details/json?placeid=".$placeid."&key=".$apikey;
        $jsonPlacesObject=json_decode(htmlspecialchars(@file_get_contents($url),true),true);
        echo json_encode($jsonPlacesObject);  //sending json to javascript**
        die();
    }

Your AJAX form looks wrong. Try reading https://www.w3schools.com/js/js_json_php.asp .

Original.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM