简体   繁体   中英

Serialize form data to PHP

I've inherited some PHP code, never having worked with it before, and I'm stuck. I've tried to use echo like I would console.log() in JS, but I'm hardly getting into the script.

I'm trying to post 3 input values and a select option to PHP code, and email that information off to someone. Fairly simple I would assume.

HTML

        <form method="post" class="contact-form" id="register-form">
            <fieldset> 
                <input type="text" name="first_name" placeholder="First Name" class="col-xs-12 col-sm-12 col-lg-12 input-text" id="firstName" required>

                <input type="text" name="last_name" placeholder="Last Name" class="col-xs-12 col-sm-12 col-lg-12 input-text" id="lastName" required>

                <input type="text" name="location_preference" placeholder="Location Preference" class="col-xs-12 col-sm-12 col-lg-12 input-text" id="locationPreference" required>

                    <select name="internType" style="width: 100%; display: block; color: #000;" id="internType" required>
                        <option selected="" value="default">Please Select</option>
                        <option value="inside">Inside</option>
                        <option value="outside">Outside</option>
                        <option value="open">Open</option>
                    </select>
                <button name="submit" type="submit" class="btn btn-success submitinformation pull-right" id="submit"> Submit</button>
                <button name="reset" type="reset" class="btn btn-success submitinformation pull-right" id="reset"> Reset</button>

            </fieldset> 
        </form> 

Pretty basic..

JavaScript

    var PATH =  'processor.php';
    var APP = 'wse01010';

    $("#register-form").on("submit", function(e){
    e.preventDefault();

        var errors = 0;
        var inputs = $('input:text, #internType'); 

            $(inputs).map(function(){
                if( !$(this).val() || $(this).val() == "default") {
                  $(this).addClass('warning'); //Add a warning class for inputs if Empty
                  errors++;
            } else if ($(this).val()) {
                  $(this).removeClass('warning');
            }   
            });

    var formData = $(this).serialize();
    console.log(formData);
    //console.log($(this)[0]);
    //var formData = new FormData( $(this)[0] );
    //console.log(formData);

            if(errors < 1) {
            // If no errors, send POST
                $.ajax({
                    url: PATH + '?i=' + APP,
                    type: 'POST',
                    data: formData,   
                    async: true,
                    success: function (data) {
                    alert("Success");
                },
                    error: function(xhr, textStatus, errorThrown){
                           alert('Request failed. Please try again.');
                        }

                });
            }

    });

This alerts Success every time.

PHP

$firstName = $_POST['first_name'];

        if( !isset( $_POST['first_name'] ) ) {
        var_dump($_POST);  // This gives me an empty array: array(0) { }
                $outcomeArr = array(
                                        'outcome'=>'failure',
                                        'message'=>'Step 1 failed.'
                                    );
            echo json_encode( $outcomeArr );
            exit();
        }

        unset( $_POST['submit'] );

        $postVar = print_r($_POST,true);
        //Other code omitted

Here's how the data is being passed.

在此处输入图片说明

I'm not sure how to get my Form Data into the correct format (if that's the issue), or why PHP isn't recognizing my POST . I'm also not sure of any other checks I should be doing to validate the POST .

This is the JavaScript that ended up working for me

var form_processor = {

settings : {
    'outcome' : -1,
    'status' : 0, // 0 == correct, 1 == errors detected
    'error_msg' : '',
    'path' : 'processor.php',
    'app' : 'wse01010'
},


sendData : function(formData){
    var self = this;
            $.ajax({
                        url: self.settings.path + '?i=' + self.settings.app ,  
                        type: 'POST',
                        data: formData,   
                        async: true,
                        success: function (data) {
                            toastr.success('Your request went through!', "Success")
                        },
                        error: function(xhr, textStatus, errorThrown){
                           toastr.error("Something went wrong. Please try again.", "Error!")
                        },
                        cache: false,
                        contentType: false,
                        processData: false
            });
},

bindForm : function(){
    var self = this;
    $('.contact-form').submit(function(e){
        self.settings.formObj = $(e.target);

        e.preventDefault();

        var errors = 0;
        var inputs = $('input:text, #internType'); 

        $(inputs).map(function(){
                if( !$(this).val() || $(this).val() == "default") {
                  $(this).addClass('warning'); //Add a warning class for inputs if Empty
                  errors++;
            } else if ($(this).val()) {
                  $(this).removeClass('warning');
            }   
        });

        if( errors > 0 ) {  
            self.settings.status = 0;
            self.settings.error_msg = '';   
            toastr.error("Please fill in all of the fields.", "Error!")             
            return false
        } else {
            formData = new FormData( $(this)[0] );
            self.sendData(formData);
        }
    });
},
init : function(){
    this.bindForm();
}
}
form_processor.init();

In your PHP, you start off with this:

echo "1";

When using AJAX, an echo is the same as a return , so this is where your function stops. Remove all unnecessary echo 's or your function will simply not continue.

Furthermore, you are using spaces in your HTML name attributes:

<input type="text" name="first name"> <!-- Incorrect -->

Use underscores instead or you will not be able to retrieve the value properly:

<input type="text" name="first_name"> <!-- Correct -->

Afterwards, $firstName = $_POST["first_name"]; is the correct way to retrieve your values in PHP.

I recommend to not use space in name so change that in firstname etc.

for serializing u need this.

$(function() {
    $('#register-form').on('submit', function(e) {
        var data = $("#register-form").serialize();
        $.getJSON("http://YOUR PHP FILE TO CATCH IT &",data)
                  });
});

on your php page use $_GET['firstname'] for example and add that to a variable.

Your code is setting the content type of the form twice, and both times incorrectly:

  • Drop enctype="multipart/form-data" from the <form> tag. (This is for file uploads)
  • Drop contentType: "application/json; charset=utf-8" from the jQuery ajax() call. (This is for JSON, which PHP does not understand natively)

The correct encoding is application/x-www-form-urlencoded , which is the default value for both the <form> tag and the ajax() call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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