【问题标题】:Adding AJAX/jQuery to simple PHP Form将 AJAX/jQuery 添加到简单的 PHP 表单
【发布时间】:2015-02-12 22:42:59
【问题描述】:

我了解如何仅使用 PHP 制作一个简单的表单,但现在我正在尝试了解如何将 AJAX/jQuery 添加到此过程中。

不幸的是,我对 AJAX/jQuery 的了解还不够,看不出我做错了什么。

我一直在关注一个设置 AJAX 表单的教程,但它实际上并没有写入 MYSQL 数据库。我已经在代码中添加了数据库和 PDO,但是当我提交时,我没有收到错误,也没有提交到数据库。

有人能指出我缺少什么吗?

index.html

<h1>Processing an AJAX Form</h1>

    <form action="process.php" method="POST">
        <!-- Name -->
        <div id="name-group">
            <label for="name">Name</label>
            <input type="text" name="name" placeholder="Name">
            <!-- Errors -->
        </div>

        <!-- Class -->
        <div id="class-group">
            <label for="class">Class</label>
            <input type="text" name="class" placeholder="Class">
            <!-- Errors -->
        </div>

        <button type="submit">Submit</button>
    </form>

script.js

$(document).ready(function() {

// Process form
$('form').submit(function(event) {
    $('.form-group').removeClass('has-error'); // Remove the error class
    $('.help-block').remove(); // Remove the error text

    // Get form data
    var formData = {
        'name': $('input[name=name]').val(),
        'class': $('input[name=class]').val()
    };

    // Process form
    $.ajax({
        type: 'POST',
        url: 'process.php',
        data: formData, // Data object
        dataType: 'json', // Type of data expected back from server
        encode: true
    })

        // Using the done promise callback
        .done(function(data) {

            // Log data to the console
            console.log(data);

            // Handle errors and validation messages
            if (!data.success) {

                // Handle errors for name
                if (data.errors.name) {
                    $('#name-group').addClass('has-error'); // Add the error class to show red input
                    $('#name-group').append('<div class="help-block">' + data.errors.name + '</div>'); // Add the actual error message under our input
                }

                if (data.errors.class) {
                    $('#class-group').addClass('has-error'); // Add the error class to show red input
                    $('#class-group').append('<div class="help-block">' + data.errors.class + '</div>'); // Add the actual error message under our input
                }
            } else {
                // Show success message
                $('form').append('<div class="alert alert-success">' + data.message + '</div>');

                // usually after form submission, you'll want to redirect
                // window.location = '/thank-you'; // redirect a user to another page
                //alert('success'); // for now we'll just alert the user
            }
        })

        .fail(function(data) {

            console.log(data);
        });

    // Stop form from submitting the normal method and refreshing the page
    event.preventDefault();
});
});

process.php

<?php

require_once 'database.php';

$errors = []; // Array to hold validation errors
$data   = []; // Array to pass back data

$name  = $_POST['name'];
$class = $_POST['class'];

// Validate the variables
// If variables do not exist, add an error to $errors array
if (empty($name)) {
    $errors['name'] = 'Name is required';
}

if (empty($class)) {
    $errors['class'] = 'Class is required';
}

// Return a response
// If there are any errors in errors array, return a success boolean of false
if (!empty($errors)) {
    // If there are errors in errors array, return those errors
    $data['success'] = false;
    $data['errors']  = $errors;
} else {
    // If there are no errors process form, then return message

    // Form processing here
    $pdo = Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO class(name, class_id) values(?, ?)";
    $query = $pdo->prepare($sql);
    $query->execute(array(
        $name,
        $class
    ));
    Database::disconnect();

    // Show a message of success and provide a true success variable
    $data['success'] = true;
    $data['message'] = 'Success!';
}

// Return all our data to an AJAX call
echo json_encode($data);

【问题讨论】:

  • 您说添加 POST 变量时它不起作用 - 您是否确保调用了脚本?您可以通过打开开发者控制台、转到网络选项卡然后提交表单来在 chrome 中进行测试 - 如果一切顺利,您应该会看到面板上附加了一个 process.php 脚本,检查此处的标题并查看您的数据是否发送:)

标签: php jquery ajax forms


【解决方案1】:

$name$class 已使用但未赋值,请为其赋值。

$name = $_POST['name'];
$class = $_POST['class'];

【讨论】:

  • 感谢添加这个和更新的问题,但没有运气仍然没有输入到 MYSQL 并且没有错误。
  • 重新检查代码,我在.js中更改了一些不正确的字段。但是使用您的建议有效。
猜你喜欢
  • 2017-03-24
  • 1970-01-01
  • 2013-04-12
  • 2011-01-22
  • 1970-01-01
  • 2015-08-14
  • 1970-01-01
  • 1970-01-01
  • 2017-08-14
相关资源
最近更新 更多