0

I am just starting to learn JSON where a tutorial from other site uses this code (which I already modified to simplify this):

$(document).ready(function(){
    $('#getdata-button').click(function(){
        $.ajax({
            type: "GET",
            url: "json-data.php",
            dataType: "json",
            success: function(){
                alert('a');
                $('#showdata').html(
                    "<p>item1="+data.item1+
                    " item2="+data.item2+
                    " item3="+data.item3+"</p>"
                );
            }
        });
    });
});

And this is the code for json-data.php

<?php
    $item1 = "candy";
    $item2 = "chocolate";
    $item3 = "ice cream";

    //return in JSON format
    echo "{";
    echo "item1: ", json_encode($item1), "\n";
    echo "item2: ", json_encode($item2), "\n";
    echo "item3: ", json_encode($item3), "\n";
    echo "}";
?>

The problem is that alert function (for debugging purposes) isn't responding after I have clicked the button (with the id of "getdata-button"). Firebug says that the request is successful and I can see the data from there. No error was found. It is just the callback function is not executing, but why?

fullybaked
  • 4,117
  • 1
  • 24
  • 37
Arman
  • 1,434
  • 2
  • 22
  • 42
  • 2
    Your JSON isn't valid. Keys and string values must be wrapped in double quotes, and `json_encode()` isn't meant to be used INSIDE a json string, it is meant to output a complete JSON string. – Kevin B May 03 '13 at 15:39
  • 4
    Gah! Don't do that! You should be building an array in PHP and then just doing `echo json_encode($array)` – Bojangles May 03 '13 at 15:41
  • I find http://jsonlint.com very helpful. You should take advantage of the ajax "error" callback too. Also http://www.json.org is good for the theory and syntax. – dmgig May 03 '13 at 15:42
  • Add an `error` function to see if the request is failing. – nullability May 03 '13 at 15:50
  • 1
    I also noticed your `success()` function does not take any arguments, so `data` would not be defined. It should be `success: function(data)` – nullability May 03 '13 at 15:50
  • @nullability , Yes thanks, I forgot to add `data` parameter. – Arman May 03 '13 at 15:52

1 Answers1

2

You need to output your JSON correctly. Replace your PHP with the below

$items = array(
    'item1' => $item1,
    'item2' => $item2,
    'item3' => $item3
);
header('Content-type: application/json');
echo json_encode($items);
fullybaked
  • 4,117
  • 1
  • 24
  • 37
  • @fullybaked Thanks, this works perfectly. But is the header really mandatory? – Arman May 03 '13 at 15:54
  • I wouldn't say mandatory, no. But good practice... Yes, as it informs the browser/client exactly what to expect in the response – fullybaked May 03 '13 at 15:55