简体   繁体   中英

Passing js variable to php variable

I want to pass the id value of the tag that has just been clicked to a php file that is being loaded onto the page using greybox.

I got the id stored in a js variable called linkID and I can get it passing the correct id using location.href but this needs a page reload and doesnt work alongside greybox. Can and maybe how can I use Ajax to help send this info in the background? Any help would be greatly appreciated?

The Javascript to get the id of the clicked a tag

<script type="text/javascript">
function myCallback(caller)
{
  var linkID =caller.id; 
  location.href="species/butterfly.php?linkID=" + linkID;
  alert(linkID);
  }
</script>

The html a tag in index.php

<div id="stump">
<a href="#" id="2" class="hedgehog descript"  title="Hedgehog"
 rel="gb_page_center[1020, 550]" onclick="myCallback(this)"></a>
</div><!--close stump div -->

The butterfly.php page that is trying to recieve the id

<?php
// Retrieve the URL variables (using PHP).
$linkid = $_GET['linkID'];
echo "Number: ".$linkid;
?>

This will convert js variable to php variable

<script>
function sud(){

javavar=document.getElementById("text").value;  

document.getElementById("rslt").innerHTML="<?php 
$phpvar='"+javavar+"'; 
echo $phpvar.$phpvar;?>";
}

function sud2(){
document.getElementById("rslt2").innerHTML="<?php 
echo $phpvar;?>";
}

</script> 
<body>
<div id="rslt">
</div>

<div id="rslt2">
</div>
<input type="text" id="text" />
<button onClick="sud()" >Convert</button>
<button onClick="sud2()">Once Again</button>

</body>
var myCallback = function(caller){
    var linkID = caller.id; 

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST","species/butterfly.php",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("linkID="+linkID;);

    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
            alert("Request complete. Data: "+xmlhttp.responseText);
        }
    };

    alert(linkID);
 }

EDIT:

Pure GreyBox:

var myCallback = function(caller){
    var linkID = caller.id; 
    caller.href = "species/butterfly.php?linkID="+linkID;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM