views:

509

answers:

2

I need to redirect an Ajax call without letting the client know.

getPage.php is an application which returns html etc. for a given query.

getPage.php?hash=interesting-article-title and getPage.php?page=3 returns the same.

To avoid the client from having to cache both of these I would like getPage.php?hash=interesting-article-title to REDIRECT to getPage.php?page=3 via PHP header 301 and location.

I tried doing this and it returns nothing. The ajax call does not seem to want to be redirected.

Does anyone have any idea what could solve this double-cache problem?

I would like to use 301 redirects because they are cacheable. This way the browser would automatically call page=3 when it is told to fetch hash=insteresting-article-title.

Code examples:

 function handleInit(event) {
  if (event.path != "/") {
   var hash = event.path.replace(/\//,"").replace(/\?/g,"");
   getPage(hash);
   currentState.hash = hash;
  } else {
   currentState.id = 1;
  }
  SWFAddress.addEventListener(SWFAddressEvent.CHANGE, handleChange);
 }


 function chapter_forward() {
  if (!freeze) {
   freeze = true;
   getPage(currentState.id - 1);
  }
 }


 function ajax_data(id) {
  return typeof(id) == "string" ? "hash=" : "page=";
 }

 function getPage(id) {
  $.ajax({
   method: "get",
   url: getPage.php,
   data: ajax_data(id) + id.toString(),
   dataType: 'json',
      timeout: 2000,
      error: function() {
    $("#space-3").html('40104 - Request Timeout');
      },
   complete: function() {},
   success: function(result) {
    handleContent(result);
   }
  });
 }

The reason I need the redirect to happen is because I get the id from a HASH when the user uses his back and forth browser buttons.

When the user simply navigates back and forth I simply add +1 to the current id.

getPage.php returns something like this:

{"article_id":"3","hash":"music-in-your-ear","title":"Music in your ear.","html":"Blah blah article 3","modified":"Fri, 20 Mar 2009 02:46:00 GMT"}

Thanks!

+1  A: 

If you look at this answer, the correct behaviour for browsers is to not cache urls with query params.

I dont know if 301 redirect even works when you are basically accessing the same url.

I suggest you go through your code and only use one of those links if they return the same thing.

OIS
I really wouldn't use both if it was not necessary.
Willem
+1  A: 

If you are using apache, mod-rewrites and a rewrite map file are an excellent way to solve this server side assuming your hash is a predefined list of terms that map to the specified IDs.

I am assuming you are doing this for SEO benefits?

Pete
Indeed I am using Apache and they are predefined. However the process of adding items into mod-rewrite would have to be dynamic for users to be able to do it via a form.Could you please define SEO. Thanks!
Willem
Search Engine Optimization
NVRAM