简体   繁体   中英

Jquery Ajax post empty input value to the php

I have a problem with Jquery Ajax posting.
Previously I was using

<form method="post" action="manageUserItem.php">....</form> 

to post my input value and insert into database.
But when I try to change to jquery ajax function with this code:

$.validator.setDefaults({
        submitHandler: function() {
            var formData = new FormData($(this)[0]);    
                $.ajax({
                    url:'manageUserItem.php',
                    type: 'POST',
                    data: formData,
                    async: false,
                    beforeSend: function(){
                        if(confirm('Are you sure?'))
                            return true;
                        else
                            return false;
                    },
                    cache: false,
                    contentType: false,
                    processData: false
                }).done(function () {
                        //do something if you want when the post is successfully
                        if(!alert('New User Created.')){document.getelementbyclassname('form').reset()}
                }).fail(function () {
                        //if the post is failed show an error message if you want
                        alert('Some error occur. Please try again later.');
                });
                return false;
        }
    });

then my input field for name, userid and password become empty when insert into the database.
Is there anything wrong in my code?

Please give me some advice, because I'm still new to this.

您可以尝试以下方法:

var formData = new FormData(document.forms[0]);

You have a problem here :

var formData = new FormData($(this)[0]);    

In this context "this" - is submitHandler

Try use class or id of form like

   var formData = new FormData($(".myFormClass")[0]);    

Try to serialize the data:

var formdata = $( "form" ).serialize();
console.log(formdata);

And to a console.log()

Output would look something like:

name=john_doe&user_id=1&password=my_passowrd

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