简体   繁体   English

通过jQuery Ajax PHP发送动态表单

[英]Sending a dynamic form via jquery ajax php

I have a pet registration form where people can add a new pet. 我有一个宠物登记表,人们可以在其中添加新的宠物。

People will click the add pet button and jquery clones the pet portion of the form and changes the id to #pet-2, another, #pet-3 and so on. 人们将点击添加宠物按钮,jquery克隆表单的宠物部分,并将id更改为#pet-2,另一个,#pet-3等。

After fruitless web searching, I now need to know how to send this via php and ajax. 经过无用的网络搜索之后,我现在需要知道如何通过php和ajax发送此消息。

I have already created an ajax function for my contact forms as well as have php code to send the contact forms so would, ideally, want to modify that code in a separate file to handle the register pet also. 我已经为我的联系表创建了一个ajax函数,并具有php代码来发送联系表,因此,理想情况下,我想在一个单独的文件中修改该代码以处理注册宠物。

Here is the fiddle: http://jsfiddle.net/zsxe44c8/ 这是小提琴: http : //jsfiddle.net/zsxe44c8/

Here is the code for the add pet form: 以下是添加宠物表单的代码:

<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>

Here is the jQuery code for the add pet 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;
    });
}

Now here is the code for the ajax contact form that is working and I wish to modify for the add pet form: 现在,这是正在运行的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');
}

And finally, the PHP code for the contact form handler that I wish to modify to allow for dynamic pets from the add pet 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.";
    }

The URLS for this project are as follows: http://cvs.dev.dannycheeseman.me/base/about-us/register-your-pets/ 该项目的URLS如下: http//cvs.dev.dannycheeseman.me/base/about-us/register-your-pets/

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

Thank you for your time. 感谢您的时间。

Seems like you want to post the whole form, including the input files generated dynamically. 好像您要发布整个表单,包括动态生成的输入文件。

if so, then you will want to see into using array of input. 如果是这样,那么您将希望了解使用输入数组的情况。

<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>

When the form is sent (whether by basic or AJAX), the PHP script can read the input as an array 发送表单时(无论是通过Basic还是AJAX),PHP脚本可以将输入作为数组读取

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

above script will output 以上脚本将输出

Dog
Cat
Snake

This can be applied to all input. 这可以应用于所有输入。 Does this help? 这有帮助吗?

Addition 加成

So in your case, you can do it like this: 因此,就您而言,您可以这样操作:

<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>

To read the POST dynamically 动态读取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*/
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM