将AJAX / jQuery添加到简单的PHP表单中

时间:2015-02-12 22:43:00

标签: php jquery ajax forms

我理解如何使用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);

1 个答案:

答案 0 :(得分:0)

$name$class已使用但未分配,请为其指定值。

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