views:

480

answers:

2

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 = 'protein';

?>

I'm fuzzy on how to get it into a php variable?

+3  A: 

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?

Pekka
+2  A: 

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"]);
Jonathan Sampson
Simple and clean.
Ariel