0

User clicks on a menu, and using the following code, the menu $.load()s it's linked content:

$(function() {
    $('#menu a').click(function() {
        $('#content').load(this.href);  
        return false;
    });
});

OK, now the form's loaded. There is still a problem. When the forms is submitted, the result shouldn't bring us to the real action address. So I'm using the following code:

$('#content').on('submit', function() { // catch the form's submit event
    alert('begin');
    $.ajax({ // create an AJAX call...
        data: $(this).serialize(), // get the form data
        type: $(this).attr('method'), // GET or POST
        url: $(this).attr('action'), // the file to call
        success: function(response) { // on success..
            alert('aaaa');
            $('#content').html(response); // update the DIV
        }
    });
    return false; // cancel original event to prevent form submitting
}); 

Unfortunately on is not called and alert('begin'); doesn't work!

Thanks to jquery submit form and then show results in an existing div

Community
  • 1
  • 1
Mohammad Naji
  • 5,372
  • 10
  • 54
  • 79

1 Answers1

0

I had entered the first peace of code, not in $(document).ready(function() {}); and it is working so perfect, but the second code didn't work without the document ready.

But Why? I don't know.

The final code that works now is the one below:

$(document).ready(function()
{
    $('#content').on('submit', 'form', function() { // catch the form's submit event
        alert('begin');
        $.ajax({ // create an AJAX call...
            data: $(this).serialize(), // get the form data
            type: $(this).attr('method'), // GET or POST
            url: $(this).attr('action'), // the file to call
            success: function(response) { // on success..
                $('#content').html(response); // update the DIV
            }
        });
        return false; // cancel original event to prevent form submitting
    }); 

});

Thank you guys for your try.

Mohammad Naji
  • 5,372
  • 10
  • 54
  • 79
  • 1
    "But Why? I don't know." I guess that is because this script is located before the html markup for div#content. It is the point of the .ready(). It seems there were two problems with the code (this wouldn't work without the on(...'form'...) – jbl Mar 19 '13 at 17:07
  • @jbl Yes, you are right. It doesn't work without passing `'form'` as the second parameter. Also thank you for your speech about `$(document).ready()` – Mohammad Naji Mar 20 '13 at 07:59