0

I am retrieving a string from Database & this string is an Array.

 jq.ajax({
            type: "GET",
            url: "/Method/",
            success: function () {
               // Sample data     
               var data = "[{                                   
                              name: "Santro",
                              canvas: "1"
                             }, {                                       
                              name: "Tata",
                              canvas: "2"
                           }]";

After getting the data by AJAX call, I get the string.

How to convert this string to an Array?

16
  • 1
    JSON.parse(data); ignoring the errors Commented Oct 28, 2015 at 6:36
  • your data is invalid try it here jsonlint.com Commented Oct 28, 2015 at 6:37
  • @Tushar How to solve this double quotes issue? Commented Oct 28, 2015 at 6:39
  • Is the data coming from server? Add the code. If not then use the \ at the end of the line where string is not completed. Use single quotes for string and double quotes inside Commented Oct 28, 2015 at 6:40
  • var data = [{ name: "Santro", canvas: "1" }, { name: "Tata", canvas: "2" }]; Commented Oct 28, 2015 at 6:41

2 Answers 2

0

Try this

jq.ajax({
        type: "GET",
        url: "/Method/",
        dataType: "JSON",
        success: function (obj) {
            $.map(obj, function(el) 
               { 
                    return el // as array 
               });
        }
Sign up to request clarification or add additional context in comments.

Comments

0

your php should look like this :

 public function actionTest2() {
    $arr[] = [
        'name' => 'saura',
        'canvas' => 1,
    ];
    $arr[] = [
        'name' => 'tat',
        'canvas' => 3,
    ];
  //$arr like your db result 
    echo json_encode($arr);
}

and php output: [{"name":"saura","canvas":1},{"name":"tat","canvas":3}]

your js should look like this:

jq.ajax({
    type: "GET",
    url: "test2",
    dataType: "JSON",
    success: function (data) {
      var obj = jQuery.parseJSON(data);
       console.log(obj[0]); // make loop to navigate the data
    }

2 Comments

check the answer please is that you want!

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.