Joseph Joseph - 2 days ago 5
Ajax Question

How get values in Multidimensional Array in ajax request with jquery

I return in a ajax call a multidimensional array and I need to get all values

PhP

public function ExampleAction()
{

$arr = array(array("title" => 'Example Title 1',"description" => "Morbi leo risus, porta ac consectetur ac","datetime"=>new \DateTime("tomorrow")),
array("title" => 'Example Title 2',"description" => "Morbi leo risus, porta ac consectetur ac","datetime"=>new \DateTime("today"))
);
return new JsonResponse(array(
'data' =>$arr,
'success' => true), 200);
}


For simple array I get the values like this in Javascript:

$.ajax({
type: 'POST',
url: Routing.generate('example'),
data: {},
dataType: 'json',
success: function(response) {
for (var key in response.data) {

title= response.data[key];
description= response.data[key];
datetime= response.data[key];

},
}
})


But I do not know how to get it for multidimensional arrays. I have tried several ways and I have not succeeded.

I appreciate your help in advance.

Edited--------------------------Initial problem------------------------------

I needed to obtain one object like this:

$.ajax({
type: 'POST',
url: Routing.generate('example'),
data: {},
dataType: 'json',
success: function(response) {

$('#calendar').eCalendar({
...
events: [{
title: 'Example Title 1',
description: 'Description 1. Without link',
datetime: new Date(2016, 11, 30)
},
{
title: 'Example Title 2',
description: 'Description 2.',
datetime: new Date(2016, 10, 23),
}]
});
}
})


So I put the following:

$.ajax({
type: 'POST',
url: Routing.generate('example'),
data: {},
dataType: 'json',
success: function(response) {

$('#calendar').eCalendar({
....
events: response.data,
....

});
}
})


But this gave me the following error:

TypeError: d.getDate is not a function
if (d.getDate() == day && d.getMonth() == dMonth && d.getFullYear() == dYear) {...


I guess it's because of the way to get the date in php that does not give the same result as the one indicated in javascript. So I wanted to get the data with the ajax call and assign it manually, but I was assigning it to the object, so I was doing it wrong. How can I solve this problem?

Answer

Actually you don't have a multi-dimensional array. You have an array of objects which have a second level object. But I see why you would think so. Try this

 success: function(response) {
   for (var i = 0; i < response.data.length; i = i + 1) {

     title = response.data[i].title; 
     description = response.data[i].description;
     datetime = response.data[i].datetime; 
     date = datetime.date
     timezone_type = datetime.timezone_type
     timezone = datetime.timezone

     console.log('timezone=' + timezone)

   },   

The datetime object is the trickier but not really hard once you see it done.

Comments