Alon
Alon

Reputation: 7758

How to create multiple ajax calls in jQuery in more efficient and useful way

I have these 3 links in my code:

<ul>
<li><a id="link1" href="#">link 1</a></li>
<li><a id="link2" href="#">link 2</a></li>
<li><a id="link3" href="#">link 3</a></li>
</ul>

This is how I write the ajax request for each link (as you can see the same code is multiple 3 times for each link - and I want to know how to avoid that)

$(document).ready(function () {
    $("a#link1").click(function() {
        $.get("anothertest.php?q=1", function(data){
            $("#phpTestAlon").html(data);
        });
    });
    $("a#link2").click(function() {
        $.get("anothertest.php?q=2", function(data){
            $("#phpTestAlon").html(data);
        });
    });
    });
    $("a#link3").click(function() {
        $.get("anothertest.php?q=3", function(data){
            $("#phpTestAlon").html(data);
        });
    });
});

What is the way to create this code but without the multiple duplications to make it more efficient? Is there a way to write it like this?:

$.get("anothertest.php?q=" + theIDofTheElement, function(data){

thanks, Alon

Upvotes: 2

Views: 509

Answers (3)

Amir Raminfar
Amir Raminfar

Reputation: 34149

You can do

$("ul li a").click(function() {
        e.preventDefault()
        $.get(this.href, function(data){
            $("#phpTestAlon").html(data);
        });
    });

With this HTML:

<ul>
<li><a id="link1" href="anothertest.php?q=1">link 1</a></li>
<li><a id="link2" href="anothertest.php?q=2">link 2</a></li>
<li><a id="link3" href="anothertest.php?q=3">link 3</a></li>
</ul>

It is important that this solution also works if javascript is disabled. return false will make sure if js is enabled to not actually go to a different page. But if js was disabled, then the user would just go to whatever linked they clicked on.

Upvotes: 0

zoli
zoli

Reputation: 468

 var  theIDofTheElement = $(this).attr('id').match(/\d$/)[0];

Upvotes: 0

Bojangles
Bojangles

Reputation: 101483

Add a data-id attribute to your link and use one piece of JS:

<ul>
    <li><a id="link1" href="#" data-id="1">link 1</a></li>
    <li><a id="link2" href="#" data-id="2">link 2</a></li>
    <li><a id="link3" href="#" data-id="3">link 3</a></li>
</ul>

$("ul li a").click(function() {
    var idToSend = $(this).data('id');

    $.get("anothertest.php?q=" + idToSend, function(data){
        $("#phpTestAlon").html(data);
    });
});

This example uses data-id, but you could use any attribute you wanted, including id="". Another sensible option would be rel="".

Notice the selector has changed to ul li a so as to capture all <a> clicks in one event.

Upvotes: 5

Related Questions