Reputation: 21
So I have this unordered list of items that is made from querying a mysql database
<ul>
<li>apple</li>
<li>orange</li>
<li>pear</li>
</ul>
I want there to be an onclick event that will pass 'apple' when I click apple and 'orange' when I click orange.
I also want to pass this information to another page through php. So this is my idea for the javascript function.
<script>
function passName(obj){
var pass = "<?php $x= " + obj.getName() + " ?>";
}
function getname(obj){
return 'string';
}
</script>
My Question: is there a method that exists within JavaScript that allows me to pull the raw string value of my unorderedlist without writing my own function? If I have to write my own JavaScript function, is there a way to set the 'name' strings automatically, while the list is populating?
Upvotes: 0
Views: 151
Reputation: 4547
/* Get value from clicked li */
$(function() {
let value = "";
$('ul li').on("click", function() {
value = $(this).text();
console.log(value);
});
/* AJAX for send value into result.php page */
$.post("result.php", {value: value}, function(res) {
console.log(res); // return from result.php page
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<ul>
<li>apple</li>
<li>orange</li>
<li>pear</li>
</ul>
result.php
if(isset($_POST['value']) && !empty($_POST['value'])) {
echo $_POST['value'];
}
Upvotes: 1
Reputation: 1360
This is how you can do it. On click you can change the page or do whatever you want. In the new url you can append the fruit value as a parameter to pass it to php
<ul>
<li onclick="fruitsClick('apple')">apple</li>
<li onclick="fruitsClick('orange')">orange</li>
<li onclick="fruitsClick('pear')">pear</li>
</ul>
<script>
function fruitsClick(fruit){
// do whatever you want
window.location.href = "[yourpageurl]?fruit=" + fruit
}
</script>
Upvotes: 1