Jaydeep Gondaliya Jaydeep Gondaliya - 3 months ago 10
Ajax Question

php to get json encode and decode issue

my php file ajax.php

<?php


$data=array();
$i=0;
while($i <= 2)
{
$data[$i]['allDay']="test";
$data[$i]['title']="Test event";
$data[$i]['id']="821";
$data[$i]['start']="2016-08-23 14:00:00";
$data[$i]['end']="2016-08-23 15:00:00";
$i++;
}

echo (json_encode($data));

?>


AJAX call

$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax.php",
dataType: "json",
success: function (data) {

alert("suc" + data);
},
error: function (result) {
alert("Error");
}
});


Expected output

[
"0",
{
"allDay": "",
"title": "Test event",
"id": "821",
"start": "2016-08-23 14:00:00",
"end": "2016-08-23 15:00:00"
},
"1",
{
"allDay": "",
"title": "Test event",
"id": "821",
"start": "2016-08-23 14:00:00",
"end": "2016-08-23 15:00:00"
},
"2",
{
"allDay": "",
"title": "Test event",
"id": "821",
"start": "2016-08-23 14:00:00",
"end": "2016-08-23 15:00:00"
},
"3",
{
"allDay": "",
"title": "Test event",
"id": "821",
"start": "2016-08-23 14:00:00",
"end": "2016-08-23 15:00:00"
}
]


get Outpput


[{"allDay":"test","title":"Test event","id":"821","start":"2016-08-23
14:00:00","end":"2016-08-23 15 :00:00"},{"allDay":"test","title":"Test
event","id":"821","start":"2016-08-23 14:00:00","end":"2016-08-23
15:00:00"},{"allDay":"test","title":"Test
event","id":"821","start":"2016-08-23 14:00:00","end":"2016-08-23
15:00:00"}]


enter image description here

Answer

First I would suggest to write your array like this:

<?php
    $data=array();
    $i=0;

    while($i <= 2) {
        $data[$i] = array(
            'allDay' => 'test',
            'id' => 821,
            'start' => '2016-08-23 14:00:00',
            'end' => '2016-08-23 15:00:00'
        );
        $i++;
    }

    echo (json_encode($data));
?>

Also your output is correct, your expectation is wrong, your JSON Output looks like this:

[
    {
         data...
    }
    {
         data...
    }
    {
         data...
    }
    ...
]

so each of the {} is one index inside your [] array. There are no keys set for them because you only have numbers set as keys.

Comments