0

Following is my JavaScript code to get JSON data:

 $(document).ready(function()
          {
               $.support.cors = true;
               $.getJSON('http://example.com/root_dir/test_json.php', function(data1)
               {
                         alert("data1= "+data1); 
               });
          });

but the above alert shows me JSON in following format-

enter image description here

If I hit my php script URL in browser, it shows JSON data in expected formate as shown below-

[{"name":"AB","std":"7","number":"82"},{"name":"CD","std":"9","number":"90"},{"name":"PQ","std":"12","number":"79"}]

Following is my test_json.php code-

<?php

//Create an array
$json_response = array();

        $row_array['name'] = 'AB';
        $row_array['std'] = '7';
        $row_array['number'] = '82';

         array_push($json_response,$row_array);

        $row_array['name'] = 'CD';
        $row_array['std'] ='9';
        $row_array['number'] = '90';

         array_push($json_response,$row_array);

        $row_array['name'] = 'PQ';
        $row_array['std'] = '12';
        $row_array['number'] = '79';

        //push the values in the array
        array_push($json_response,$row_array);


   echo json_encode($json_response); 
?>
3
  • so wats the problem..Its correct.try with JSON.stringify(data1) Commented Aug 26, 2014 at 9:57
  • Why do you have $.support.cors = true;? You should never touch $.support it is there to tell jQuery if a browser supports a feature. You can't use it to turn cors support on in browsers that don't support cors. Commented Aug 26, 2014 at 9:58
  • @Quentin If I remove $.support.cors = true; it gives me "No Transport” error. Commented Aug 26, 2014 at 10:02

1 Answer 1

2

getJSON decodes the JSON into a JavaScript data structure.

Concatenating it with a string will implicitly call toString() on it. That will turn arrays in to a comma-seperated format and plain objects into "[Object object]".

Nothing is going wrong. That is the expected behaviour.

If you want to see the data in JSON format, then use JSON.stringify(data) or use .ajax instead of .getJSON and access the raw text data in the jqXHR object.

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

1 Comment

Thanks..! I did it using "jqXHR object".

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.