I have the following jquery script
$("li").click(function(){
var id = $(this).attr("id");
$.get("getData.php", {id: id}, function(data){
$("ul").after(data);
});
$(this).css("color","red");
});
and the getData.php file
<?php
include("db_config.php");
$ctgID = $_GET["id"];
if(isset($ctgID))
{
getData($dbh, $ctgID);
}
function getData($dbh, $ctgID)
{
try{
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $dbh->prepare("select ctgid, ctgdescription from categories where ctgparentid = $ctgID");
$sql->execute();
$result = $sql->rowCount();
if($result >0)
{
echo "<ul>";
while($row = $sql->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
{
echo "<li class=\"subCtg\" id=\"". $row[0] . "\">" . $row[1] . "</li>";
}
echo "</ul>";
}
else
{
echo "1";
}
}
catch(PDOException $e){
die($e);
}
}
?>
Even if the above is working perfectly for the top level categories its not working when i am clicking on the subCtg class that is created. Can you help me please?
Use click event like this, that trigger on your existing and dynamic lists as well:
$('ul').on('click', 'ul li', function(){
.....
});
Take a look on this example
HTML:
<ul>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
JS:
$(document).on('click', 'li', function(e){
e.preventDefault();
e.stopPropagation();
$(this).parent('ul').after('<ul><li>new item click here </li></ul>');
});
Live demo: http://jsfiddle.net/jogesh_pi/YdByT/
Use Jquery Bind instead of click event ..
$( ".subCtg" ).bind( "click", function() {
alert( "User clicked " );
});
Jquery Bind
As you load new ul/li elements, you have to bind the "click"
event on them.
Try this:
PHP
...
while($row = $sql->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
{
echo "<li class=\"subCtg\" onclick=\"myFunc(".$row[0].");\" id=\"". $row[0] . "\">" . $row[1] . "</li>";
}
...
Javascript
$("li").click(function(){
var id = $(this).attr("id");
myfunc(id);
});
function myFunc(id){
$.get("getData.php", {id: id}, function(data){
$("#"+id).parent(ul).after(data);
});
$("#"+id).css("color","red");
}
An only-javascript approach could be:
function myFunc(id){
$.get("getData.php", {id: id}, function(data){
$("#"+id).parent(ul).after(data);
});
$("#"+id).css("color","red");
//create onclick event on new elements
$("li").each(function(){
$(this).click(myFunc($(this).attr("id")));
});
}
Related
this code displays the name as i type, as i type it gives suggestion of names and when clicked on it it displays the result in the textbox.but i want to display the id related to that name from database when i clicked on that name from the dropdown option. please help
<input type="text" name="st_id" id="st_id" ><div id="txtHint" style="position: absolute; width:390px ;"></div>
ajax code:
$(document).ready(function () {
$("#st_id").keyup(function () {
var search = $(this).val();
if (search != '') {
$.ajax({
type: "POST",
url: "ajaxcode.php",
data: {search: search},
success: function (data) {
$("#txtHint").fadeIn();
$("#txtHint").html(data);
}
});
}
});
});
php code
<?php
if (isset($_POST["search"])) {
$display = '';
$q = $_POST["search"];
$stmt = $DBconnect->prepare("SELECT * FROM table1 WHERE First_name LIKE :sh ");
$stmt->bindValue(':sh', '' . $q . '%', PDO::PARAM_STR);
$stmt->execute();
$display = '<ul class="list-unstyled">';
foreach ($stmt as $row) {
if ($row) {
$display .= '<li>' . $row["First_name"] . ' ' . $row["Middle_name"] . ' ' . $row["Last_name"] . '</li>';
} else {
$display .= '<li>name not found</li>';
}
}
$display .= '</ul>';
echo $display;
}
?>
Most naive way I can come up with is adding an id to the top ul
<ul id="name_suggestion" class="list-unstyled">
and the id to the <li> tag with a data- attr
$display .= '<li data-user-id = '. $row["id"] . '>'.$row["First_name"].' '.$row["Middle_name"].' '.$row["Last_name"].'</li>';
Then add an a click listener to the li:
$('#name_suggestion li').on('click', function(e){
let val = $(this).attr('data-user-id');
$('#st_id').val(val);
});
So I've got 2 boxes. On the left I have a list of items pulling from the database which I can drag and drop to the right. This works great. I can't for the life of me work out how to get it to post the data for the list on the right and I think I've tried every example Google has to offer this week.
When I do a print_r($_POST); on the page this submits to, I get Array ( ) with nothing in it. It doesn't seem to be grabbing the ID's and serializing them.
Does anyone have experience with this see anything I'm missing?
<script>
$(function() {
$( "ul.droptrue" ).sortable({
connectWith: "ul"
});
$( "ul.dropfalse" ).sortable({
connectWith: "ul",
dropOnEmpty: true
});
$( "#sortable1, #sortable2" ).disableSelection();
});
$( "#sortable2" ).sortable({
axis: 'y',
handle : '.handle',
update: function (event, ui) {
var data = $(this).sortable('serialize');
console.log(data);
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: 'setlists-edit-process.php'
});
}
});
</script>
<ul id="sortable1" class="droptrue">
<?php
$_GET['setlist_id'];
$sql = "SELECT material_id, material_name FROM material WHERE user_id=$session_id";
$result = mysqli_query($conn, $sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($conn));
exit();
}
while($row = mysqli_fetch_array($result))
{
echo "<li id=" . $row['material_id'] . ">" . $row['material_id'] . " | " . $row['material_name'] . "</li>";
}
?>
</ul>
<ul id="sortable2" class="dropfalse">
</ul>
Replace this:
while($row = mysqli_fetch_array($result))
{
echo "<li id=" . $row['material_id'] . ">" . $row['material_id'] . " | " . $row['material_name'] . "</li>";
}
with:
while($row = mysqli_fetch_array($result))
{
echo '<li id="material_' . $row['material_id'] . '">' . $row['material_id'] . " | " . $row['material_name'] . "</li>";
}
Sortable expects the ID to be in the format setname_number.
Moreover, your code outputs in the format id=abc (no quotations), and rather it should be id="abc" with surrounding quotes.
I'm using jQuery autocomplete and trying to get it to go directly to the link when I click on suggestion or press enter. Here's the code I used:
<script>
$(function() {
$( "#search" ).autocomplete({
source: 'search.php',
select: function(event, ui) {
$(this).val(ui.item.value);
$(this).parents("form").submit(); // this will submit the form.
}
});
});
</script>
Then I have my php code for search: '
if ($_POST['search'] != null) {
//die("asdf: " . $_POST['search']);
$search = $_POST['search'];
$result = mysqli_query($con,"SELECT * FROM question WHERE text LIKE '%$search%'");
while($row = mysqli_fetch_array($result)) {
$text = $row['text'];
$question_id = $row['question_id'];
//die($search . " " . $text);
if ($search == $text){
header("Location: http://localhost/showstats.php?question_id=$question_id");
die();
}
echo "<br>";
echo " <a href=\"showstats.php?question_id=" . $question_id;
echo "\">$text</a> ";
//echo "<br>";
}}
The problem is when I click on suggestion it doesn't redirect to "showstats.php?question_id=$question_id", insted give me a blank result page.
And when I insert die($search . " " . $text); inside if statement it's showing me text 2 times, so I know it enters the body of it statement.
also worth escaping your sql...
$search = $_POST['search'];
$search = mysqli_real_escape_string($search);
$result = mysqli_query($con, "SELECT * FROM question WHERE text LIKE '%$search%'") or die(mysqli_error($con));
When you select a suggestion, the event occurs in the client so this code in your PHP is not really necessary:
if ($search == $text) {
header("Location: http://localhost/showstats.php?question_id=$question_id");
die();
}
Instead, when you select a suggestion, try triggering the redirection from jQuery:
<script>
$(function() {
$( "#search" ).autocomplete({
source: 'search.php',
select: function(event, ui) {
// This will redirect you to whatever URL is in ui.item.value:
window.location = ui.item.value;
}
});
});
</script>
It is because your headers are already sent, you have started your output, hence the redirect will not work.
Try buffering your output.
Can anyone help me fixing my issue?
How can I make my links work, which come by ajax?
I tried to write some links directly into the document and they worked pretty well, but the "imported" ones don't.
JSFiddle
-> res/ajax/search.php
<?php
$search = $_POST['search'];
if( $search != "" ) {
$db = mysql_connect('localhost', 'root', '');
mysql_select_db('invoice');
$query = "SELECT * FROM profile";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
for( $a=1; $a <= $rows; $a++ ) {
$query = "SELECT * FROM profile WHERE full_name LIKE '%$search%' AND id='$a'";
$result = mysql_query($query);
$array = mysql_fetch_array($result);
if($array != "") {
echo "<a href='#' class='address'>" . $array['full_name'] . "</a><br />";
}
}
}
echo "<a href='#' class='address'>currywurst</a><br />";
echo "<a href='#' class='address'>bratwurst</a><br />";
?>
Use:
$(document).on('click', '.address', function(){
alert('something');
});
Instead of:
$('.address').click(function(){
alert('something');
});
You should try binding handlers to ajax loaded content in your ajax callback. Try this:
$(document).ready(function(){
$('input[name="search"]').keyup(function(){
$.post('res/ajax/search.php',
{
search: $('input[name="search"]').val()
},
function(data) {
$('#search-preview').html(data);
// onclick moved to ajax callback function
$('.address').click(function(){
alert('something');
});
});
});
});
The weirdest thing. If I upload my files and start clicking on the link it works just fine. However if I go surf on another tab and then come back to it and click the link the .post or .click jquery doesn't seem to work. I only included excerpts of the code. Let me know if you need to see more code. Thanks!!
likeOnClick.php file
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="includes/js/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".like").click(function() {
var data = $(this).attr('data-id');
$.post("updateLikes.php", {'id': data});
});
return false;
});
</script>
...
displayDBUsers.php
while($row = mysql_fetch_array($result))
{
?>
<?php $id = $row['uniqueid'];?>
<?php $finalID = "showdata" . $id ;?>
<?php echo "<br>FinalID: " . $finalID;?>
<?php echo "<br>ID: " . $row['uniqueid'];?>
<?php echo "<br>Name: " . $row['surname']; ?>
<?php echo "<br><a href class=like data-id=" . $id . ">Like (" . $row['likes'] . ")</a>"; ?>
<?php echo "<br><br>"; ?>
<?php
}
...
updateLike.php
if( $_POST['id'])
{
$unique_id = mysql_real_escape_string($_POST['id']);
$sql = "
UPDATE atable
SET likes=likes + 1
WHERE uniqueid=$unique_id;";
$result = mysql_query($sql);
if(!$result)
{
echo "Failed to retrieve record";
}
Please pay attention. return false; placed in different position:
<script type="text/javascript">
$(document).ready(function() {
$(".like").click(function() {
var data = $(this).attr('data-id');
$.post("updateLikes.php", {'id': data});
return false;
});
});
</script>
Put quotes around your attribute values:
echo "<br>Like";