n00b0101
n00b0101

Reputation: 6893

jquery - find last element with a certain class and pass it to php?

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?

Upvotes: 8

Views: 19766

Answers (4)

Sampson
Sampson

Reputation: 268384

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"] );

Upvotes: 21

Andrew Atkinson
Andrew Atkinson

Reputation: 4251

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

Upvotes: 0

Vijay
Vijay

Reputation: 11

$.post("script.php", { value: $(".list:last-child").text() }, function(result){
 // Your Code
});

Upvotes: 0

Pekka
Pekka

Reputation: 449525

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?

Upvotes: 3

Related Questions