使用JQuery提交AJAX表单

Lately I've noticed from looking through our Google Analytics and our search popularity, we have been coming up a lot for AJAX Forms. Now we have this other article, Submitting AJAX Forms: The AngularJS Way. That seems to be why people find us when searching for AJAX forms, but the Angular way just isn't the way they want.

最近,从我们的Google Analytics(分析)和搜索的流行程度来看,我注意到AJAX Forms的使用非常多 。 现在,我们还有另一篇文章,《 提交AJAX表单:AngularJS Way》 。 这似乎就是为什么人们在搜索AJAX表单时会找到我们的原因,但是Angular方式并不是他们想要的方式。

Today we'll be looking at AJAX forms, the non-Angular way and using jQUery. This is to hopefully help those people coming to our site and looking for something other than the Angular version.

今天,我们将研究AJAX表单,非Angular方式以及使用jQUery。 希望能帮助那些访问我们网站并寻找除Angular版本以外的内容的人。

我们将建立什么 (What We'll Build)

There are a few basic requirements usually asked from forms. We want:

通常有一些从表格中提出的基本要求。 我们想要:

  • Process a form without a page refresh using AJAX

    使用AJAX处理表单而不刷新页面
  • Client side validation

    客户端验证
  • Server side validation (validation from the PHP side)

    服务器端验证(来自PHP端的验证)
  • Showing a processing icon while our form is... processing

    正在处理表单时显示处理中的图标
  • Showing errors if there are any

    显示错误(如果有)
  • Showing success if the form is submitted correctly

    如果表单提交正确,则显示成功

processing-ajax-forms-with-jquery

入门 (Getting Started)

Let's get started processing our form. We will need three different things for this:

让我们开始处理表单。 为此,我们需要三件事:

  • A way to process the form (we'll be using PHP, but you can use anything you want)

    一种处理表单的方法(我们将使用PHP,但是您可以使用任何您想要的东西)
  • A view to show the form

    显示表单的视图
  • The JavaScript and AJAX (jQuery flavored) to make it all work

    JavaScript和AJAX(jQuery风格)使其全部正常工作

处理表单process.php (Processing the Form process.php)

This will be the easiest part. Since we're using PHP, we can just create a simple script to process our form. Let's call it process.php (clever I know), and make the code for that.

这将是最简单的部分。 由于使用的是PHP,因此我们可以创建一个简单的脚本来处理表单。 让我们将其称为process.php (我知道很聪明),并为此编写代码。

We will provide support to send back JSON data (which is what our JavaScript code will be processing after our PHP or any server side code sends back information). We will also send back errors and error messages in the data that we send back.

我们将提供支持以发送回JSON数据(这是在我们PHP或任何服务器端代码发送回信息之后,我们JavaScript代码将处理的内容)。 我们还将在发送回的数据中发送回错误和错误消息。

We will just check to see if a variable exists or not. There are many more validations that you can do like checking to see if there is a valid email, but we'll just focus on the required status.

我们将仅检查变量是否存在。 您可以执行许多其他验证操作,例如检查是否有有效的电子邮件 ,但我们仅关注所需的状态。

<?php
// process.php

$errors         = array();      // array to hold validation errors
$data           = array();      // array to pass back data

// validate the variables ======================================================
    // if any of these variables don't exist, add an error to our $errors array

    if (empty($_POST['name']))
        $errors['name'] = 'Name is required.';

    if (empty($_POST['email']))
        $errors['email'] = 'Email is required.';

    if (empty($_POST['superheroAlias']))
        $errors['superheroAlias'] = 'Superhero alias is required.';

// return a response ===========================================================

    // if there are any errors in our errors array, return a success boolean of false
    if ( ! empty($errors)) {

        // if there are items in our errors array, return those errors
        $data['success'] = false;
        $data['errors']  = $errors;
    } else {

        // if there are no errors process our form, then return a message

        // DO ALL YOUR FORM PROCESSING HERE
        // THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)

        // 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);

Notice in PHP, to pass data back to our JavaScript call, you want to echo json_encode(). Using a return like you normally would in a function wouldn't provide JSON data back.

注意在PHP中,要将数据传递回我们JavaScript调用,您需要echo json_encode() 。 像平常那样在函数中使用return不会提供JSON数据。

Now that we have the form processing worked out, we'll create our form.

现在我们已经完成了表单处理,我们将创建表单。

显示表格index.html (Showing the Form index.html)

We will be using Bootstrap to build out our views. It's just easier since all their classes are already pre-built and we can create our view quickly.

我们将使用Bootstrap建立我们的视图。 因为它们的所有类都已经预先构建,因此我们可以快速创建视图,因此更加容易。

We will place all of the code we need for our view and inject errors into the view later.

我们将放置视图所需的所有代码,然后在视图中注入错误。

<!-- index.html -->

<!doctype html>
<html>
<head>
    <title>Look I'm AJAXing!</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"> <!-- load bootstrap via CDN -->

    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <!-- load jquery via CDN -->
    <script src="magic.js"></script> <!-- load our javascript file -->
</head>
<body>
<div class="col-sm-6 col-sm-offset-3">

    <h1>Processing an AJAX Form</h1>

    <!-- OUR FORM -->
    <form action="process.php" method="POST">

        <!-- NAME -->
        <div id="name-group" class="form-group">
            <label for="name">Name</label>
            <input type="text" class="form-control" name="name" placeholder="Henry Pym">
            <!-- errors will go here -->
        </div>

        <!-- EMAIL -->
        <div id="email-group" class="form-group">
            <label for="email">Email</label>
            <input type="text" class="form-control" name="email" placeholder="rudd@avengers.com">
            <!-- errors will go here -->
        </div>

        <!-- SUPERHERO ALIAS -->
        <div id="superhero-group" class="form-group">
            <label for="superheroAlias">Superhero Alias</label>
            <input type="text" class="form-control" name="superheroAlias" placeholder="Ant Man">
            <!-- errors will go here -->
        </div>

        <button type="submit" class="btn btn-success">Submit <span class="fa fa-arrow-right"></span></button>

    </form>

</div>
</body>
</html>

processing-ajax-forms-with-jquery

使用AJAX magic.js提交表单 (Submitting the Form using AJAX magic.js)

To submit a form via AJAX, we will need to do certain things in our JavaScript file.

要通过AJAX提交表单,我们需要在JavaScript文件中执行某些操作。

  • Capture the form submit button so that the default action doesn't take place

    捕获表单提交按钮,以便不执行默认操作
  • Get all of the data from our form using jQuery

    使用jQuery从我们的表单中获取所有数据
  • Submit using AJAX (we'll go through a few ways)

    使用AJAX提交(我们将通过几种方式进行提交)
  • Show errors if there are any

    显示错误(如果有)

We'll start our JavaScript file by getting data from our form and sending a POST request to our already create PHP script (process.php).

我们将通过从表单中获取数据并将POST请求发送到我们已经创建PHP脚本( process.php )来启动JavaScript文件。

// magic.js
$(document).ready(function() {

    // process the form
    $('form').submit(function(event) {

        // get the form data
        // there are many ways to get this data using jQuery (you can use the class or id also)
        var formData = {
            'name'              : $('input[name=name]').val(),
            'email'             : $('input[name=email]').val(),
            'superheroAlias'    : $('input[name=superheroAlias]').val()
        };

        // process the form
        $.ajax({
            type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
            url         : 'process.php', // the url where we want to POST
            data        : formData, // our data object
            dataType    : 'json', // what type of data do we expect back from the server
                        encode          : true
        })
            // using the done promise callback
            .done(function(data) {

                // log data to the console so we can see
                console.log(data); 

                // here we will handle errors and validation messages
            });

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

});

Now when we press submit on our form, our JavaScript code will get all the input values that we need and send a POST request to process.php.

现在,当我们在表单上按Submit时,我们JavaScript代码将获取我们需要的所有输入值 ,并将POST请求发送到process.php

Promise Callbacks: We will be using the .done callback to handle a successful AJAX request. This used to be called .success but that has since been deprecated in jQuery 1.8+.

承诺回调 :我们将使用.done回调来处理成功的AJAX请求。 以前称为.success但此后在jQuery 1.8+中已弃用。

获取表格数据序列化的另一种方法 (Another Way to Get Form Data serialize)

You could also use serialize instead of pulling the form information individually.

您也可以使用序列化而不是单独提取表单信息。

看到JSON数据回来了 (Seeing JSON Data Come Back)

Our PHP script will process the inputs that our AJAX call sent and spit back the $data[] array that we created. You can see this in your browser's console after you submit your form.

我们PHP脚本将处理AJAX调用发送的输入,并吐回我们创建的$data[]数组。 提交表单后,您可以在浏览器的控制台中看到此内容。

ajax-form-console-error
You can access any of these attributes as part of your data object. Just use the . to get to a specific item.

您可以将任何这些属性作为data对象的一部分进行访问。 只需使用即可. 转到特定项目。

处理错误 (Handling Errors)

In our PHP script, we are only checking to make sure that all the fields are required. If a field is not present, we send an error back. We'll want to inform our user of this error.

在我们PHP脚本中,我们仅检查以确保所有字段都是必需的。 如果没有字段,我们将发送回一个错误。 我们希望将此错误通知我们的用户。

We're going to add errors under each of the inputs. The Bootstrap classes help us do this so let's go ahead and handle those errors and inject them into our page if they happen.

我们将在每个输入下添加错误。 Bootstrap类可以帮助我们做到这一点,所以让我们继续处理这些错误,如果发生错误,将它们注入到我们的页面中。

// magic.js

...

// process the form
$.ajax({
    type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
    url         : 'process.php', // the url where we want to POST
    data        : formData, // our data object
    dataType    : 'json' // what type of data do we expect back from the server
})
    // using the done promise callback
    .done(function(data) {

        // log data to the console so we can see
        console.log(data);

        // here we will 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
            }

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

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

        } else {

            // ALL GOOD! just show the 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

        }

    });

...

Now if there are any errors that come back from our server, we can show them like so:

现在,如果服务器中出现任何错误,我们可以像这样显示它们:

ajax-form-error
And if our AJAX form was successful:

如果我们的AJAX表格成功完成:

ajax-form-success

清除错误 (Clearing Errors)

Every time we submit the form, our errors from our previous submission are still there. We just need to clear them by removing them as soon as the form is submitted again.

每次我们提交表单时,我们先前提交的错误仍然存​​在。 我们只需要在再次提交表单后通过删除它们来清除它们。

// magic.js

...

// process the form
$('form').submit(function(event) {

    $('.form-group').removeClass('has-error'); // remove the error class
    $('.help-block').remove(); // remove the error text

...

显示服务器错误 (Showing Server Errors)

If there is an error in our server-side code, we won't get any feedback from our AJAX call. We'll just be left there scratching our heads. There's a simple solution to that: we'll add an errorattribute to our AJAX call.

如果我们的服务器端代码有错误,我们将不会从AJAX调用中获得任何反馈。 我们将只剩下挠头。 有一个简单的解决方案:我们将一个error属性添加到我们的AJAX调用中。

// magic.js

...

// process the form
$.ajax({
    type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
    url         : 'process.php', // the url where we want to POST
    data        : formData, // our data object
    dataType    : 'json' // what type of data do we expect back from the server
})
    // using the done promise callback
    .done(function(data) {
        ...
    })

    // using the fail promise callback
    .fail(function(data) {

        // show any errors
        // best to remove for production
        console.log(data);
    });

...

Now if there are any errors in our PHP code (maybe a missing semicolon), they will show. You'll probably want to not show errors when you move your application live though so remember to handle that accordingly.

现在,如果我们PHP代码中有任何错误(可能是缺少分号),它们就会显示出来。 您可能不希望在实时移动应用程序时不显示错误,因此请记住相应地进行处理。

ajax-form-jquery-fail

进行AJAX呼叫的不同方法 (Different Ways To Do AJAX Calls)

If you don't want to write all that AJAX code out every time, there's an easier way! You can use the jQuery POST Shorthand method. This let's you simplify your code and still get the same results.

如果您不想每次都写完所有的AJAX代码,那么有一种更简单的方法! 您可以使用jQuery POST Shorthand方法。 这使您可以简化代码,并且仍然获得相同的结果。

The above code would be the equivalent of:

上面的代码等效于:

$.post('process.php', function(formData) {

        // place success code here

    })
        .fail(function(data) {
            // place error code here
        });

Much cleaner!

干净得多!

结论 (Conclusion)

Submitting forms using AJAX is a fairly easy process and hopefully this helped you on your journey in creating forms and processing them without a page refresh.

使用AJAX提交表单是一个相当简单的过程,希望这可以帮助您在创建表单和处理表单的过程中无需刷新页面。

This article only covers the server-side validation part of forms. You'll want to look at doing client-side validation as well and doing more than just required validation. There are plenty of resources out there to push forward and as always, ask questions in the comments if you need any help!

本文仅介绍表单的服务器端验证部分。 您将要同时进行客户端验证,而不仅仅是所需的验证。 有很多资源可以推动,并且如往常一样,如果需要任何帮助,请在评论中提问!

Moving Forward: If you want to see another cool way to process an AJAX form, check out our other article that uses AngularJS to submit forms.

前进 :如果您想了解另一种处理AJAX表单的好方法,请查看我们使用AngularJS提交表单的另一篇文章。

翻译自: https://scotch.io/tutorials/submitting-ajax-forms-with-jquery

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值