0
votes

UPDATED : now I can see datas are loaded (from F12 > Network on Chrome). But spans are not updated with datas loaded from JSON :(

I've error "Uncaught SyntaxError: Unexpected token", but after hours of searching and tests I don't know why.

index.html head :

<script type="text/javascript">
    var displayResult = function(response){
        $("#fruit_name").append(response.fruit_name);
        $("#fruit_color").append(response.fruit_details.Color);
        $("#fruit_taste").append(response.fruit_details.Taste);
    }
    var response = $.ajax({
    type: "GET",
    dataType:"json",
    url: "https://www.domain.tld/api/?core=fruits&function=getFruits",
    data: "",
    success: displayResult
});
</script>

index.html body :

<p>Fruit name : <span id="fruit_name"></span></p>
<p>Fruit color : <span id="fruit_color"></span></p>
<p>Fruit taste : <span id="fruit_taste"></span></p>

api file (PHP) :

$array = array(
            "fruit_name" => "Tomato",
                "fruit_details" => array(
                    "Color" => "red",
                    "Taste" => "acid"
                )
            );
echo json_encode($array,JSON_UNESCAPED_UNICODE);

api raw return :

{"fruit_name":"Tomato","fruit_details":{"Color":"red","Taste":"acid"}}

Can someone help me ?

Content JSON send as Content-Type: application/json

Thank you.

2
missing semi colons on lines 4 & 5 - MLeFevre
Error when copy/paste, updated ;) - Franck Boudraa
looks fine... which is the line pointed out by browser console - Arun P Johny
do you have a line number of where the error is occuring? - MLeFevre
Where and when you got the error - Emilio Gort

2 Answers

0
votes
url: "https://www.domain.tld/api/?core=fruits&function=getFruits&callback=?",

You're using a callback parameter in your url, which means that jQuery will treat it as a JSONP call - where your response is invalid. Remove it, and your response will be properly parsed as JSON:

url: "https://www.domain.tld/api/?core=fruits&function=getFruits",
-1
votes

This is jQuery code:

$("#fruit_name" ).val(response.fruit_name);
$("#fruit_color" ).val(response.fruit_color);
$("#fruit_taste" ).val(response.fruit_taste);

Make sure it is enclosed with:

$(document).ready(function() {
    $("#fruit_name" ).val(response.fruit_name);
    $("#fruit_color" ).val(response.fruit_color);
    $("#fruit_taste" ).val(response.fruit_taste);
});