0

I'm trying to learn Ajax and Json so I can build on it to pass php data to my web page with out refreshing. I am using the following example but the result html page does not show anything. Can some one please let me know what I'm doing wrong.

Html code

<html>
<body>

<script src="jquery.js"></script>
<script>
    $.ajax({
      url: "test.php",
      dataType: "json", //the return type data is jsonn
      success: function(data){ // <--- (data) is in json format
        alert(data.test1);
        //parse the json data
      }
    });
</script>
<div id = "data"></div>
</body>
</html>

PHP code named test.php

<?php

$test = array();
$test['test1'] = '1';
$test['test2'] = '2';
$test['test3'] = '3';

echo json_encode($test);
//echo nothing after this //not even html
?>

2 Answers 2

2

You need to set response content type in php.

I think jQuery checks response type.

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

Also add bindings for errors.

$.ajax({
  url: "test.php",
  dataType: "json", //the return type data is jsonn
  success: function(data){ // <--- (data) is in json format
    alert(data.test1);
    //parse the json data
  },
  error: function(jqXHR, textStatus, errorThrown) {
    alert("Error: " + textStatus);
  }
});
Sign up to request clarification or add additional context in comments.

3 Comments

I have added the header in the php file just under <?php and also the error part in the html script but still nothing is showing.
ajax request either falls to success or error. Check for syntax error.
Also check for semantic errors. Using your browser's debugging feature.
-1
  1. Check your Jquery code file in the same directory and it is valid.
  2. Your php file is also in the same directory.
  3. You must run your html file using localhost.

10 Comments

i have added this but still nothing showing on the html page
Does your jquery file is included properly?
what do you mean by jquery file included properly. all the code for the two files are shown above
do you have the jquery file in the same folder of html file?
First, adding type: "POST" does nothing to answer the question here. The op is clearly not trying to send any data. They're trying to receive. The HTTP request verb is irrelevant. @user2669997 Second, why are you expecting anything to show up on the page? Your code only uses an alert.
|

Your Answer

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