-5

PHP code=>`

<?php
    //request data from the database
    //code here to connect to database and get the data you want

    /* Example JSON format 
    {
        "item1": "I love jquery4u",
        "item2": "You love jQuery4u",
        "item3": "We love jQuery4u"
    }
    */

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

JS=>

$(document).ready(function(){ 
    //attach a jQuery live event to the button
    $('#getdata-button').click(function(){
        $.get('json-data.php', function(data) { 
        //alert(data); //uncomment this for debug
        //alert (data.item1+" "+data.item2+" "+data.item3); //further debug
        $('#showdata').html("<p>item1="+data.item1+" item2="+data.item2+" item3="+data.item3+"</p>");
        });
    });
});

Please i've asked earlier too and i wasnt including details so this time ive included the whole sample when included Apart from this my console gives no error. Thank You `

Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55
Sachin Bahukhandi
  • 2,378
  • 20
  • 29
  • 2
    **Never build JSON by hand.** Your PHP code generates invalid JSON. Make an array and use [`json_encode()`](http://php.net/manual/en/function.json-encode.php) to generate valid JSON. – JJJ Feb 05 '16 at 17:45
  • 1
    If you asked earlier, then UPDATE that question. It will be reset in the queue again. Don't ask the same question again! – Bogdan Bogdanov Feb 05 '16 at 17:45
  • 5
    Possible duplicate of [can getJSON() be used for php?](http://stackoverflow.com/questions/35195273/can-getjson-be-used-for-php) – legoscia Feb 05 '16 at 17:45
  • excuse me sir Bogdan!!! have u got a solution to the prbolem please!!! ive been trying it almost a week and php files gives the correct json Output so please help me out if u can – Sachin Bahukhandi Feb 05 '16 at 17:52

1 Answers1

1

You should add the following header to your PHP file:

header('Content-type: text/json');

Besides that, just put your data directly into an array and then use json_encode. Your PHP file should look something like this:

<?php
header('Content-type: text/json');
$results = array( "item1"=> "I love jquery4u",
"item2"=> "You love jQuery4u",
"item3"=> "We love jQuery4u"
);
echo json_encode($results);
?>

Which will give you the following result:

{
    "item1": "I love jquery4u",
    "item2": "You love jQuery4u",
    "item3": "We love jQuery4u"
}
DouglasCamargo
  • 411
  • 3
  • 8