为什么在输入数据正确时表单没有被发送(JavaScript,Ajax)?

huangapple go评论60阅读模式
英文:

Why is the form not sent when the data is entered correctly (javascript, ajax)?

问题

以下是翻译好的部分:

有一个登录表单:

{% block content %}
  <form method="POST" class="login-form" id="login-form">
    {{ login_form.hidden_tag() }}
    <div class="form-group">
        {{ login_form.name.label }}
        {{ login_form.name(class="form-control", id="login_form_name", placeholder="Name") }}
    </div>
    <div class="form-group">
        {{ login_form.password.label }}
        {{ login_form.password(class="form-control", id="login_form_password", placeholder="Password") }}
        <p id="incorrect-data-error" class="error-message" style="margin-top: 30px;"></p>
    </div>
    <div class="form-group">
		{{ login_form.recaptcha.label }}
		{{ login_form.recaptcha(class="g-recaptcha") }}
		<p id="recaptcha-error" class="error-message" style="margin-top: 30px;"></p>
    </div>
    <div class="form-group">
        {{ login_form.submit(class="btn btn-primary", id="login-form-submit") }}
        <p id="session-exists-error" class="error-message" style="margin-top: 30px;"></p>
    </div>
  </form>
  <p class="register_account_message">Don't have an account? <a href="/signup">Signup here</a></p>
{% endblock %}

有一个与此表单相关联的js脚本,它使用ajax在按下“登录”按钮后将表单数据发送到服务器:

$(document).ready(function() {

  $("#login-form").on("submit", function(event) {
    event.preventDefault();
    var formData = $(this).serialize();

    $.ajax({
      type: "POST",
      url: "/check_login_user_credentials",
      data: formData,
      success: function(response) {
        if (response.response === 'Incorrect data') {
          $("#incorrect-data-error").text('Incorrect username or password');
        } else if (response.response === 'Session already exists') {
          $("#session-exists-error").text('This account is already in use. Please try again later.');
        } else if (response.response === 'Allow') {
          $("#incorrect-data-error").text('');
          $("#login-form")[0].submit();
        }
      }
    });
  });
});

数据发送到的路由:

@app1.route('/check_login_user_credentials', methods=['GET', 'POST'])
def check_login_user_credentials():
    hashed_password = sha256(request.form.get('password').encode('utf-8')).hexdigest()
    user = User.query.filter(User.name==request.form.get('name'), User.password==hashed_password).first()
    if user:
        if user.active_session:
            return jsonify({ 'response': 'Session already exists' })
        else:
            return jsonify({ 'response': 'Allow' })
            
    return jsonify({ 'response': 'Incorrect data' })

问题似乎与 event.preventDefault(); 有关,因为它会阻止表单的默认提交行为。如果数据正确,应该使用 $("#login-form")[0].submit(); 手动触发表单的提交。如果点击按钮后仍然没有任何反应,可能需要检查其他js或css文件是否有冲突,以及确保jQuery版本没有问题。

英文:

There is a login form:

{% block content %}
  &lt;form method=&quot;POST&quot; class=&quot;login-form&quot; id=&quot;login-form&quot;&gt;
    {{ login_form.hidden_tag() }}
    &lt;div class=&quot;form-group&quot;&gt;
        {{ login_form.name.label }}
        {{ login_form.name(class=&quot;form-control&quot;, id=&quot;login_form_name&quot;, placeholder=&quot;Name&quot;) }}
    &lt;/div&gt;
    &lt;div class=&quot;form-group&quot;&gt;
        {{ login_form.password.label }}
        {{ login_form.password(class=&quot;form-control&quot;, id=&quot;login_form_password&quot;, placeholder=&quot;Password&quot;) }}
        &lt;p id=&quot;incorrect-data-error&quot; class=&quot;error-message&quot; style=&quot;margin-top: 30px;&quot;&gt;&lt;/p&gt;
    &lt;/div&gt;
    &lt;div class=&quot;form-group&quot;&gt;
		{{ login_form.recaptcha.label }}
		{{ login_form.recaptcha(class=&quot;g-recaptcha&quot;) }}
		&lt;p id=&quot;recaptcha-error&quot; class=&quot;error-message&quot; style=&quot;margin-top: 30px;&quot;&gt;&lt;/p&gt;
    &lt;/div&gt;
    &lt;div class=&quot;form-group&quot;&gt;
        {{ login_form.submit(class=&quot;btn btn-primary&quot;, id=&quot;login-form-submit&quot;) }}
        &lt;p id=&quot;session-exists-error&quot; class=&quot;error-message&quot; style=&quot;margin-top: 30px;&quot;&gt;&lt;/p&gt;
    &lt;/div&gt;
  &lt;/form&gt;
  &lt;p class=&quot;register_account_message&quot;&gt;Don&#39;t have an account? &lt;a href=&quot;/signup&quot;&gt;Signup here&lt;/a&gt;&lt;/p&gt;
{% endblock %}

There is a js-script, which is associated with this form. It, using ajax, sends data from the form to the server after the Log In button is pressed:

$(document).ready(function() {

  $(&quot;#login-form&quot;).on(&quot;submit&quot;, function(event) {
    event.preventDefault();
    var formData = $(this).serialize();

    $.ajax({
      type: &quot;POST&quot;,
      url: &quot;/check_login_user_credentials&quot;,
      data: formData,
      success: function(response) {
        if (response.response === &#39;Incorrect data&#39;) {
          $(&quot;#incorrect-data-error&quot;).text(&#39;Incorrect username or password&#39;);
        } else if (response.response === &#39;Session already exists&#39;) {
          $(&quot;#session-exists-error&quot;).text(&#39;This account is already in use. Please try again later.&#39;);
        } else if (response.response === &#39;Allow&#39;) {
          $(&quot;#incorrect-data-error&quot;).text(&#39;&#39;);
          $(&quot;#login-form&quot;)[0].submit();
        }
      }
    });
  });
});

The route to which the data is sent:

@app1.route(&#39;/check_login_user_credentials&#39;, methods=[&#39;GET&#39;, &#39;POST&#39;])
def check_login_user_credentials():
    hashed_password = sha256(request.form.get(&#39;password&#39;).encode(&#39;utf-8&#39;)).hexdigest()
    user = User.query.filter(User.name==request.form.get(&#39;name&#39;), User.password==hashed_password).first()
    if user:
        if user.active_session:
            return jsonify({ &#39;response&#39;: &#39;Session already exists&#39; })
        else:
            return jsonify({ &#39;response&#39;: &#39;Allow&#39; })
            
    return jsonify({ &#39;response&#39;: &#39;Incorrect data&#39; })

The thing is that when the data is incorrectly entered and/or the account has been logged in earlier, everything works as it should (the form is not sent and the corresponding messages appear). But, when the data is correct and no one has previously logged into the account, then there are no messages (as it should be), but the form is still NOT sent, although it should be. I just click the button and nothing happens, although the data is sent with ajax.

If anything, I use this version of jQuery:

&lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js&quot;&gt;&lt;/script&gt;

If anything, ChatGPT can't handle it) Any help and advice would be great.

As far as I understand it is most likely related to event.preventDefault();

答案1

得分: 0

你需要改变你的逻辑。你当前的做法是阻止正常的提交,而是进行了一个AJAX调用,根据这个调用的响应来决定是否执行正常的提交。

下面这行代码会强制提交,因为表单标签中没有URL,所以它会提交到当前页面,这就是为什么提交后会返回到该页面,而不是这行代码,你可能想要将用户重定向到主页,例如:

$("#login-form")[0].submit();
英文:

You have to change your logic. You are preventing the normal submit to happen to instead make an AJAX call, and with the response of this call you decide if you do a normal submit.

The line below is going to force a submit, as there are no URL in the form tag, it's going to submit to your current page, that why you are getting back to the page when submiting, instead of this line, you want to redirect the user to the home page for example

$(&quot;#login-form&quot;)[0].submit();

huangapple
  • 本文由 发表于 2023年6月12日 03:51:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76452283.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定