Zrom
Zrom

Reputation: 1230

Prevent javascript to execute when i load the html page

I tried to submit my form using ajax so i wrote this script :

$(document).ready(  
function doAjaxPost() {
        var email = $('#user_email').val();
        var firstName = $('#user_firstName').val();
        var lastName = $('#user_lastName').val();
        var password = $('#user_password').val();

        $
                .ajax({

                    type : "POST",
                    async: false ,
                    url : "home1",
                    data : "email=" + email + "&firstName=" + firstName
                            + "&lastName=" + lastName + "&password=" + password,

                    success : function(response) {

                        alert('Error: '+ "test");
                        if(response.result=="error")
                        $('#info').html(
                                response.message);

                    },

                    error : function(e) {

                        alert('Error: ' + e);

                    }

                });

    }
);
$('#myForm').submit(doAjaxPost());

then i included it in my page.html.

but when i load the page the script executed but the script must intercept submit event.

how can i prevent the script to execute when i load my page ?

Upvotes: 2

Views: 917

Answers (3)

forrest
forrest

Reputation: 1

Just swap the last two lines and take out async: false.

Upvotes: 0

Zrom
Zrom

Reputation: 1230

I think I've found a solution by moving my function code into submit scope :

$(document).ready(
$('#myForm').submit(function() {
    var email = $('#user_email').val();
    var firstName = $('#user_firstName').val();
    var lastName = $('#user_lastName').val();
    var password = $('#user_password').val();

    $
            .ajax({

                type : "POST",
                async: false ,
                url : "home1",
                data : "email=" + email + "&firstName=" + firstName
                        + "&lastName=" + lastName + "&password=" + password,

                success : function(response) {

                    alert('Error: '+ "test");
                    if(response.result=="error")
                    $('#info').html(
                            response.message);

                },

                error : function(e) {

                    alert('Error: ' + e);

                }

            });

})
);

Upvotes: 2

Mattia Galati
Mattia Galati

Reputation: 2587

I think your problem is the last line of code:

$('#myForm').submit(doAjaxPost());

whit this code you are saying to jquery to fire the "submit" event to the form. Try to replace it with:

$('#myForm').bind('submit', doAjaxPost);

Upvotes: 0

Related Questions