How can I send the value from php to ajax?
How can I send the value of PersonID into edit.php when user clicks on the <a>
tag?
<?php
$result = mysql_query("SELECT PersonID, FirstName, LastName, Age FROM persons");
echo "<table>";
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>Name: ".$row['FirstName']." ".$row['LastName'].", Age: ".$row['Age']."</td>";
?>
<td>
<a class="edit" name="<?php echo $row['PersonID'] ?>">Edit</a>
</td>
<?php
echo "</tr>";
}
echo "</table>";
?>
Here's the unfinish ajax,
<script type="text/javascript" language="javascript">
$("a.edit").click(function(){
$(this).closest("tr").after("<div id=\"editform\"></div>");
$.ajax({
url: "edit.php",
// -- WHAT SHOULD BE THE NEXT STEP? --
});
});
&开发者_StackOverflow中文版lt;/script>
Thanks!
Quick and dirty way, you can get the value of PersonID from the tag itself, and then send it as part of the querystring:
<script type="text/javascript" language="javascript">
$("a.edit").click(function(){
$(this).closest("tr").after("<div id=\"editform\"></div>");
var personid = $(this).attr("name");
$.ajax({
url: "edit.php?personID=" + personid,
success : function () { /* Add success callback here */ }
});
});
</script>
This is assuming you want to do it with a GET request. A cooler (and RESTful) way would be to do it with a POST request, and send the personID as a parameter in the request body:
<script type="text/javascript" language="javascript">
$("a.edit").click(function(){
$(this).closest("tr").after("<div id=\"editform\"></div>");
var personid = $(this).attr("name");
$.ajax({
url: "edit.php,
type : "POST",
data : { personID : personid },
/* add callback etc here */
});
});
</script>
In this case, you'd have to modify edit.php to fetch the personID parameter from the request, not from the querystring.
In the case of a GET request
<script type="text/javascript" language="javascript">
$("a.edit").click(function(){
var id = $(this).attr("name");
$(this).closest("tr").after("<div id=\"editform\"></div>");
$.ajax({
url: "edit.php" + id,
success: function(response) {
// Do whatever
}
});
});
</script>
In the case of a POST request
<script type="text/javascript" language="javascript">
$("a.edit").click(function(){
var id = $(this).attr("name");
$(this).closest("tr").after("<div id=\"editform\"></div>");
$.ajax({
url: "edit.php",
data: { id: id },
success: function(response) {
// Do whatever
}
});
});
</script>
精彩评论