Damian Pakuła Damian Pakuła - 5 months ago 9
JSON Question

Create JSON object (with array) in php

I tried to create JSON object witch contain an array. I want to get JSON via AJAX, orginaly:

$.ajax({
url: 'data/events.json',
type: 'GET',
})


But I change this to

$.ajax({
url: 'data/events.php',
type: 'GET',
})


JSON I need looks like this:

{
"events": [
{
"month": "6",
"day": "12",
"year": "2016",
"title": "Lorem ipsum",
"description": "desc..."
},
{
"month": "6",
"day": "9",
"year": "2016",
"title": "Lorem ipsum",
"description": "desc..."
}
]
}


I've tried:

$events = array(
"events" => array(
array(
"month"=> "6",
"day"=> "12",
"year"=> "2016",
"title"=> "Lorem ipsum",
"description"=> "desc.."
),
array(
"month"=> "6",
"day"=> "9",
"year"=> "2016",
"title"=> "Lorem ipsum",
"description"=> "desc..."
)
)
);

echo json_encode($events);


But this is not working. Thank you in advance!

Answer

I think your array is ok , but in ajax
Try:

dataType: 'json' : This will convert your response to json object.

$.ajax({
    url: 'data/events.json',
    type: 'GET',
    dataType: 'json'
});