Reputation: 63
I want to create a JavaScript object as follows.
var codropsEvents = {
'02-02-2017' : '<span>Some txt from database</span><span>Some txt from database</span>',
'02-05-2017' : '<span>Some txt from database</span><span>Some txt from database</span>'
};
For that, the js function I developed is as follows.
function setEventsCalendar() {
var codropsEvents
try {
$.ajax({
type: "POST",
url: "calendarData.php",
dataType: "text",
async: false,
success: function(msg) {
codropsEvents = "{" + msg + "}";
codropsEvents = JSON.parse(codropsEvents);
}
});
return codropsEvents;
} catch(ex) {
alert(ex);
}
}
var codropsEvents = setEventsCalendar();
calendarData.php file generates following as a String (Including all colons, commas, tags etc.)
'02-02-2017' : '<span>Some txt from database</span><span>Some txt from database</span>', '02-08-2017' : '<span>Some txt from database</span><span>Some txt from database</span>'
How can I create the JS object using that String? Or any other proper way to get the expected result.
Upvotes: 1
Views: 888
Reputation: 3579
you can make an array like in php-
$dataArray = ['02-02-2017' => '<span>Some txt from database</span><span>Some txt from database</span>',
'02-05-2017' => '<span>Some txt from database</span><span>Some txt from database</span>'];
// and this array to json string and print it,
echo json_encode($dataArray,JSON_FORCE_OBJECT);
Now in ajax part you can simply get data in json format by changing dataType to json
; msg parameter of success function is javascript object or having code like codropsEvents = JSON.parse(msg);
inside success function.
Upvotes: 1