user376112
user376112

Reputation: 869

ajax post reload page

My index.jsp page, load my form with this line of code :

 $('#box').load('/Edit_Data.jsp?id=' + myID);

Then, I can correctly edit the data presents in the form. When I've finished, I click on a button that triggers this function :

function save() {
  $.ajax({
    type: 'POST',
  cache: false,
     url: '/Edit_data',
    data: $('form[name="formData"]').serialize(),
  complete : function(jqXHR,textStatus) {
    alert("complete " + jqXHR.responseText );
    },
  error: function(jqXHR,textStatus){
        alert("status " + textStatus + ", response :" + jqXHR.responseText);
     }
   });

}

and my java servlet for the path "/Edit_data", return this :

  resp.setCharacterEncoding("UTF-8");
  resp.setContentType("text/xml");
  String xml = "<report><error_msg></error_msg></report>";
  resp.getWriter().println(xml);

The behavior after I clicked on the button is :

  1. The request is correctly sent
  2. I receive the error alert message : status error, response :
  3. Then, I receive the complete message :complete (the responseText is null)
  4. Finally, it reloads my index.jsp page with a Get request with the parameters that I sent to the servlet. Like that : http://localhost:8888/index.jsp?name=test&firstname=test

My problem is : why after the ajax request has been done, the index.jsp page is reloaded. The correct behavior should be : after the request, nothing sould be done because I handle the complete function

One clue should be the error message returned by the servlet, but I can't see the full content of the error so I don't understand what triggers the error...

One other important clue, I only have this problem with firefox and chrome. It works correctly for IE.

Could you help me to solve that?

Thank you very much,

Bat

Upvotes: 3

Views: 5595

Answers (2)

karim79
karim79

Reputation: 342765

Looks like your form gets submitted the "classic" way, because you are not preventing the form's default action. Try adding a return false to the end of your save function, or binding a handler to your form's submit event:

$("#theForm").submit(function (e) {

    // prevent normal submit behaviour
    e.preventDefault();
});

Upvotes: 4

Manish Shrivastava
Manish Shrivastava

Reputation: 32070

Ajax means asynchronous request... It should not reload ideally,If you didn't do any mistake. Well, you can use return false; Or on calling ajax function onclick="return AjaxFunction(); For your case it might be : onclick="return save();

Hope this will solve your issue.

Cheers!

Upvotes: 6

Related Questions