I have been trying a lot of different ways to make this work, but haven't found the right way to tackle this yet.
I need to make a list of links, each containing a number of querystrings with data. I need this data going to "get.php" through AJAX. Apart from using the data in "get.php" I would like to be able to via PHP change the class of the specific link clicked - for an example from "noshow" to "inattendance" or a third option link "sick".
I am thinking of listing the links like this:
<a href="get.php?athlete=57&session=142" class="noshow">Athlete 1</a>
<a href="get.php?athlete=45&session=142" class="noshow">Athlete 2</a>
<a href="get.php?athlete=23&session=142" class="noshow">Athlete 3</a>
Or perhaps the data should be in the ID to better be recognized in the script?:
<a href="#" id="57&142" class="noshow">Athlete 1</a>
<a href="#" id="45&142" class="noshow">Athlete 2</a>
<a href="#" id="23&142" class="noshow">Athlete 3</a>
Is AJAX able to change a link based on its ID, or would each link need to be inside a DIV?
I would love to get some help regarding where to go from here!
Thanks in advance!
jQuery:
$(function(){
$('a').click(function(e){
e.preventDefault(); // stop the default action from taking you to get.php
var $this = $(this); //cachable reference because $(this) inside the $.ajax() does not refer to the "A" we clicked on
$.ajax({
url: $this.prop("href"), //will pass the data, default is $_GET anyway
dataType: 'json', //so we can easily access the class (if we need) and then the raw data.
success: function(data){
if(data.class != null){
$this.addClass(data.class); //add the class from the php script return
}
//do something with data.body which is the rest of the code
}
});
});
});
Then in your PHP script, just return a json array with the expected keys.
echo json_encode(array(
'class' => 'inactive',
'body' => 'whatever you were returning before'
));
If I understand what you're trying to do correctly, you should use a JavaScript library like jQuery to help you do this.
// bind a click handler to all links that have href starting with get.php
$("a[href^=get.php]").on("click", function(e){
// prevent link from navigating to get.php
e.preventDefault();
// jQuery object of the anchor tag
var $link = $(this);
// use Ajax to send data to get.php
$.getJSON($link.attr("href"), function(data){
// replace current class with the value in data.class
$link.removeClass().addClass(data.class);
});
})
get.php should return json data
header('Content-Type: application/json');
echo json_encode(array(
'class' => 'new class',
));