views:

176

answers:

2

I am trying to keep my AJAX call from posting back to the server when using Prototype.

Code:

  echo " <a href='my.php?action=show&amp;id=".$fid."'
  onclick=\"return  display('".$fid."');\"> ";  
  echo "" .$fname."</a> ";

How can I do this?

+3  A: 

Your display() function should return false; to prevent the default link action from happening.

Paolo Bergantino
yes i have defined return false,but still the page redirect to that link
venkatachalam
Then you're going to need to paste the code. If you are returning false INSIDE the success callback of the AJAX function it would not work because it needs to return false immediately.
Paolo Bergantino
yeah its working !
venkatachalam
A: 

Its pretty easy to do (though I would encourage you to do it unobtrusively via the Event.observe() pattern explained here: http://prototypejs.org/api/event)

Here is a solution that doesn't follow the encouragement I just gave (for the sake of not changing to much of your code and allowing you to easy see what its doing.).

echo " <a href='my.php?action=show&amp;id=".$fid."'
        onclick=\"Ajax.Request(this.href); return false;\"> ";
echo "" .$fname."</a> ";


What might be better is adding a class to this link, something like 'xhr' and then unobtrusively-finding all links with an xhr class and observe for a click and then fire off the xhr request. Here is how I'd do that.

So in your body, change the link element to:

echo '<a href="my.php?action=show&amp;id=' . $fid .'" class="xhr">' . $fname . '</a> ';

Now somewhere your script area do:

<script type="text/javascript" charset="utf-8">
....
// wait for the dom to be loaded (http://prototypejs.org/api/document/observe)
document.observe('dom:loaded',function(){
   // use prototype's $$ utility method to find all the link's 
   // with class xhr (http://prototypejs.org/api/utility/dollar-dollar)
   $$('a.xhr').each(function(link_element){
       // iterate through each of these links and attach the following observer
       link_element.observe('click', function(click_event){
           Ajax.Request(link_element.href);
           // stop() will cancel the click-event from "doing" anything else
           // http://prototypejs.org/api/event/stop
           click_event.stop();
       });
   });
});
</script>

What happens now, is after the dom loads (but before the page is displayed) your click-observer will be attached to all link-elements with the class 'xhr'. It captures the click event, fires off an xhr request, and prevents the event from preforming the default action (in this case following the link to another page) by calling the stop() method.

banderson623
I misread the question and my answer doesn't apply -- I'll keep it up since it outlines how to add unobtrusive behavior to your link element(s)
banderson623