1

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.

5
  • 1
    That's not valid JSON. In JSON, strings are surrounded with double quotes, not single quotes. Why aren't you using json_encode() in the PHP script? Commented Feb 12, 2017 at 6:27
  • 1
    One thing more async: false has been deprecated, please do not use it. Commented Feb 12, 2017 at 6:32
  • @Barmar I tried 'json_encode()'. But still I couldn't get the expected result. Therefore, could you be more specific so that I can adapt it in my code. Commented Feb 12, 2017 at 6:57
  • @Kumar Thank you very much for the advice Commented Feb 12, 2017 at 6:58
  • 1
    If PHP returns valid JSON, you don't need to concatenate { and } in the Javascript. Commented Feb 12, 2017 at 6:58

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.