tags:

views:

41

answers:

4

I want to make POST Ajax calls when users click on text links.

One way to do it is to create many forms and make the submit button a text link. Then with jQuery I will fetch the variables from the form and submit them with Ajax.

This will create something like the following:

<form><input type="hidden" name="unique-id" value="1"><a href="" class="submitForm"></form>
<form><input type="hidden" name="unique-id" value="2"><a href="" class="submitForm"></form>
<form><input type="hidden" name="unique-id" value="3"><a href="" class="submitForm"></form>

Now with jQuery I will use .click() Event handler and send a POST request with the "unique-id" value (from the scope in which the link click was from).

It looks very complicated and messy and I was wondering if there is a better way to do that.

Thanks

Joel

+1  A: 

You don't need a form to do an Ajax post, You feed the data into the Ajax call itself:

$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success
  dataType: dataType
});

See: http://api.jquery.com/jQuery.post/

Diodeus
A: 

If Your forms are something like this:

<form><input type="hidden" name="unique-id" value="1"><a href="" class="submitForm">Submit1</form>

<form><input type="hidden" name="unique-id" value="2"><a href="" class="submitForm">Submit2</form>

<form><input type="hidden" name="unique-id" value="3"><a href="" class="submitForm">Submit3</form>

Then your jQuery will be like this for all above submit links:

jQuery('.submitForm').click( function( ) {

        $.ajax({
            url     : '/path/to/your/action/script',
            type    : 'POST',
            data    : $(this).parent("form").serialize(),
            success : function( response ) {
                        alert(response);        
                      },
            error   : function(){
                        alert('Error');
                      }          

        });

        return false;
});

Remember your submit link for each form is inside the <form> tags then $(this).parent("form") is pointing that form who's link is clicked.

More Detail:

http://api.jquery.com/jQuery.ajax/

NAVEED
A: 

Check Ajaxify Jquery plugin using the new the Forms submit feature its very easy to use and clean

Kronass
+1  A: 

Why not just use the "unique-id" as an id for the links and use that id when posting.

<a id="1" href="#">Link</a>
<a id="2" href="#">Foo</a>
<a id="3" href="#">ASDF</a>


<script type="text/javascript">
    $(function() {
        $("a").click(function(evt) {
            evt.preventDefault();
            $.ajax({
                type: "POST",
                url: url,
                data: "unique-id=" + $(evt.target).attr("id"),
                success: function(data) {
                    alert("done");
                }
            });
        });
    })
</script>
john_doe
Cleanest answer so far gets my vote
Kristoffer S Hansen