prakashchhetri
prakashchhetri

Reputation: 1816

why is my ajax script reloading my page

I am using ajax to submit a form. Well the script I am using is just to test the form where some plain text is echoed in processform.php. However when I click on the submit button, nothing gets alert and the page gets reloaded.

isnt that return false supposed to prevent from it. And when I delete the ajax part, every thing goes well.

Where am i doing it wrong?

$("#submit").click(function(){
      $("#sidebar .message").show();
      $(".sidebar-content").hide();

      $.ajax({
        type: "POST",
        url: "processform.php",
        data: { name: "John", location: "Boston" }
      }).done(function( msg ) {
        alert( "Data Saved: " + msg );
      });

      return false;
    });

Upvotes: 0

Views: 252

Answers (2)

Ruben Infante
Ruben Infante

Reputation: 3135

If the element #submit is a button or input with type="submit", it will likely trigger a default behavior to send data to whatever the form action happens to be.

You can either change the type to be type="button" which does not have a default behavior of submitting data or use event.preventDefault() in your click handler to block the default behavior.

$("#submit").click(function(e){
    e.preventDefault();
    ...
});

If you want your alert to trigger when your ajax request is successful, you can use the success option instead of .done().

$("#submit").click(function () {
    $("#sidebar .message").show();
    $(".sidebar-content").hide();

    $.ajax({
        type: "POST",
        url: "processform.php",
        data: {
            name: "John",
            location: "Boston"
        },
        success: function(msg) {
            alert("Data Saved: " + msg);
        },
        error: function() {
            alert("Error occurred");
        }
    });

    return false;
});

jsfiddle

Upvotes: 1

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114437

The simple solution: change your submit button to type="button" instead of "submit".

Upvotes: 2

Related Questions