Francesca
Francesca

Reputation: 28118

Using jQuery to submit a form with post vars

I'm trying to use .ajax to submit a form without refreshing the page. But at present, it just refreshes the page and doesn't even reach my script.

I'm calling the function as so. The string being passed through is the URL for the script I wish to run (and submit the post vars to)

<form onsubmit="submitForm('login-register/submit-registration.php')" method="POST">

And the function submitForm() looks like this:

function submitForm(url){
    var url = 'actions/'+url;
    console.log(url);
    $.ajax({
        type: 'post',
        url: url,
        data: $('form').serialize(),
        success: function () {
            $('#success-message').fadeIn("fast");
        }
        });
}

I am seeing my console.logs correctly, so it must be reaching the script, but it is not posting the vars to the script (or even running the script at all, it appears).

Upvotes: 1

Views: 73

Answers (2)

DoubleK
DoubleK

Reputation: 562

html

<form id="myForm" >

js

   var myForm= $('#myForm');
     myForm.submit(function (ev) {
            $.ajax({
                type: 'post',
                url: 'login-register/submit-registration.php',
                data: myForm.serialize(),
                success: function (data) {
                   //something
                }
            });

            ev.preventDefault();
        });

I think this is cleaner solution since you would have cleaner html

Upvotes: -1

dfsq
dfsq

Reputation: 193261

You need onsubmit handler to return false in order to prevent default browser page reload:

<form onsubmit="return submitForm('login-register/submit-registration.php')" method="POST">

And in JS:

function submitForm(url){
    var url = 'actions/'+url;
    $.ajax({
        type: 'post',
        url: url,
        data: $('form').serialize(),
        success: function () {
            $('#success-message').fadeIn("fast");
        }
    });
    return false;
}

As the further improvement, you could get rid of inline event handlers in favor of unobtrusive event binding model. For example like this:

<form action="login-register/submit-registration.php" method="POST">

and then you no longer need submitForm function, you just bind onsubmit event:

$('form').submit(function(e) {
    e.preventDefault();
    $.ajax({
        type: 'post',
        url: 'actions/' + this.action,
        data: $(this).serialize(),
        success: function () {
            $('#success-message').fadeIn("fast");
        }
    });
});

Upvotes: 2

Related Questions