Basically, I have a list:
<li class="list">fruit</li>
<li class="list">vegetables</li>
<li class="list">protein</li>
And, I want to find the last list item, get the text from it, and then assign it to a php variable, so that:
<?php
$variable = 'p开发者_运维百科rotein';
?>
I'm fuzzy on how to get it into a php variable?
The JavaScript / jQuery Side:
$.post("script.php", { value: $(".list:last").text() }, function (result) {
alert(result); // alerts whatever comes from the php script
});
The PHP Side
print strtoupper( $_POST["value"] );
There is a fundamental difference between Javascript and PHP: PHP runs on the server side, and produces the page's code. JavaScript runs on the client side, after PHP has run and served the content. So you can't pass something "back" from JQuery to PHP. You would have to make an AJAX call to do that. More on how to do that with JQuery here.
But what you're trying to do sounds easy enough to achieve in JQuery alone. Why the PHP?
$.post("script.php", { value: $(".list:last-child").text() }, function(result){
// Your Code
});
if the php is creating all the html, then each time you are printing the list item you could set a variable to the content.
<li class="list"><?PHP echo $var; ?></li><?PHP $yourvar = $var; ?>
<li class="list"><?PHP echo $var; ?></li><?PHP $yourvar = $var; ?>
<li class="list"><?PHP echo $var; ?></li><?PHP $yourvar = $var; ?>
Once the list is finished you will have the last content in a variable.
If you are returning the results from a database then a little more efficient would be finding out how many rows you have returned. then testing that number with the number of the row you are on as you loop through it. You will be able to find the last row then too
精彩评论