简体   繁体   中英

ajax Json returning null

I have a simple ajax call to php with a json response. I have written these multiple times, but have never come across this issue.

The Ajax sends over the "id" parameter fine and the PHP receives it, does it's work and sends back the json response, which is where the issue begins. one of the parameters is always null, for a reason i can't seem to find. I have tested the php manually, and it returns both the values. i have checked the ajax to see if it revives the id parameter, it does. So the issue is some where around the json response being sent, and it being received by the jquery ajax.

 // This gets the paramaters from the url
 theParams = parseURLParams(document.URL);

 // ^^ it returns an id, like this  {"id":"4a17bcb93fe3fac3978671a66959d902"}

 $.ajax({
    url: 'viewer_code.php',
    type: 'GET',
    dataType: 'json',
    data: {id: theParams.id},
    success: function(dataImg) { 

    alert(dataImg.imgUrl);

    }
});

and the PHP (All seems fine & all will be sanitized)

    $id = $_GET['id'];

    $q = "SELECT * FROM `images` WHERE id = '$id'";
    if(!($result_set = mysql_query($q))) die(mysql_error());
        $row = mysql_fetch_array($result_set);

        $thumb = $row['thumb'];
        $image = $row['image'];

        header('Content-Type: application/json');
        echo json_encode(array("imgUrl" => $image, "id" => $id));

when the PHP is tested manually, it returns: {"imgUrl":"pictures/75de7c1c30d956113f937a8e685f7e50.jpg","id":"4a17bcb93fe3fac3978671a66959d902"}

It's the imgUrl that always returns null, anyone have any idea why this is happening? Oh and i have tried switching from GET to POST as previous questions on SO have suggested, but it didn't make any difference.

Many thanks in advance for any help, cheers guys :)

Have you try instead of id: theParams.id using id: 1 I had a big problem trying to handle variables that were not correct json.

In the other hand I am doing a similar code but do not have

header('Content-Type: application/json');

Have you try in your php file echo json_encode(array("imgUrl" => 'image.jpg', "id" => '1')); Depending on those tests maybe I could help you more

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