Php – jQuery AJAX Redirection problem

ajaxjqueryPHPredirect

please consider this: On page A I have a link that takes you to page B when JS is off, but when JS is on, I want to replace content on current page with content from the page B.

Pages A and B are in fact the same script that is able to tell AJAX calls from regular ones and serve the content appropriately. Everything works fine, as long as there are no redirects involved.

But, sometimes there is a 301 redirect and what seems to be happening is that client browser then makes a second request, which will return with a 200 OK. Only the second request is sent without a X-Requested-With header, therefore I cannot tell within my script wether it came from AJAX or not, and will send a complete page instead of just the content.

I have tried checking for 301 status code in my error, success, and complete handlers but none of them worked. It seems to be handling the 301 behind the scenes.

Could anyone help me with this?

jQuery 1.4, PHP 5

Edit: People requested the code to this, which I didn't think was necessary but here goes:

// hook up menu ajax loading
$('#menu a').live("click", function(){
    // update menu highlight
    if($(this).parents('#menu').size() > 0){
        $("#menu>li").removeClass("current_page_item");
        $(this).parent().addClass("current_page_item");
    }
    // get the URL where we will be retrieving content from 
    var url = $(this).attr('href');

    window.location.hash = hash = url;

    $.ajax({
        type: "GET",
        url: url,
        success: function(data){
            // search for an ID that is only present if page is requested directly 
            if($(data).find('#maincontent').size() > 0){
                data = $(data).find('#maincontent .content-slide *').get();
            }
            // the rest is just animating the content into view
            $("#scroller").html(data);
            $('.content-slide').each(setHeight);

            $('.content-slide').animate({
                    left: "0px"
                }, 1000, 'easeOutQuart', 
                function(){
                    $('#home').css("left", "-760px").html(data);
                    $('#scroller').css("left", "-760px");
                    $('.content-slide').each(setHeight);
                }
            );
        }
    });

    return false;
});

Best Answer

Due to the fact that the headers aren't being passed properly after the redirect, it seems like a good option would be to allow for a query string variable to indicate the isAjax status of a request as well as the x-requested-with header. So if your 301 redirects are being generated by an .htaccess file, you'd just need to pass the query string arguments onto the new path when redirecting. For instance:

RewriteEngine on
RewriteRule pageB.php$ pageC.php?%{QUERY_STRING} [L,R=301]

So your request for pageB.php?isAjax=1 will be pageC.php?isAjax=1, resulting in the properly formatted response from the server.