April 20, 2012
Run PHP code when user clicks link and pass variables
Question by user1323294
I need to run a PHP code from external server when user clicks a link. Link can’t lead directly to PHP file so I guess I need to use AJAX/jQuery to run the PHP? But how can I do it and how can I pass a variable to the link?
Something like this?
<a href="runcode.html?id=' + ID + '">
and then runcode.html will have an AJAX/jQuery code that will send that variable to PHP?
Answer by Anwar
use something like this in you page with link
Some text
in the same page put this somewhere on top
<script language='javascript'>
$(function(){
$('.myClass').click(function(){
var data1 = 'someString';
var data2 = 5;//some integer
var data3 = "<?php echo $somephpVariable?>";
$.ajax({
url : "phpfile.php (where you want to pass datas or run some php code)",
data: "d1="+data1+"&d2="+data2+"&d3="+data3,
type : "post",//can be get or post
success: function(){
alert('success');//do something
}
});
return false;
});
});
</script>
on the url mentioned in url: in ajax submission
you can fetch those datas passed
for examlple
<?php
$data1 =$_POST['d1'];
$data2 =$_POST['d2'];
$data3 =$_POST['d3'];
//now you can perform actions as you wish
?>
hope that helps
Answer by Starx
You can do this with an ajax request too. The basic idea is:
- Send ajax request to runcode.html
- Configure another AJAX to trigger from that page
Considering, this as the markup
<a id="link" href="runcode.html'">Test</a>
JS
$("#link").on("click", function() {
$.get("runcode.html", { "id" : ID }, function(data) {
//on success
});
return false; //stop the navigation
});