Hundotte Hundotte - 5 months ago 7
jQuery Question

Why is AJAX data not received by PHP?

I have the following extremely simple PHP tester:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

<button id="button">send request</button>

<script>
$("#button").click(function(){
$.ajax({
type: "POST",
url: "ajaxTest.php",
data: {userresponse: "hi"},
success: function(data){
alert(data)
analyse()
}
})
})

var analyse = function () {
<?php
if(isset($_POST["userresponse"])){
$variable = $_POST["userresponse"];
switch($variable){
case "hi":
echo 'alert("' . $variable . '")';
break;
default:
echo 'alert("LOGIC")';
}
}
?>
}
</script>


What's supposed to happen is that when I click the button, it sends the data
userresponse: "hi"
to the server, and then PHP receives it and alerts the value (i.e. "hi")

However, despite the fact that the file paths are correct, the AJAX send is OK in XHR, the PHP does not receive the value of the data, and the
alert(data)
returns the entire HTML document.

What is going on and how do I fix this?

Answer

Remove analyze() and put your php code in external file called ajaxTest.php, your code works perfect just remove your php code fron analyze and request for external this is bad practice having both in same file(header problems).

Proof: enter image description here

Comments