DaveLar DaveLar - 4 months ago 19
jQuery Question

Using dynamic links to trigger ajax

I have a couple of links that I want to trigger operations through ajax from, but I dont know how to continue on this matter. I've kind of solved it for static links but my links are dynamic and there will be different amount of links at different stages.

I have a index.php that looks like this:

<script src="../jquery-3.1.0.min.js"></script>
<script>
$(document).ready(function() {
$("#link1").click(function(e) {
e.preventDefault();
$('#result').empty().text('Executing command...');
$('#result').load('ajax.php?op=edit&id=4', function(){
$('#result').before("The server answered:");
$('#result').after("The operation was a success<br>");
}); // end load
}); //end click
}); //end ready()
</script>

<div id='result'></div>
<a id='link1' href='#'>Link 1</a><br>
<a id='link2' href='#'>Link 2</a><br>
<a id='link3' href='#'>Link 3</a><br>
<a id='link4' href='#'>Link 4</a><br>
<a id='link5' href='#'>Link 5</a><br>
<a id='link6' href='#'>Link 6</a><br>


And the "ajax" file looks like this:

<?php
if(isset($_GET['op']) && isset($_GET['id'])) {
$op = $_GET['op'];
$id = $_GET['id'];
switch($op) {
case "edit":
// do operations here
echo $id;
break;
case "doSomethingElse":
// do other operations here
echo $id;
break;
}
}
?>


So what I struggle with now is: How do I solve this so I don't have to define each link within the jquery ready() function?

Edit:
Basicly I need to trigger an operation in the ajax.php file depending on what link I click.

Any ideas?

Answer

Try this selector;

$('[id^="link"]')

$(document).ready(function() {
  $('[id^="link"]').click(function(e) {
     e.preventDefault();
     $('#result').empty().text('Executing command...'); 
     $('#result').load('ajax.php?op=edit&id=4', function(){         
        $('#result').before("The server answered:");
        $('#result').after("The operation was a success<br>");
    }); // end load
  }); //end click
}); //end ready()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id='result'></div>
<a id='link1' href='#'>Link 1</a><br>
<a id='link2' href='#'>Link 2</a><br>
<a id='link3' href='#'>Link 3</a><br>
<a id='link4' href='#'>Link 4</a><br>
<a id='link5' href='#'>Link 5</a><br>
<a id='link6' href='#'>Link 6</a><br>