douhuan1497 2015-03-25 11:31
浏览 43
已采纳

将表单数据序列化为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.

enter image description here

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();
  • 写回答

3条回答 默认 最新

  • dph87312 2015-03-25 11:37
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?