-2

Let's say I have the following code:

<a href="index.php">Link</a>

When the link is clicked I want it to pass on a POST value named a containing b, so that I on index.php can reach it with $_POST['a']. I understand that this is a job for AJAX, but how?

Zebra123
  • 1
  • 1

3 Answers3

1

it is going to be something like this:

  1. create a handler on the anchor
  2. since you're using jQuery you can use the AJAX helpers. THere is a simpler "post" method in the jQuery API docs but i don't bother with it. (notice the statement about post() being shorthand version of ajax()

e.g.

$('a').on('click', function () {
    $.ajax({
        type: "POST",
        url: "index.php",
        data: {
            "a": "b"
        },
        success: function () {
            // a function called after POST   
        }  // end success
    }); // end ajax

    // optional code here that is run asynchronously from the POST above but also triggered by the click
           return false; 
}); // end on click
gillyspy
  • 1,578
  • 8
  • 14
  • I can't seem to get your code to work. The link takes me to index.php, where I run print_r($_POST), but nothing is ever returned. I suspect that I haven't "created a handler on the anchor", whatever that means. – Zebra123 May 01 '13 at 01:38
  • the handler in the the `'click'` event delegated by the `on()` method. Because you're using a link to index.php in the html I can't tell where your problem is. Perhaps to keep things simple change your `a` (anchor) to a different element like a `p`. Since we're adding a `click` handler we don't need to use the anchor's default event. You won't get the nice finger-pointer but we're just simplifying things for now. However, i added a `return false` above though which should stop the default request. If you do stay with an anchor then maybe change it to `` – gillyspy May 01 '13 at 13:23
0

First you'll need to learn a little more about JQuery Ajax functions:

http://www.w3schools.com/jquery/jquery_ajax_intro.asp

The examples there should be a good start for what you want. Update your question if you have any specific question.

Francisco Afonso
  • 247
  • 1
  • 15
0

Try taking a look at the jQuery.post() documentation page. The 2nd example listed shows you how to pass data explicitly to a specific URL such as "index.php".

Marty
  • 241
  • 1
  • 2
  • 5