0

I am testing the getJSON with php array, but it is not working, can anyone check for me ? I feel the problem is from the php code because when i test the html code with getJSON url https://graph.facebook.com/zombies, it is working.

In my array.php

<?php

 header("Content-type: text/javascript");

 $arr = array(

            "name" => "Tim",
            "age" => "28"     );

echo json_encode($arr);

?>

In my test.html :

  <html>
  <head>
    <script type='text/javascript' src='jquery.js'></script>
  </head>
  <body>

    <script type='text/javascript'>

    $(document).ready(function() {
         $.getJSON('array.php', function(data) {        
            if(data) {
            document.write(data.age);       
            }
            else {
            alert('error');
            }
        });
    }); 
    </script>

   </body>
   </html>
2
  • 1
    Try the content type application/json Commented Nov 24, 2012 at 9:30
  • ok i have solve my problem, in php : echo $_GET["callback"] . "(" . json_encode($arr) . ")"; in html : $.getJSON('array.php?callback=?', function(data) so the cross server can be done Commented Nov 24, 2012 at 10:12

3 Answers 3

3

Change

header("Content-type: text/javascript");

To

header('Content-Type: application/json');

For JSONP

header('Content-Type: application/javascript');
Sign up to request clarification or add additional context in comments.

Comments

1

header("Content-type: text/javascript");

You're telling the browser you're sending it JavaScript, when what you're sending it is JSON. The content type for JSON is application/json.

If you fix that, it should work, provided you're not running afoul of the Same Origin Policy. If you're making a cross-domain request, your options are:

  • Don't use ajax and JSON, use JSON-P.

  • Use CORS, but it requires that the server allow your document's origin, and that the browser supports it (most modern ones do, older ones don't).

  • Use YQL as a cross-domain proxy.

3 Comments

oh ... i found my problem, because my script is inside Ubuntu server and i running it from win 7, thx for it !
i have a question, if the array transfer happen in local and cross domain, what should i do ?
@jc_tan: The cross-domain options work for the same domain as well.
1

Try to set the content type to

application/json

So jQuery will interpte as json data

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.