user34537
user34537

Reputation:

Ajax Links and jquery

Going with the just jquery it joke i was wondering in my website i have a link that says "Add". After clicking it the page refreshes and it says remove. I figure this would be better with ajax and not require the page to reload. How do i do this with jquery (should i do it in jquery?) and how do i know when the server receives the add so i can update my picture (i am sure there is a processing/complete state?)

Upvotes: 1

Views: 17411

Answers (6)

clinton3141
clinton3141

Reputation: 4841

jQuery AJAX functions let you specify success and failure functions which you can use to update your page.

$("#mylink").click (function (event) {
  $.ajax({
    type: "POST", // or GET
    url: "/my/address.php",
    data: "someData=someThing&someMore=somethingElse",
    success: function(data) {
      $("#someElement").doSomething().
    },
    error: function() {
      // something's gone wrong.
    }
  });

  event.preventDefault(); // stop the browser following the link
});

For more read the jQuery AJAX page - it has loads of examples).

Upvotes: 7

powtac
powtac

Reputation: 41080

This would be the needed jQuery function: http://docs.jquery.com/Events/toggle

Upvotes: 0

jjclarkson
jjclarkson

Reputation: 5954

You should do this with jQuery :)

something like...

$("#input").click(function(){
    if( $("#input").val() == "add" ) {
        $("#input").val("remove");
    }
});

Throw some ajax in there to do the work.

Upvotes: 0

Rishav Rastogi
Rishav Rastogi

Reputation: 15492

You can do it Jquery,its a great tool for it.

Basically, add a click event handler to your link as given below:

<a href="/url" id="add-button">  Add </a>

<script>

function callback(response) {
  // remove add button here and add the "remove " button
 }

 $('#add-button').click( function() {
   $.get( this.href, data, callback);
  //or
   $.post( this.href, data, callback);
 }

</script>

Upvotes: 1

kgiannakakis
kgiannakakis

Reputation: 104196

Quick intro to jquery.

HTML:

<a href="#" id="mylink"><img src="add.jpg"/></a>

Javascript:

$(function() {
   //Everything inside here is called on page-load

   // This selects the link element by its id and add an onclick handler
   $("#mylink").click(function() {
        post_url = (The url to post to the server);
        $.post(url, function() {
           // This is called when the AJAX finishes successfully.

           // Select the image element and modify the src attribute
           $("#mylink img").attrib("src", "remove.jpg");
        });
   });
});

Upvotes: 0

Natrium
Natrium

Reputation: 31204

  • Make a function that get's triggered when the link is clicked.
  • make an ajax-call to server.
  • You can define a callback-method that will be triggered if the ajax-call is successful.
  • In the callback-function: change Add to Delete.

In a nutshell :-)

Upvotes: 1

Related Questions