I'm new to php so please bare with me. I have an ajax function that creates a post request to send data to server side php and echo it and my code should work fine. The problem is the php echo is proccessing before the create()
function is ran so an error that the variables are not found is only displayed. Is there a way in php to make the echo proccess wait untill the ajax function is ran. Any help is appreciated. Thanks in advace.
function create() {
$.ajax({
url: "test.php",
type: "post",
dataType: 'json',
data: {
registration: "success",
name: "xyz",
email: "abc@gmail.com"
},
success: function(result) {
console.log(result.abc);
}
});
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<button onclick="create()">click me</button>
<?php
$registration = $_POST['registration'];
$name= $_POST['name'];
$email= $_POST['email'];
if ($registration == "success"){
echo json_encode(array("abc"=>'successfuly registered'));
}
?>
function create() {
$.ajax({
url: "test.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {
registration: "success",
name: "xyz",
email: "abc@gmail.com"
},
success: function(result) {
console.log(result.abc);
}
});
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<button onclick="create()"> Click me</button>
<? php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$registration = $_POST['registration'];
$name= $_POST['name'];
$email= $_POST['email'];
if ($registration == "success"){
// some action goes here under php
echo json_encode(array("abc"=>'successfuly registered'));
}
}
?>