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>
<?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;
}
}
?>
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>