Uncaught Reference Error and JS functionality - javascript

I've been looking at this for a while and I can't seem to find a proper solution for it.
Here is part of my code:
<li style="float: right;">Themes
<ul>
<?php
$db=mysql_connect('localhost','root','');
if(!$db) {
die('Could not connect: '.mysql_error());
}
$connection_string=mysql_select_db('somedb',$db);
$selectSQL='SELECT * FROM color_patterns';
$queryset=mysql_query($selectSQL);
$num=mysql_num_rows($queryset);
if(0==$num) {
echo "No record";
exit;
} else {
while($row=mysql_fetch_assoc($queryset)) {?>
<li onclick="liPosition()">
<?php echo($row['name']);?></li><?php
}
}
?>
</ul>
</li>
this is a list item that contains a drop down list. To populate the dropdown list I make a call to my database and for each row in the table I add an li element to the dropdown. I want to retrieve more information from the db based on which li the user clicks so I made a JS function that should get me the index of the li that's clicked on, (The li index corresponds to the id of another table I want to retrieve information from):
<script>
function liPosition() {
var index = $(this).parent().children().index(this);
alert("You clicked item " + index);
});
</script>
When I click on the li I get an error:
Uncaught ReferenceError: liPosition is not defined after some research I found that I can't pass onclick listeners here but I don't know how to find the index of the li in the while loop otherwise. Is there a way to find the index of an li element in a list that's been generated with a while loop? Any help would be greatly appreciated, Thank you.

Why not remove the inline JavaScript and go full jQuery?
PHP - use a class to identify the clicked item;
while($row=mysql_fetch_assoc($queryset)) {?>
<li class="list_item">
<?php echo($row['name']);?></li><?php
}
jQuery - The selector is the list item's class;
<script>
$(document).on('click', '.list_item', function() {
var index = $(this).id;
alert("You clicked item " + index);
});
</script>
In addition: please stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really pretty easy.

you can send the this reference as a parameter to the function.
<li onclick="liPosition(this)">
and then add the parameter to your function.
<script>
function liPosition(listitem) {
var index = $(listitem).parent().children().index(listitem);
alert("You clicked item " + index);
};
</script>
FYI, you also have a small typo with an extra ) at the end of your function definition });
<script src="http://code.jquery.com/jquery-3.0.0.min.js" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=" crossorigin="anonymous"></script>
<li onclick="liPosition(this)">item 1</li>
<li onclick="liPosition(this)">item 2</li>
<script>
function liPosition(listitem) {
var index = $(listitem).parent().children().index(listitem);
alert("You clicked item " + index);
};
</script>

Related

Sort list items loaded after ajax call using jquery

Consider 2 files:
File 1 - list.html
<ul>
<li>Dog</li>
<li>Ant</li>
<li>Cat</li>
</ul>
File 2 - ajax.html
<html>
<body>
<button type="button">Click</button>
<ul id="list">
</ul>
<script type="text/javascript">
$("button").click(function() {
$("#list").load("list.html ul > li");
});
</script>
</body>
</html>
Here file 1 contain list of items and file 2 load file 1's li tag list items to file 2's ul tag. After ajax call, how can we sort the loaded list alphabetically before it is displayed on the screen. I wanted to sort only after ajax call. Please help me.
To do this you can provide a function to the callback argument of load() which is executed after the AJAX request completes and the new content has been added to the DOM. Try this:
$("button").click(function() {
let $list = $("#list").load("list.html ul > li", function() {
$list.find('li').sort((a, b) => a.innerText < b.innerText ? -1 : 1).appendTo($list);
});
});
You can do this inside the ajax success callback function. Also, you can user JS .sort() for sorting the names. This is a simple ajax call. You can add more properties based on your need. let's assume the result variable contains the names which you want to add:
$('#myButton').click(function(){
$.ajax({
url : 'Your_server_url',
success: function(result){
result.sort()
for (i = 0; i < result.length; i++) {
$('#list').append("<li>" + result[i] + "</li>")
}
},
error: function (xhr, status) {
console.info("cannot update list!");
}
});
});
<html>
<body>
<button type="button" id="myButton">Click</button>
<ul id="list">
</ul>
</body>
</html>

Create a clickable list in HTML using JSON data with Javascript

I'm using Jquery mobile, and I want to create a clickable view list in my panel. to look something like this...
<li><a href='#' onclick='getmoviepic_mobile(this) ;' > MovieTitle"</a>
</li>
MovieTitle is obtained from my MYSQL database array using json_encode($x) so when the user clicks on the title the function getmoviepic_mobile(this) is triggered.
My question is how to set up my javascript with json data to populate my html
page.
My HTML
<div data-role="panel" id="Panelcategory" >
<ul data-role="listview" data-inset="true" id="MovieTitle">
<li></li>
</ul>
</div >
PHP getcatagories2_mobile.php
<?php
include("includes/connection.php");
$q=$_POST['input'];
$resultActor = mysqli_query($con,"SELECT id,title,
plot,catagory,release_date,rated FROM ".TBL_DATA." WHERE catagory LIKE
'%".$q."%' ORDER BY title ");
while($rowMovie = mysqli_fetch_array($resultActor)) {
$x[]=$rowMovie['title'];
}
$jsonarray=json_encode($x);
echo $jsonarray;
?>
Javascript
function getcatagories(catagory){
var catagoryValue = $(catagory).text();
$.getJSON( "getcatagories2_mobile.php", {input:catagoryValue},
function(json) { this is the part I am stuck on
}
not sure even if my HTML is set up correctly maybe don't need the "li".
thanks guys
I would iterate through the JSON and add attributes by key. For example, you could query the list and add each value.
$("#MovieTitle").append("<li>" + json["category"] + "</li>")
And do so for each key-value pair you want to include.

How can I get ID from "ul" dynamic tag

I have the next situation.
I have a button in HTML code. When I press one of the options from the button I call a function that constructs the content from other button.
I have a ul tag in HTML code with a list of li tags inside. The value of this li tags are generated dynamically with a query database.
When I generate the options from li tags I assign a different ID to each other.
Here you can see the code that I have for the second button:
<div class="dropdown" class="btn-group-lg" id="test">
<button name="selSensor" id="seltipoSensor" class="btn btn-primary dropdown-
toggle" type="submit" data-toggle="dropdown">
<span>Select one option</span>
</button>
<ul class="dropdown-menu" id="test2">
</ul>
</div>
Here you can see the code that I have to generate the li tags inside the button.
<script type="text/javascript">
function selectedUbi(ubicacion){
var datos = {
"arg" : ubicacion
};
$.ajax({
data: datos,
url: 'condatabase/calculos_bdd2.php',
type: 'post',
success: function (response) {
if(response){
document.getElementById("test2").innerHTML = "";
var ul = document.getElementById("test2");
for (i=0;i<response.length;i++){
var li = document.createElement("li");
li.appendChild(document.createTextNode(response[i][i+1]));
li.setAttribute("id", "element"+i);
li.setAttribute("onclick",myFunction);
ul.appendChild(li);
}
}
},
dataType:"json"
});
}
</script>
The question that I have is...
how can I get the ID from the li tag that I generate dynamically?
I tried to use "getElementByID" and "getElementByTagName" but as the ID is dynamic I have no idea to caught the value.
For example the button have the next options to select:
- apple (ID= element0)
- bannana (ID= element1)
- carrot (ID= element2)
When I select the option "bannana" I need to get the ID "element1".
You can use querySelectorAll on your container to get a list of elements and then read their attribute id.
function getIds(container){
return [...container.querySelectorAll('li[id]')].map(li => li.getAttribute('id'));
}
However, I would rather recommend to create a data layer abstraction to handle operations related to data fetching, etc... in order to avoid a strong coupling on your html structure and your "logic" code.
function createStore(){
return {
async fetch(arg){ /*... return your data (and cache it etc */ }
};
}
so your button handlers can share that "store"
const store = createStore();
document.getElementBy('button1').addEventListener('click', () => {
store.fetch().then(data => { /* do something with your data like updating html ... */})
});
document.getElementBy('button2').addEventListener('click', () => {
store.fetch().then(data => { /* do something with your data like updating html ... */})
});
//etc

Get value of li clicked as a link

I got couple of li elements and using them as a links to welcome.php. In welcome.php I need to know which one was clicked.
<ul>
<li><a href='welcome.php'>sport</a></li>
<li><a href='welcome.php'>relax</a></li>
<li><a href='welcome.php'>gym</a></li>
</ul>
I can't use jquery. Is there any other way to do this?
The simplest way to do this might be to append a query parameter to your links:
<ul>
<li>sport</li>
<li>relax</li>
<li>gym</li>
</ul>
you can incorporate the value in the links and get them with PHP like this
<a href="welcome.php?x=sport">
Where x is the variable you're going to get by using this in your php:
$x = $_GET["x"];
You'd need to do the same with all other links. but you only need to get the value once ofcourse
I was a little bit too late with posting this, but I think mine might have a better explaination so I'm keeping it
You can use $_GET for post value of li
I prepare an example for you
index.php
<form action="welcome.php" method="post">
<ul>
<li>sport</li>
<li>relax</li>
<li>gym</li>
</ul>
</form>
welcome.php
$var = $_GET["var"];
echo $var;
I have prepare one solution for you using simple html and Javascript :
<html>
<body>
<ul>
<li>sport</li>
<li>relax</li>
<li>gym</li>
</ul>
</body>
<script>
var el = document.getElementById('sport');
el.onclick = showMsg1;
var el = document.getElementById('relax');
el.onclick = showMsg2;
var el = document.getElementById('gym');
el.onclick = showMsg3;
function showMsg1() {
//alert('Sport Clicked!');
//Do what ever you want after click of "sport"
window.location = "welcome.php?type=sport";
return false;
}
function showMsg2() {
//alert('relax Clicked!');
//Do what ever you want after click of "relax"
window.location = "welcome.php?type=relax";
return false;
}
function showMsg3() {
//alert('Gym Clicked!');
//Do what ever you want after click of "Gym"
window.location = "welcome.php?type=gym";
return false;
}
</script>
I am sure this will helpful to you. Thank you :)

How To Fade Out Function With No Unique ID/Class

I don't normally post my server side code but I guess I can post abit to solve this issue,I have a staff page that loops through in a database as I am going to use the database to do other things like deleting/demoting the staff if they did anything wrong and to make the site neater. (don't like demoting staff but in a case I need to)
Anyway I am looping it through with a box what I want now is when one of the boxes are clicked I want it to go to a php page (via a ajax request to delete the user from the database) then hide or fade way by using the hide or fade function.
But the only issue is how can I do this when it's looping through? because the div does not have it's own class or id and I don't think jquery can connect to a database to get a unique id (since it's client side)
Here's some of my code to help
while($staff_info = mysqli_fetch_array($select_staff)) {
$account_name = $staff_info['account_name'];
$position = $staff_info['position'];
$description = $staff_info['description'];
echo "
<div id='staff_boxes'> <text style='float:right;'> <a href='#' class='delete_button'> X </a> </text>";
echo"
<h2>$account_name</h2>
$position
<p>$description</p>
</div> ";
}
Hoping to get some help and this I search Google but can't find nothing I might be doing it wrong for this type of system
Thanks!
You can give each box a unique id like this with your code:
while($staff_info = mysqli_fetch_array($select_staff)) {
$id = $staff_info['id']; // assuming you have an id field in your DB
$account_name = $staff_info['account_name'];
$position = $staff_info['position'];
$description = $staff_info['description'];
echo "
<div id='staff_boxes_$id'> <text style='float:right;'> <a href='#' class='delete_button'> X </a> </text>";
echo"
<h2>$account_name</h2>
$position
<p>$description</p>
</div> ";
}
Alternatively, you can give all the divs the same class (e.g. <div class="staff_box"> ... </div> then use jQuery like this:
$('.staff_box').each(function(index) {
var box = $(this);
box.children('.delete_button').click(function(event) {
event.stopPropagation();
box.hide();
})
});

Categories