简体   繁体   中英

ajax request page redirecting

I am loading a form named staff_view.php in main.php through ajax. It's loading fine but when I submit form to staff_post.php it's redirecting to it instead of showing in console, before I add the code for loading form using ajax it was posting fine but after it's redirecting.

Here is my code

$(document).ready(function() {            
    $('.content_load').load('staff_view.php');
    $('ul#nav li a').click(function() {
        var page = $(this).attr('href');
        $('.content_load').load(page);
        $('form.ajax').on('submit', function() {
            var that = $(this);
            url = that.attr('action'),     
                type = that.attr('method'), 
                data = {};

            that.find('[name]').each(function(index, value) {            
                var that = $(this),
                    name = that.attr('name'),
                    value = that.val();
                    data[name] = value;
            });

            $.ajax({
               url: url,
               type: type,
               data: data,
               success: function(response){
                   console.log(response);
               }
            });
        });
        clearAll();
        return false;
    });
});

function clearAll(){
    $("form :input").each(function(){
        $(this).val(""); 
    });
}

Because it's a form, and because you wish to submit via AJAX instead of the usual "redirect-to-page" method that forms automatically use, you must suppress the default action.

Change this:

$('form.ajax').on('submit', function(){
    var that = $(this);
    etc.

to this:

$('form.ajax').on('submit', function(e){  // <=== note the (e)
    e.preventDefault();                   // <=== e used again here
    var that = $(this);
    etc.

You need to prevent default action when you click anchor tag, and that is redirects you to the link in your href attribute

$('ul#nav li a').click(function(e){
    e.preventDefault(); 
    var page = $(this).attr('href');
    $('.content_load').load(page);
    // code...

This is what cause your redirection

I could be wrong, but it looks like you might have a race condition to load the page and attach the submit listener. The page might load after the $('form.ajax') bit is executed.

$('.content_load').load(page); // Race condition?
$('form.ajax').on('submit', function() {

One fix would be to move the following code into a completion callback:

$('.content_load').load(page, function() {
    $('form.ajax').on('submit', function(e) {
       e.preventDefault();
       // ...
});

Also, add the e.preventDefault(); to prevent the form from actually submitting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM