Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将AJAX/jQuery添加到简单PHP表单_Php_Jquery_Ajax_Forms - Fatal编程技术网

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

将AJAX/jQuery添加到简单PHP表单,php,jquery,ajax,forms,Php,Jquery,Ajax,Forms,我知道如何只用PHP制作一个简单的表单,但我现在正试图了解如何将AJAX/jQuery添加到这个过程中 不幸的是,我对AJAX/jQuery了解不够,看不出我做错了什么 我一直在遵循一个教程,该教程设置了一个AJAX表单,但实际上它并没有写入MYSQL数据库。我在代码中添加了数据库和PDO,但是当我提交时,我没有收到错误,也没有提交到数据库 有人能指出我遗漏了什么吗 index.html <h1>Processing an AJAX Form</h1> <

我知道如何只用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>
处理AJAX表单
名称
等级
提交
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();
});
});
$(文档).ready(函数(){
//过程形式
$('form')。提交(函数(事件){
$('.form group').removeClass('has-error');//删除错误类
$('.help block').remove();//删除错误文本
//获取表单数据
var formData={
'name':$('input[name=name]')。val(),
'class':$('input[name=class]')。val()
};
//过程形式
$.ajax({
键入:“POST”,
url:'process.php',
data:formData,//数据对象
dataType:'json',//预期从服务器返回的数据类型
编码:正确
})
//使用done承诺回调
.完成(功能(数据){
//将数据记录到控制台
控制台日志(数据);
//处理错误和验证消息
如果(!data.success){
//处理名称的错误
if(data.errors.name){
$(“#名称组”).addClass('has-error');//添加错误类以显示红色输入
$(“#名称组”).append(“”+data.errors.name+“”);//在输入下添加实际的错误消息
}
if(data.errors.class){
$(“#类组”).addClass('has-error');//添加错误类以显示红色输入
$(“#类组”).append(“”+data.errors.class+“”);//在输入下添加实际的错误消息
}
}否则{
//显示成功消息
$('form').append(“”+data.message+“”);
//通常在表单提交之后,您需要重定向
//window.location='/thank-you';//将用户重定向到其他页面
//alert('success');//现在我们只提醒用户
}
})
.失败(功能(数据){
控制台日志(数据);
});
//停止表单提交正常方法并刷新页面
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);

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

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

谢谢你添加了这个更新的问题,但是没有运气仍然没有输入到MYSQL中,也没有错误。重新检查代码,我在.js中更改了一些不正确的字段。但是使用你的建议是有效的。你说当你添加POST变量时它不起作用-你确保脚本被调用了吗?您可以在chrome中测试这一点,方法是打开开发者控制台,转到网络选项卡,然后提交表单-如果一切正常,您应该会看到一个
process.php
脚本附加到面板上,检查此处的标题并查看是否发送了数据:)