1

I want to create a hello world json rest webservice in test.php:

  <?php header("Content-type: application/json; charset=utf-8");


     $test[] = "hello";  
     $test[] = "world";  

    $json = json_encode($test);
    echo $json;    
  ?>

But nothing is returned when I test it with ajax below why ?

<html>
<head>
<script>
function test()
{ 
    var xhr; 
    try {  xhr = new ActiveXObject('Msxml2.XMLHTTP');   }
    catch (e) 
    {
        try {   xhr = new ActiveXObject('Microsoft.XMLHTTP');    }
        catch (e2) 
        {
          try {  xhr = new XMLHttpRequest();     }
          catch (e3) {  xhr = false;   }
        }
     }

    xhr.onreadystatechange  = function()
    { 
         if(xhr.readyState  == 4)
         {
              if(xhr.status  == 200) 
                  alert(xhr.responseText); 
              else 
                 alert("Error code " + xhr.status);
         }
    }; 

   xhr.open(GET, "test.php",  true); 
   xhr.send(null); 
} 
</script>
</head>

<body>
<script>
test();
</script>
 </body>
 </html> 
2
  • Why you don't use jQuery or other library? Commented Oct 30, 2010 at 13:09
  • Because I want to learn the basics first (json + xmlhttprequest) Commented Oct 30, 2010 at 16:56

1 Answer 1

1
  1. You have spaces before your PHP code starts, so the header call will error
  2. You're setting a text/html Content-Type for JSON data, it should be application/json
  3. You are are replacing the reference to the input element in the form with a string, you probably want to set it's .value property instead. (For that matter, you should probably be accessing it as document.forms.id_of_form.elements.dyn.value for clarity) (Using an input to display output is a rather dubious practice in the first place though)
Sign up to request clarification or add additional context in comments.

1 Comment

I have taken into account 1 & 2. Instead of 3 I just want to show alert but it doesn't work.

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.