在PHP MySQL中使用jQuery AJAX提交表单而无需重新加载 [英] Submit form without reload using jQuery AJAX in PHP MySQL

查看:115
本文介绍了在PHP MySQL中使用jQuery AJAX提交表单而无需重新加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本的注册/登录页面,该页面使用php将数据提交到SQL数据库.但是,我希望页面在jQuery AJAX的帮助下不要重定向(无论成功与否).

I have a basic signup/ login page that submits the data to the SQL database with php. However, I would like the page not to redirect on submission with help of jQuery AJAX (either successful or not).

这是我目前拥有的,并且无法正常工作.它不会显示任何错误消息.

This is what I currently have and it is not working. It doesn't show any error messages.

HTML-signup.html

HTML - signup.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Signup</title>
    <meta charset="utf-8">
</head>
<body>
    <form>
        <table>
            <tbody>
                <tr>
                    <td>
                        <input type="text" name="first" placeholder="First Name" id="first">
                    </td>
                </tr>
                <tr>
                    <td>
                        <input type="text" name="last" placeholder="Last Name" id="last">
                    </td>
                </tr>
                <tr>
                    <td>
                        <input type="submit" value="Signup" id="signup">
                    </td>
                </tr>
            </tbody>
        </table>
    </form>
</body>
</html>

JavaScript-signup.js

JavaScript - signup.js

function submit() {
    $("form").submit(function(e) {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: 'signup.php',
            data: $('form').serialize(),
            success: function() {
                console.log("Signup was successful");
            },
            error: function() {
                console.log("Signup was unsuccessful");
            }
        });
    });
}

$(document).ready(function() {
    submit();
});

PHP-signup.php

PHP - signup.php

<?php
  include_once "db_connect.php";

  $post_FirstName = $_POST['first'];
  $post_LastName = $_POST['last'];

  $addData = "INSERT INTO details (firstname, lastname) VALUES ('$post_FirstName', '$post_LastName')";

  if ($conn->query($addData) === TRUE) {
    echo "Working";
  } else {
    echo "Not working";
  }
?>

这是 JSFiddle .

希望你们能提供帮助.在此先感谢:)

I hope you guys can help. Thanks in advance :)

推荐答案

如果使用的是ajax,则无需将输入类型用作submit,请使用button.

If you are using ajax no need to use input type as submit use button.

$(document).ready(function() {
$("#signup").click(function(e) {
    e.preventDefault();
    $.ajax({
  type: 'POST',
  url: 'signup.php',
  data: $('form').serialize()
  success: function() {
    console.log("Signup was successful");
  }
  error: function() {
    console.log("Signup was unsuccessful");
  }
});
});

也可以在这里更改

$post_FirstName = $_POST['first']; // name is `first` not `firstname`

这篇关于在PHP MySQL中使用jQuery AJAX提交表单而无需重新加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆