2

I'm using ajax to post the form data. In the end I want to redirect to homepage. I'm trying following code, it does not work. It returns error 302. How can I redirect in the following function? Thanks.

add_action('wp_ajax_nopriv_custom_register', 'custom_register');
add_action('wp_ajax_custom_register', 'custom_register');

function custom_register(){

    //process

    wp_redirect( home_url() );
    exit;
}
4

The AJAX request runs in the background. Redirects here do not affect the main page. And 302 is not an error, it is just a status code.

Your AJAX response should return either the URL and the status code to the calling page or just a number like 1. Then you handle the redirect in the calling page:

jQuery( document ).ready( function( $ ) {
    var url = '<?php echo home_url(); ?>';
    $( '#ajaxtrigger' ).on( 'click',
        function() {
            $.post( ajaxurl, {}, function( response ) {
                if ( 1 == response )
                    top.location.replace(url);
            });
            return false;
        }
    );
});
| improve this answer | |
-2

If you want to redirect then use javascript window.lcation="your url" in your php code.

Try this in your function that is called by the ajax call;

add_action('wp_ajax_nopriv_custom_register', 'custom_register');
add_action('wp_ajax_custom_register', 'custom_register');

function custom_register(){

    //process

    $url = home_url(); 

    ?>
       <script>

        demo(); //function name of jscript

        function demo()
        {
            window.location="<?php echo $url ?>";
        }

       </script>

    <?php exit;
}
| improve this answer | |
  • 2
    How does this answer the question? – Johannes Pille Sep 30 '14 at 9:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.