简体   繁体   中英

How to get link specific php varaible to pass through ajax

I dont know much about ajax or jquery yet but i currently have an ajax script that does successfully send A variable through and does work properly.

-- the way i have it set up is like this for my loop:

<?php  

$tt= mysql_query("SELECT * FROM monsters");

while ($row= mysql_fetch_array($tt))
{
$namee= $row['name'];

echo "<a id='namee' onclick='post();'>$namee</a>", "</br>";
}

which echos:

    horseman
    dragon

---the results do make a list of all the names from the table as shown above and they are clickable which is working great

my ajax request is this:

<script type="text/javascript">

function post(){

var hr = new XMLHttpRequest();

var url = "mess.php";
var vars =document.getElementById("namee").innerHTML;

hr.open("POST", url, true);

hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

hr.onreadystatechange = function() {
  if(hr.readyState == 4 && hr.status == 200) {
    var return_data = hr.responseText;
  document.getElementById("new").innerHTML = return_data;
  }
}

hr.send(vars);     // Actually execute the request  

alert(vars); 
 }


  </script>

the alert when i click on horseman returns "horseman" but when i click on dragon it still alerts "horseman"

i would like to get the specific variable ( when i click horseman it says horseman and when i click dragon it says dragon etc) so i can send it through ajax to update a database ( which i already know to to set up)

please help me and show me if you can full code so i can learn and see how it works and understand your response since im new like i said :)

thanks in advance:
if have any questions feel free to ask

Thats because ids should be unique, jquery will get only the first element with that id, my suggestion is to pass the value by parameter:

echo "<a class='namee' onclick='post($namee);'>$namee</a>", "</br>";

And then the js:

function post(vars) {
    var hr = new XMLHttpRequest();
    var url = "mess.php";
    hr.open("POST", url, true);
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    hr.onreadystatechange = function () {
        if (hr.readyState == 4 && hr.status == 200) {
            var return_data = hr.responseText;
            document.getElementById("new").innerHTML = return_data;
        }
    }
    hr.send(vars); // Actually execute the request  
    alert(vars);
}

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