Marcus Tan
Marcus Tan

Reputation: 417

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.

Upvotes: 0

Views: 781

Answers (3)

henrik123
henrik123

Reputation: 1683

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

Upvotes: 0

xAqweRx
xAqweRx

Reputation: 1236

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]);    

Upvotes: 1

Brijesh Bhatt
Brijesh Bhatt

Reputation: 3830

You can try this:

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

Upvotes: 2

Related Questions