Reputation: 507
I'm trying to make script with JavaScript which is dynamic, yes I know, JavaScript is always dynamic but I want to do in combination with PHP.
JS:
$(document).ready(function(){
$("#glcheckmail").click(function(){
$("#glmaildiv").load('/functions/glist-MailChecker.php');
});
});
PHP:
echo "<div class=\"list-group-item\" data-toggle=\"modal\" href=\"#\"><span class=\"badge badge-danger\"><a href=\"#\" class=\"donothover\">Delete</a></span>
<div style=\"white-space:nowrap; overflow:hidden; text-overflow:ellipsis; width:80%;\">". $row['attach_name'] ." (<i>". formatSizeUnits($row['attach_size']) ."</i>)</div></div> ";
As you can see I have an "<a href="">"
with Delete in it. What I'm trying to accomplish is actually something like this (Example Not Real Code!)
<a href="#" id="RefToJS" onclick="<? echo $attach_id; ?>">
Now (hypothetically) my JavaScript should see a variable in #RefToJS
. And I want to pass this variable on to the PHP script which loads onclick
, like this
$(document).ready(function(){
$("#glcheckmail").click(function(){
$("#glmaildiv").load('/functions/glist-MailChecker.php?id='+ONCLICK_CODE);
});
});
This is sort of what I want but as you can see, the code isn't a beauty and I have to little knowledge of JavaScript to make this work
Upvotes: 0
Views: 1237
Reputation: 7556
Ok so first I would take an approach similar to @pmandell but I would make a few changes. First off instead of using id
I would use a data attribute to prevent conflicts something like this:
echo "<a href='#' class='delete-link' data-id='{$PHP_ID}'>Delete</a>";
Second since you are adding these to the DOM via ajax you should use on
to prevent issues with events not being bound to the new links you are creating. So here is what the javascript should look like:
$(document).on('click','.delete-link',function(e) {
e.preventDefault();
var linkID = $(this).data('id');
$("#glmaildiv").load('/functions/glist-MailChecker.php?id='+ linkID);
});
Upvotes: 0
Reputation: 4328
There are a few ways you could go about it. This is how I would do it:
PHP:
echo "<a href='#' class='link-class' id='" . $PHP_ID . "'>Delete</a>";
JavaScript
$('.link-class').click(function(e){
e.preventDefault(); //prevent default link action
var linkID = $(this).attr('id'); //retrieve the ID of the clicked link
$("#glmaildiv").load('/functions/glist-MailChecker.php?id='+ linkID);
});
Upvotes: 3