通过jquery ajax php发送动态表单

时间:2014-09-02 07:17:13

标签: javascript php jquery ajax forms

我有一张宠物登记表,人们可以在这里添加新宠物。

人们会点击添加宠物按钮,jquery克隆表单的宠物部分,并将id更改为#pet-2,另一个,#pet-3等等。

在无效的网络搜索之后,我现在需要知道如何通过php和ajax发送它。

我已经为我的联系表单创建了一个ajax函数,并且有php代码来发送联系表单,理想情况下,想要在单独的文件中修改该代码以处理寄存器宠物。

这是小提琴:http://jsfiddle.net/zsxe44c8/

以下是添加宠物表格的代码:

<form id="register-pet-form" data-quantity="1">

            <fieldset id="practiceField" class="row">

                <div class="col-md-6 push-md-6">

                    <h3>Practice</h3>

                    <select name="practice">
                        <option value="">Value 1</option>
                        <option value="">Value 2</option>                    
                    </select>

                </div>

            </fieldset>
            <!--/#practiceField-->

            <fieldset id="ownerDetails" class="row">

                <div class="col-md-6">

                    <h3>Your details</h3>
                    <select name="title">
                        <option value="Mr">Mr</option>
                        <option value="Mrs">Mrs</option>
                        <option value="Miss">Miss</option>
                        <option value="Ms">Ms</option>
                        <option value="Dr">Dr</option>
                        <option value="Prof">Prof</option>
                    </select>

                    <input name="fname" type="text" placeholder="First Name">

                    <input name="lname" type="text" placeholder="Last Name">

                    <input name="number" type="text" placeholder="Contact Number">

                    <input name="email" type="text" placeholder="Email Address">

                </div>

                <div class="col-md-6">

                    <h3>Your Address</h3>

                    <input name="address1" type="text" placeholder="Address 1">

                    <input name="address2" type="text" placeholder="Address 2">

                    <input name="address3" type="text" placeholder="Address 3">

                    <input name="postcode" type="text" placeholder="Postcode">

                </div>

            </fieldset>
            <!--/#ownerDetails-->

            <fieldset id="pet-1" class="row">

                <div class="col-md-12">

                    <h3>Pet Details</h3>

                </div>

                <div class="col-md-6">

                    <input name="pet-name" type="text" placeholder="Pet Name">

                    <input name="pet-breed" type="text" placeholder="Pet Breed">

                    <input name="pet-age" type="text" placeholder="Age of pet">

                </div>

                <div class="col-md-6">

                    <select name="petGender">
                        <option value="Female">Female</option>
                        <option value="Male">Male</option>
                    </select>

                    <select name="petType">
                        <option value="Dog">Dog</option>
                        <option value="Cat">Cat</option>
                        <option value="Rabbit">Rabbit</option>
                        <option value="Gerbil">Gerbil</option>
                        <option value="Guinea Pig">Guinea Pig</option>
                        <option value="Hamster">Hamster</option>
                        <option value="Mouse">Mouse</option>
                        <option value="Rat">Rat</option>
                        <option value="Chinchilla">Chinchilla</option>
                        <option value="Other">Other</option>
                    </select>

                </div>

                <div class="col-md-12">


                    <input name="pet-desc" type="text" placeholder="Pet Description">

                    <textarea name="additional-comments" placeholder="Additional Comments"></textarea>


                </div>

            </fieldset>
            <!--#petDetails-->

            <div id="form-tools" class="row">

                <div class="col-md-6">

                    <a class="add-pet" href="#">Add another pet</a>

                </div>

                <div class="col-md-6 right">

                    <input type="submit" value="Submit">

                </div>

            </div>
            <!--/#form-tools-->

        </form>

以下是添加宠物表单的jQuery代码:

function registerPet() {

    function addPetRegistrationForm() {
        var container = $('#register-pet-form'),
            lastForm = $('#register-pet-form fieldset:last-of-type'),
            currentForm = $('#pet-1'),
            newForm = currentForm.clone(),
            currentVal = parseInt(container.attr('data-quantity'), 10),
            newVal = currentVal + 1;

        $('h3', newForm).after('<a data-id="' + newVal + '" class="js-remove-pet remove-pet" href="#">Remove this pet</a>');

        $('input, select', newForm).each(function () {

            var newId = this.id.substring(0, this.id.length - 1) + newVal;

            $(this).prev().attr('for', newId);

            this.name = this.id = newId;
        });

        lastForm.after(newForm.attr('id', 'pet-' + newVal));
        container.attr('data-quantity', newVal);
    }

    function removePetRegistrationForm(target) {
        $('#pet-' + target).remove();
    }

    function handleRegisterPet() {

        if($('#pet-1').length) {

            $('#pet-1').addClass('ispet');

            $('#pet-1 *[name]').each(function(){

                $(this).attr('name',$(this).attr('name') + '[]');
            });

            var newBlock = $('#pet-1').html();

            $('#pet-1').after('<a href="" class="form-button-2" id="js-add-pet">Add another pet</a>');

            $('.add-pet').on('click',function() {

                var count = $('.ispet').length + 1;

                $('.ispet').last().after('<fieldset id="pet-'+ count +'" class="ispet">' + newBlock + '</fieldset>');

                return false;

            });
        }
    }

    $('.add-pet').on('click', function () {
        addPetRegistrationForm();
        return false;
    });

    $('#register-pet-form').on('click', '.js-remove-pet', function () {
        removePetRegistrationForm($(this).attr('data-id'));
        return false;
    });
}

现在这里是ajax联系表单的代码正在运行,我希望修改添加宠物表单:

function ajaxForm(formID) {
    var form = $(formID);
    var formMessages = $('#form-messages');
    $(formMessages).hide();
    $(form).submit(function(event) {
        event.preventDefault();
        var formData = $(form).serialize();
        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })
        .done(function() {
            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');
            $(form).hide();
            $('#fname').val('');
            $('#lname').val('');
            $('#email').val('');
            $('#phone').val('');
            $('#message').val('');
            $(formMessages).html(
                '<div class="alert alert-success" role="alert"><i class="fa fa-check"></i> <strong>Your message has been sent successfully</strong></div>'
            ).fadeIn();

        })
        .fail(function() {
            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');
            if (data.responseText !== '') {
                $(formMessages).text(data.responseText);
            } else {
                $(formMessages).text('Oops! An error occured and your message could not be sent.');
            }
        });
    });

}

function practiceOneContact() {
    ajaxForm('#practice-1-contact-form');
}
function practiceTwoContact() {
    ajaxForm('#practice-2-contact-form');
}
function practiceThreeContact() {
    ajaxForm('#practice-3-contact-form');
}
function practiceFourContact() {
    ajaxForm('#practice-4-contact-form');
}

最后,我希望修改的联系表单处理程序的PHP代码允许添加宠物形式的动态宠物:

<?php

    // Only process POST reqeusts.
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Get the form fields and remove whitespace.
        $fname = strip_tags(trim($_POST["fname"]));
                $fname = str_replace(array("\r","\n"),array(" "," "),$fname);
        $lname = strip_tags(trim($_POST["lname"]));
                $lname = str_replace(array("\r","\n"),array(" "," "),$lname);
        $phone = strip_tags(trim($_POST["phone"]));
                $phone = str_replace(array("\r","\n"),array(" "," "),$phone);
        $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
        $message = trim($_POST["message"]);
        $sendTo = strip_tags(trim($_POST["sendTo"]));
        $practice = trim($_POST["practice"]);

        echo 'field editing done';

        // Check that data was sent to the mailer.
        if ( empty($fname) OR empty($lname) OR empty($phone) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            // Set a 400 (bad request) response code and exit.
            echo "Oops! There was a problem with your submission. Please complete the form and try again.";
            exit;
        }

        // Set the recipient email address.
        $recipient = $sendTo;

        // Set the email subject.
        $subject = "New contact from $fname $lname";

        // Build the email content.
        $email_content = "Practice Name: $practice\n";
        $email_content .= "First Name: $fname\n";
        $email_content .= "Last Name: $lname\n";
        $email_content .= "Email: $email\n\n";
        $email_content .= "Phone: $phone\n\n";
        $email_content .= "Message:\n$message\n";

        // Build the email headers.
        $email_headers = "From: $fname $lname <$email>";

        echo 'section build done';

        // Send the email.
        if (mail($recipient, $subject, $email_content, $email_headers)) {
            // Set a 200 (okay) response code.
            echo "Thank You! Your message has been sent.";
        } else {
            // Set a 500 (internal server error) response code.
            echo "Oops! Something went wrong and we couldn't send your message.";
        }

    } else {
        // Not a POST request, set a 403 (forbidden) response code.
        echo "There was a problem with your submission, please try again.";
    }

此项目的URLS如下:http://cvs.dev.dannycheeseman.me/base/about-us/register-your-pets/

注册宠物:http://cvs.dev.dannycheeseman.me/base/contact-us/

感谢您的时间。

1 个答案:

答案 0 :(得分:7)

好像你想发布整个表单,包括动态生成的输入文件。

如果是这样,那么你会想看到使用输入数组。

<form method="POST" action="whereever.php>
    <input type="text" name="name[]" value="Dog" />
    <input type="text" name="name[]" value="Cat" />
    <input type="text" name="name[]" value="Snake" />
</form>

发送表单时(无论是通过基本还是AJAX),PHP脚本可以将输入作为数组读取

<?php
echo $_POST['name'][0]."<br>";
echo $_POST['name'][1]."<br>";
echo $_POST['name'][2]."<br>";
?>

上面的脚本将输出

Dog
Cat
Snake

这可以应用于所有输入。 这有帮助吗?

<强>加成

所以在你的情况下,你可以这样做:

<form>
<section>
Pet # 1
<input type="text" name="name[]">
<input type="text" name="lastname[]">
</section>

<section>
Pet # 2
<input type="text" name="name[]">
<input type="text" name="lastname[]">
</section>

<section>
Pet # 3
<input type="text" name="name[]">
<input type="text" name="lastname[]">
</section>
</form>

动态阅读POST

foreach($_POST["name"] as $key => $value)
{
    echo $value;

    /*or if you want to loop while accessing other fields too, you can do this*/

    echo "<br>".$_POST["name"][$key];
    echo "<br>".$_POST["lastname"][$key];

    /*this way you can access the other fields with the same <section> as well, just make sure you do not mess with the input placement*/
}