Caramba
Caramba

Reputation: 677

What is the best way to prevent page reload using Jquery(ajax)?

Summary: I have a:

1) main page (Main.php) 2) simple .js script file (dashboard.js) 3) one other simple .php file (form1.php) 4) process.php, a file that processes the information sent by .js file (process.php)

Just like tumblr, I am trying to recreate the same "nav" experience - clicking the several options, replacing the main panel with the new code and when filling up the some form, send that info to BD and present the result in the Main.php

Everything is going well but the last step. After clicking the nav button (main.php), bringing the new form through javascript (dashboard.js + form1.php), filling up that form, I click the button and instead of not reloading the page (jquery->ajax), it sends me to the process.php file and presents me the result.

I have tried not to reload with "return false" and "event.preventdefault()" and still the same result.

JS Code

        $('form.ajax').on('submit', function() {
    event.preventDefault();
    var that = $(this),
    url = that.attr('action'),
    type = that.attr('method'),
    data = {};

    that.find('name').each(function(index, value) {

        var that = $(this),
        name = that.attr('name'),
        value = that.val();

        data[name] = value;

    });


    $.ajax({
        url: url,
        type: type,
        data: data,
        success: function(html){
                    event.preventDefault();
                    $("ol#list-feed").append(html);
                    document.getElementById('set-width1').value='';
                    document.getElementById('tags').value='';

                }


    });
    event.preventDefault();
    return false;
});

Upvotes: 1

Views: 2250

Answers (4)

Peru
Peru

Reputation: 2971

This should work

 $('form.ajax').on('submit', function(event) {

Upvotes: 0

sharif2008
sharif2008

Reputation: 2798

try like this

$('form.ajax').on('submit', function(event) {
    event.preventDefault();
    //do other works here

}

or remove event.preventDefault() from everywhere and before the end of this function just use return false.

Upvotes: 0

hellsgate
hellsgate

Reputation: 6005

You need to change the first line to:

$('form.ajax').on('submit', function(event) {

otherwise the event variable inside the function is undefined.

Upvotes: 0

Jason P
Jason P

Reputation: 27012

You haven't defined event:

$('form.ajax').on('submit', function(event) {
    event.preventDefault();
    //...
});

Upvotes: 3

Related Questions