Search code examples
javascriptjqueryjsongetjson

getJSON gives statut 200 but no value


I've found a dozen of questions about this problem, but none of the solutions seem to help me.

I've got a piece of PHP code that creates an JSON object, basicly my page looks like this:

<?php
    $supps = ...; /* mysqli class that gets the values */
    header("Content-type: text/javascript");
    echo json_encode( $supps );
?>

When going to the page feed.php?load&menu_id=2 it shows the object:

[{"id":32,"name":"Test 4","weight":15},{"id":33,"name":"Test 5","weight":25},{"id":34,"name":"Test 6","weight":35}]

Running this through the JSONlint validator gives me this (valid!) result

[
    {
        "id": 32,
        "name": "Test 4",
        "weight": 15
    },
    {
        "id": 33,
        "name": "Test 5",
        "weight": 25
    },
    {
        "id": 34,
        "name": "Test 6",
        "weight": 35
    }
]

Now I'm trying to load this data with a JQuery function (based on a selected value from a form). I've tried multiple pieces of code:

/* Try 1 */
var menuID = $('[name=menu]:checked').val();
$.getJSON("feed.php?load&amp;menu_id="+menuID, function(json) {
    console.log(json);
});

/* Try 2 */
var menuID = $('[name=menu]:checked').val();
$.ajax({
    url: "feed.php?load&amp;menu_id"+menuID,
    dataType: "JSON",
    success: function(json){
          console.log(json);
    }
})

/* Try 3 */
var menuID = $('[name=menu]:checked').val();
$.getJSON("feed.php?load&amp;menu_id="+menuID, function(data) {
    console.log(data);
}).done(function(xhr) {
    console.log(xhr)
});

/* Try 4 */
var menuID = $('[name=menu]:checked').val();
$.ajax({
    type: "GET",
    url: "feed.php?load&amp;menu_id="+menuID,
    async: false,
    dataType: "json",
    success: function(data){
        console.log(data);
    }
});

Every try gives me the same result in the console:

GET http://.../feed.php?load&amp;menu_id=1 200 OK 51ms

But no object in the console.

What am I doing wrong here?


Solution

  • Your URL contains an encoded ampersand:

    feed.php?load&amp;menu_id="+menuID

    &amp; is not decoded when used in a URL. Your query string is broken.