Search code examples
javascriptjqueryajaxformspage-refresh

jQuery unexpected refresh of page when submit an AJAX form


I have a problem, with AJAX submit of forms.

I have a piece of code like that:

$("#content").html("<form id='requestInfo'>............</form");

That put in a div with id=content the piece of code that creates a form.

I have another piece of code:

$("#requestInfo").submit(function( event ) {
  event.preventDefault();
  ...code...
});

I would expect an execution of the code inside the submit() method where I can do my things with data of that form, but I get a refresh of the page, instead.

Does anyone know what could be the problem? It should be compatible with all browsers.

Thanks!


Solution

  • You are creating your form dynamically thus standard event binding will not work. You need to use event delegation

    $("#content").on('submit', '#requestInfo', function(evt) {
        evt.preventDefault();
    });