简体   繁体   English

如何获取ajax表单提交返回值

[英]how to get ajax form submit return value

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. 我使用ajax提交表单,但是当我完成整个过程时,它停止在api.php上,并确实恢复了ajax的成功。 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 在我的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. 在浏览器上显示的url是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; 我最终做到了!阿贾克斯过后,我错过了“ return false”; But actually I dont really know the function of return false; 但是实际上我并不真正知道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;  
});

Redirecting to other page will have the header() to use: 重定向到其他页面将具有header()来使用:

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();
}

javascript doesn't recognize return value from php. javascript无法识别php的返回值。 Use echo instead. 请改用echo

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 . 如果要查看来自api.php实际输出,请在ajax使用以下代码。

success: function(res){
   console.log(res);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM