Echo certain value by AJAX request not working

Viewed 186

I've made an ajax call to the test.php and the call is even shown successful in the devtools network. The problem is even after making a successful call the further $country is not been echoed.

Here is my code

ajax.php

<!DOCTYPE html>
<html>
<head>
    <title>Interval</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
$.ajax({url: 'test.php',
         data: {value: 'India'},
         type: 'post',
         success : function(data){
            alert(data);
         }     
});
</script>
</head>
<body>
</body>
</html>

test.php

<?php
if(isset($_POST['value']) && $_POST['value'] == 'India'){
     $country = $_POST['value'];
        echo $country;
}
?>
1 Answers

You need to separate your ajax code and call that file from ajax. The reason why this is happening is because ajax.php is returning the whole page output starting from <html> and ending at </html>. So the ajax.php should look like:

<?php
if(isset($_POST['value']) && $_POST['value'] == 'India'){
    $country = $_POST['value'];
    echo $country;
}
?>

Then your script can be edited to

<script>
$.ajax({url: 'ajax.php',
    data: {value: 'India'},
    type: 'post',
    success : function(data){
        alert(data);
    }       
});
</script>
Related