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:

  1. Send ajax request to runcode.html
  2. 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 
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!