简体   繁体   English

ajax表单提交->从php接收响应

[英]ajax form submit -> receive respone from php

I've been reading multiple threads about similar cases but even now I'm still unable to do it correctly. 我一直在阅读有关类似案例的多个主题,但即使现在我仍然无法正确地做到这一点。

What I want to do Basically, ie I have form which allows user to change his login (simply query to database). 我想做的事情基本上,即我有一个允许用户更改其登录名的表单(仅查询数据库)。 PHP script looks like that: PHP脚本如下所示:

if(isset($_POST['login'])) {
        $doEdit = $user->editData("login", $_POST['login']);
        if($doEdit) {
            $result = displayInfobox('success', 'Good!');
        } else {
            $result = displayInfobox('warning', 'Bad!');
        }   
    } else {
        $error = 'Bad!';
        echo $error;
    }

displayInfobox is just a div with class ie success and content - Good!. displayInfobox只是一个具有类(即成功和内容)的div-好!

Right now I would like to send this form by AJAX and display $result without reloading page. 现在,我想通过AJAX发送此表单并显示$ result,而无需重新加载页面。

HTML: HTML:

<form id="changeLogin" method="post" class="form-inline" action="usercp.php?action=editLogin">
        <label for="login">Login:</label><br />
        <div class="form-group ">
            <input type="text" class="form-control" name="login" id="login" required>
            <input type="submit" value="Zmień"  class="btn btn-primary">
        </div>
    </form>

And finnally - my jquery/ajax: 最后-我的jquery / ajax:

$("#changeLogin").submit(function(e) {

  var postData = $(this).serializeArray();
  var formURL = $(this).attr("action");
  $.ajax({
    url: formURL,
    type: "POST",
    data: postData,
    success: function(result) {
      alert(result);
    },
    error: function(response) {}
  });
  e.preventDefault();
});

$("#changeLogin").submit();

If I leave "success" blank, it works -> form is submitted by ajax, login changed, but I do not see the result message. 如果我将“成功”留为空白,则可以正常工作->表单是由ajax提交的,登录名已更改,但看不到结果消息。 Otherwise whole page get reloaded. 否则将重新加载整个页面。 Also, when I hit F5 form is being submited once again (even in Ajax). 另外,当我点击F5时,表单将再次提交(即使在Ajax中)。

I cant add comments because i do not have enough reputation but... 我无法添加评论,因为我没有足够的声誉,但是...

You should delete the last line with $("#changeLogin").submit(); 您应该使用$("#changeLogin").submit();删除最后一行$("#changeLogin").submit();

And then in your php script file you should echo the result so you can get this result in ajax request. 然后,在您的php脚本文件中,您应该回显结果,以便可以在ajax请求中获得此结果。 After that in your success method you have to read the result and (for example) append it somewhere to show the success or error box 之后,在成功方法中,您必须阅读结果并将其(例如)附加到某处以显示成功或错误框

我认为您可以使用普通按钮代替提交按钮,仅onclick可以是一个ajax请求,不应该提交表单,祝您好运。

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

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