Reputation: 61
I use ajax to submit a form, however when i finished the whole process, it stopped at the api.php and did get back to the ajax success. Here the code:
<form method="POST" id="form_1" action="../api.php" enctype="multipart/form-data" novalidate="novalidate">
<input type="text" name="name" id="name" value="Amy" readonly="readonly">
<input id="fileBox" class="fileUpload" type="file" name="img" accept="image/*" required>
<input type="hidden" name="isSubmit" value="1"/>
</form>
<a id="btnSubmit" href="javascript:void(0)">Submit</a>
$("#form_1").submit(function(){
var formData = new FormData(($this)[0]);
$ajax({
type: "POST",
url: "../../api.php",
data: { action:"formSubmit", formData:formData},
processData: false,
contentType: false,
success: function(){
console.log('success return');
}
})
});
$("#btnSubmit").click(function(){
if($("#form_1").valid()){
// inside click event handler you trigger form submission
$("#form_1").trigger('submit');
}
});
in my api.php
if($action=='formSubmit'){
$name = $_POST['name'];
if(createUser($name)){
return true;
}else{
return false;
}
}
I checked the database , record is successfully created. But I can't get the console in success. The url show on the browser there is the path of the api.php. Why I stopped there can't get the return?
Thanks for your help!!
I finallly did it !I am missing "return false" after the ajax; But actually I dont really know the function of return false;
$("#form_1").submit(function(){
var formData = new FormData((this)[0]);
$.ajax({
type: "POST",
url: "../../api.php",
data: { action: "formSubmit", formData: formData},
processData:false,
contentType:false,
success: function(data){
$("#thankyou").show();
}
})
return false;
});
Upvotes: 0
Views: 2453
Reputation: 167182
Redirecting to other page will have the header()
to use:
if ($action == 'formSubmit') {
$name = $_POST['name'];
if (createUser($name)) {
// Redirect to right.htm
header("Location: right.htm");
} else {
// Redirect to wrong.htm
header("Location: wrong.htm");
}
die();
}
Upvotes: 3
Reputation: 5792
javascript doesn't recognize return value from php. Use echo
instead.
if($action=='formSubmit'){
$name = $_POST['name'];
if(createUser($name)){
echo 'true';
}else{
echo 'false';
}
}
If you want to see actual output coming from api.php
then use below code in your ajax
.
success: function(res){
console.log(res);
}
Upvotes: 1