Unable to get <li> value from php/ajax search results <ul> - php

I have a text field whereby a user can search for a last name. When they start typing then a search is performed on the database via php/ajax. This then displays names in an unordered list. At this point I am just trying to alert the id of that user if you click on the <li>.
PHP for the ajax call:
if ($_POST) {
$search = "{$_POST['last_name']}%";
$stmt = $link->prepare("SELECT `first_name`, `last_name`, `id` FROM `employees` WHERE `last_name` LIKE ? LIMIT 7");
$stmt->bind_param("s", $search);
$stmt->execute();
$result = $stmt->get_result();
$numRows = $result->num_rows;
if ($numRows > 0) {
echo "<ul id='myid'>";
while ($row = $result->fetch_assoc()) {
$first_name = sanitize($row['first_name']);
$last_name = sanitize($row['last_name']);
$id = sanitize($row['id']);
echo "<li data-id='$id'>" . $last_name . " , " . $first_name . "</li>";
}
echo "</ul>";
}
else {
echo "No results found";
}
$stmt->close();
}
jQuery
$(document).ready(function(){
$( "#last_name" ).focus();
$( "#last_name" ).keyup(function(){
$( "#loading" ).show();
var last_name = $( "#last_name" ).val();
if(last_name.length > 2) {
$.ajax({
type: 'POST',
url: 'functions/employee-search.php',
data: {last_name: last_name},
success: function(data) {
if(!data.error) {
$( "#result" ).html(data);
$( "#loading" ).hide();
}
}
});
}
if(last_name.length < 1) {
$( "#result" ).html("");
$( "#loading" ).hide();
}
});
$("#myid li").click(function() {
alert($(this).attr('id'));
});
});
HTML
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Employee</label>
<input type="text" class="form-control" name="last_name" placeholder="Search by surname" id="last_name" autocomplete="off">
<div style="display:none" id=loading><img src="../plugins/images/ajax-loader.gif" /></div>
<div id="result"></div>
</div>
</div>
</div>

If I understand the issue correctly you need to use data rather than attr.
If you use attr you are saying, get me the value of the id attribute but in your code the id value is actually stored in the data-id attribute.
Try changing this line:
alert($(this).attr('id'));
To this:
alert($(this).data('id'));
Or:
alert($(this).attr('data-id'));
You can read more about the data function here: https://api.jquery.com/data/
Also as you are adding elements to the DOM via AJAX the click event will work. You need to change this line:
$("#myid li").click(function() {
To this:
$("#result").on('click', '#myid li', function() {

jquery
$("#myid li").click(function() {
console.log($(this).attr('id'));
console.log($(this).data('id'))
});
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="myid">
<li id="one" data-id="1">one</li>
<li id="two" data-id="2">two</li>
<li id="three" data-id="3">three</li>
</ul>

Related

How to remove dynamically created div elements in JQuery after deleting a record from db?

I have created a dynamic Div(s) based on records from database and want to remove any of the specific div and its elements after removal a record from db. I have written deleteFile(id) function where ajax removes the div tag on getting response from php file.
But the specific div is not being removed from front end in my Code. How to properly access the closest div of element. Here is the code. Thank you
$sql2 = "SELECT * FROM table where
obj_id=".$idObjDetails;
$result2= mysqli_query($con,$sql2);
$count_file_rows = mysqli_num_rows($result2);
$index=1;
if($count_file_rows>0)
{
while ($row2 = mysqli_fetch_assoc($result2))
{?>
<div class="form-row">
<div class="form-group col-md-12 fileDiv">
<i class="fa fa-remove float-right" id="e_removeBtn" type="button" onclick=" deleteFile(<?php echo $row2['id'];?>)"></i>
<input type="text" name="e_fileGet" id="e_get_file_<?php echo $index ?>" class="form-control fileClass" readonly value="<?php echo $row2['file_name'];?>"/>
</div>
</div>
<?php
$index++;
}
}
?>
// DELETE Objection -
function deleteFile(id)
{
if(confirm("Are You Sure, You Want to Delete This Objection? "))
{
var del_file_id=id;
var element=this;
$.ajax({
url:"deleteFile.php",
type:"POST",
data: {'id':del_file_id},
success : function(data){
;
if(data==1)
{
//$("#e_get_file_1").remove();
$(element).closest(".fileDiv").remove();
//window.location.reload();
}
else
{
$("#error-message").html("cant del").slideDown();
$("#Success-message").slideUp();
}
}
});
}
//add alert - later
}
to remove the whole element
// DELETE Objection -
function deleteFile(id)
{
if(confirm("Are You Sure, You Want to Delete This Objection? "))
{
var del_file_id=id;
var element=this;
var selector = '#e_get_file_'+id;
$.ajax({
url:"deleteFile.php",
type:"POST",
data: {'id':del_file_id},
success : function(data){
;
if(data==1)
{
// parent().parent() to reach the .form-row div
$(selector).parent().parent().remove();
}
else
{
$("#error-message").html("cant del").slideDown();
$("#Success-message").slideUp();
}
}
});
}
//add alert - later
}

Add new data in Autocomplete

I am beginner in Jquery. I am using auto complete to suggest data to user in a form text box. Its working properly. But if a user entering a new entry or data in the text box.I need to add that data dynamically to the database by use of a pop up window. After that I need the id of the stored data, for storing the whole form data in other table.
Script:
<script type="text/javascript">
$(function() {
var availableTags = <?php include('vname.php'); ?>;
$("#vessel_name").autocomplete({
source: availableTags,
autoFocus:true,
minLength:2,
select: function(event, ui) {
$("#vessel_name").val(ui.item.value);
$("#vessel_id").val(ui.item.key);
}
});
});
</script>
php:
$connection = mysqli_connect("localhost","root","","db") or die("Error " . mysqli_error($connection));
//fetch vessel names from the vessel table
$sql = "select vessel_id,vessel_name from vessel";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
while($row = mysqli_fetch_array($result))
{
$vname = $row['vessel_name'];
$vid = $row['vessel_id'];
$vname_list[] =array("key"=>"$vid","value"=>"$vname");
}
echo json_encode($vname_list);
html:
<div class="form-group">
<label>Vessel Name</label>
<input type="text" id="vessel_name" placeholder="Vessel Name" class="form-control" name="nam">
</div>
<div class="form-group">
<label>Vessel Name</label>
<input type="text" id="vessel_id" placeholder="Vessel Name" class="form-control" name="nam">
</div>
Seems like you are doing it right.
Just grab the stored id from the form control.
$("#vessel_id").val();
you can as well keep it as an attribute:
<script type="text/javascript">
$(function() {
var availableTags = <?php include('vname.php'); ?>;
$("#vessel_name").autocomplete({
source: availableTags,
autoFocus:true,
minLength:2,
select: function(event, ui) {
$("#vessel_name").val(ui.item.value);
$("#vessel_id").val(ui.item.key).attr('data-id') = ui.item.key;
}
});
});
</script>
In while loop $vid and $vname this value not put in "". It will not enter into your database.
while($row = mysqli_fetch_array($result))
{
$vname = $row['vessel_name'];
$vid = $row['vessel_id'];
$vname_list[] =array("key"=>$vid,"value"=>$vname);
}

select ajax result and replace in input search PHP

I want select result Ajax request and Replace it on my input.
result display in result div,I want selected one of them and insert to mobile input and hidden results
<form method="post" action="#" class="form-horizontal" id="adduser">
<div class="form-group"><label class="col-sm-2 control-label">Mobile</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="mobile" id="mobile" autocomplete="off" />
<div id="result"></div></div>
</div>
<input type="submit" name="useradd" id="useradd" class="btn btn-block btn-w-m btn-success" value="add">
</form>
ajax jquery :
<script>
$(document).ready(function(){
var req = null;
$('#mobile').on('keyup', function(){
var mobile = $('#mobile').val();
if (mobile && mobile.length > 2)
{
$('#loading').css('display', 'block');
if (req)
req.abort();
req = $.ajax({
url : 'ajax.php',
type : 'POST',
cache : false,
data : {
mobile : mobile,
},
success : function(data)
{
console.log(data)
if (data)
{
$('#loading').css('display', 'none');
$("#result").html(data).show();
}
}
});
}
else
{
$('#loading').css('display', 'none');
$('#result').css('display', 'none');
}
});
});
</script>
fetch data and return in Ajax.php
if(isset($_POST['mobile'])) {
$user = new User();
$result = $user->Searchuser($_POST['mobile']);
$mobiles= array();
$names = array();
while ($info = $result->fetch(PDO::FETCH_ASSOC)) {
echo $info['firstname'].'-'.$info['mobile'].'<br/>';
}
}
Look this pic :
I want select Dany and insert that to mobile input

passing id name on click using ajax to php

i am using Ajax to make a filtered search system. I have three different tabs where users can search by names, by category and location.
I am able to seacrh when user enters name in the search box(tab-1).
In second tab, how can I use the same Ajax, so when user clicks a link, the id is passed in the ajax script to my php, and that id is passed as varibale in my mysql query.
First time with Ajax, any help would be highly appreciated.
AJAX script:
$(document).ready(function () {
$("#search_results").slideUp();
$("#button_find").click(function (event) {
event.preventDefault();
search_ajax_way();
});
$("#search_query").keyup(function (event) {
event.preventDefault();
search_ajax_way();
});
});
function search_ajax_way() {
$("#search_results").show();
var search_this = $("#search_query").val();
$.post("search.php", {
searchit: search_this
}, function (data) {
$("#display_results").html(data);
})
}
html:
<form id="searchform" method="post">
<input id="search_query" name="search_query" placeholder="What You Are Looking For?"
size="50" type="text" />
<input id="button_find" value="Search" type="submit" />
</form>
<div id="display_results">
</div>
<div class="tab">
<input id="tab-2" name="tab-group-1" type="radio" />
<label for="tab-2">Search by Category</label>
<div class="content">
<div id="searchbycategory">
<div id="nav_1_a">
<ul>
<li>All Categories</li>
<li>Category-1</li>
<li>Category-2</li>
<li>Category-3</li>
</ul>
<div id="display_results">
</div>
</div>
<!-- END nav_1_a -->
</div>
</div>
</div>
<div class="tab">
<input id="tab-3" name="tab-group-1" type="radio" />
<label for="tab-3">Search by location</label>
<div class="content">
<div id="searchbylocation">
<div id="nav_1_a">
<ul>
<li>All</li>
<li>Location-1</li>
<li>Location-2</li>
<li>Location-3</li>
<li>Location-4</li>
</ul>
</div>
search.php:
<?php
$connection = mysql_connect('localhost', 'user', 'pwd');
$db = mysql_select_db('db', $connection);
$term = strip_tags(substr($_POST['searchit'],0, 100));
$term = mysql_escape_string($term);
echo "Enter name to search";
else{
$sql = mysql_query("select col1,col2 from tab2 where tab2.somecolm like
'{$term}%'", $connection);
echo "<ul>";
if (mysql_num_rows($sql)){
while($info = mysql_fetch_array($sql, MYSQL_ASSOC ) ) {
echo "<li>";
echo "" . $info['col2'] . "";
echo "</li>";
}
}else{
echo "No matches found!";
}
echo "</ul>";
}
?>
Pass block id to search_ajax_way function:
$("#search_query").keyup(function(event){
event.preventDefault();
search_ajax_way(this.id);
});
Then pass block id in data param in ajax request:
function search_ajax_way(blockId){
$("#search_results").show();
var search_this=$("#search_query").val();
$.post("search.php", {searchit : search_this, 'blockId': blockId}, function(data){
$("#display_results").html(data);
})
}
Now blockId will be availible in your php script as $_POST['blockId'].
You say you want to pass the id when a link is clicked, but you don't have any code that handles link clicks. Add a click handler for links, and modify search_ajax_way() to accept an optional id for when links are clicked:
$("a").click(function (event) {
event.preventDefault();
search_ajax_way(this.id);
});
function search_ajax_way(clickedId) {
$("#search_results").show();
var postData = { searchit: $("#search_query").val() };
if (clickedId) {
postData.clickedId = clickedId;
}
$.post("search.php", postData, function (data) {
$("#display_results").html(data);
})
}
The id will be available in PHP as $_POST['clickedId']
Edit: Actually, I'd refactor to use search_ajax_way() as the event handler, rather than calling it from an anonymous event handler:
$("#button_find,a").click(search_ajax_way);
$("#search_query").keyup(search_ajax_way);
function search_ajax_way(event) {
event.preventDefault();
$("#search_results").show();
var postData = {
searchit: $("#search_query").val(),
clickedId: this.id
};
$.post("search.php", postData, function (data) {
$("#display_results").html(data);
})
}

Submit input field value with button click

I am working with an ajax form that it is suppose to submit with a button click. I have seen similar projects but I am running into dead ends. The problem i am having is that the input field values are not getting echo in tab 2. I set a parameter var currentTab to indicate and compare when a click has been made to the next tab.
How can I display the value of the input fields after a click has been made?
(Additional) Also how can adapt the code if in the future I have multiple tabs with input fields and the last tab will be where the values get php echo out?
Thank you
AJAX/JS Function
<script>
var currentTab = 0;
$(function() {
var $tabs = $('#tabs').tabs({
disabled: [0, 1]
, select: function() {
if (currentTab == 0) {
$.ajax({
type: "POST",
url: "tabs.php",
data: { "textarea": $("#textarea_input").html(),
"title": $("#title_input").html()
},
success: function(result) {
$("#tab-2").html(result);
}
});
}
}
, show: function(event, ui) {
currentTab = ui.index;
}
});
$(".ui-tabs-panel").each(function(i) {
var totalSize = $(".ui-tabs-panel").size() - 1;
if (i != totalSize) {
next = i + 2;
$(this).append("<a href='#' class='next-tab mover' rel='" + next + "'>Next Page »</a>");
}
if (i != 0) {
prev = i;
$(this).append("<a href='#' class='prev-tab mover' rel='" + prev + "'>« Prev Page</a>");
}
});
$('.next-tab, .prev-tab').click(function() {
var tabIndex = $(this).attr("rel");
$tabs.tabs('enable', tabIndex)
.tabs('select', tabIndex)
.tabs("option","disabled", [0, 1]);
return false;
});
});
</script>
PHP
<?
if (isset($_POST['title'])){
$title = $_POST['title'];
echo ('<div id="title_result"><span class="resultval"><h2>Title Echo result:</h2>'.$title.'</span></div>');
}
if (isset($_POST['textarea'])){
$textarea = $_POST['textarea'];
echo ('<div id="textarea_result"><span class="resultval"><h2>Textarea Echo result:</h2>'.$textarea.'</span></div>');
}
?>
HTML Tab2 is where the results should be php echo out
<div id="tab-1" class="ui-tabs-panel ui-tabs-hide">
<label for="title">Title</label>
<input type="text" id="title_input" name="title_input" size="60" autocomplete="off" value="<?=$title?>"/><br>
<label for="textarea_input">Textarea</label>
<textarea id="textarea_input" name="textarea_input"><?=$textarea?></textarea>
</div>
<div id="tab-2" class="ui-tabs-panel ui-tabs-hide">
<div id="title_result" style="padding:20px;"></div>
<div id="textarea_result" style="padding:20px;"></div>
</div>
A few comments :
You should first add the echoed html from PHP, only then can you access it from jquery with $("#resultval")
I will explain - look at your "success" handler
success: function(result) {
$('#textarea_result').html( $('#resultval', result).html());
$('#title_result').html( $('#resultval', result).html());
}
The code should be
success: function(result) {
$('#textarea_result').html( result);
$('#title_result').html( result);
}
If at all.. but I don't think that it what you meant.
If you want to ask me - render the entire next tab in PHP and do something like $("#tab2").html(result);
Comment #2
You have 2 identical IDs - resultval..
Comment #3 -
You are sending "textarea" and "title" in Ajax, but referring to $_POST["textarea_input"] and $_POST["title-input"]
Comment #4 -
You are using $("#textarea-input").html() to get the value instead of $("#textarea-input").val(). same for "title_input"
Here is my working version ( just remove the "head" stuff ).
This is my main.php -
<html>
<head>
<link rel="stylesheet" type="text/css" href="/stackoverflow/public/jquery-ui-1.8.22.custom.css" media="screen" />
<script src="/stackoverflow/public/jquery-1.7.2.min.js"></script>
<script src="/stackoverflow/public/jquery-ui-1.8.22.custom.min.js"></script>
</head>
<body>
<div id="page-wrap">
<div id="tabs">
<ul>
<li> TAB1</li>
<li> TAB2</li>
</ul>
<div id="tab-1" class="ui-tabs-panel ui-tabs-hide">
<label for="title_input">Title</label>
<input type="text" id="title_input" name="title_input" size="60" autocomplete="off" value="my title"/><br>
<label for="textarea-input">Textarea</label>
<textarea id="textarea-input" name="textarea-input"></textarea>
</div>
<div id="tab-2" class="ui-tabs-panel ui-tabs-hide">
</div>
</div>
</div>
<script>
var currentTab = 0;
$(function() {
var $tabs = $('#tabs').tabs({
disabled: [0, 1]
, select: function() {
console.log("selecting a new tab " + currentTab);
if (currentTab == 0) {
$.ajax({
type: "POST",
url: "tabs.php",
data: { "textarea": $("#textarea-input").val(),
"title": $("#title_input").val()
},
success: function(result) {
$("#tab-2").html(result);
}
});
}
}
, show: function(event, ui) {
currentTab = ui.index;
}
});
$(".ui-tabs-panel").each(function(i) {
var totalSize = $(".ui-tabs-panel").size() - 1;
if (i != totalSize) {
next = i + 2;
$(this).append("<a href='#' class='next-tab mover' rel='" + next + "'>Next Page »</a>");
}
if (i != 0) {
prev = i;
$(this).append("<a href='#' class='prev-tab mover' rel='" + prev + "'>« Prev Page</a>");
}
});
$('.next-tab, .prev-tab').click(function() {
var tabIndex = $(this).attr("rel");
$tabs.tabs('enable', tabIndex)
.tabs('select', tabIndex)
.tabs("option","disabled", [0, 1]);
return false;
});
});
</script>
</body>
</html>
And this is my "tabs.php"
My working example can be found at my site
<?php
echo "This is the result are you ready?";
if (isset($_POST['title'])){
$title = $_POST['title'];
echo ('<div id="title_result"><span id="resultval"><h2>Title Echo result:</h2>'.$title.'</span></div>');
}
else{
echo "title_input is not defined!";
}
if (isset($_POST['textarea'])){
$textarea = $_POST['textarea'];
echo ('<div id="textarea_result"><span id="resultval"><h2>Textarea Echo result:</h2>'.$textarea.'</span></div>');
}
?>
Let me know if there's anything else.
You may want to look into cleaning up your HTML first and utilizing PHP correctly... your HTML tab 2 should be:
<div id="tab-1" class="ui-tabs-panel ui-tabs-hide">
<label for="title">Title</label>
<input type="text" id="title_input" name="title_input" size="60" autocomplete="off" value="<?=$title?>"/><br>
<label for="textarea-input">Textarea</label>
<textarea id="textarea-input" name="textarea-input"><?=$textarea?></textarea>
</div>
<div id="tab-2" class="ui-tabs-panel ui-tabs-hide">
<div id="title_result" style="padding:20px;"></div>
<div id="textarea_result" style="padding:20px;"></div>
</div>
You had an extra quote after title_input name and also when you want to spit out PHP code without an echo, use it like this:
<?=$title?>
also by the way, you have additional dirty code in your php... this:
if (isset($_POST['title_input"'])){
$title = $_POST['title_input"'];
echo ('<div id="title_result"><span id="resultval"><h2>Title Echo result:</h2>'.$title.'</span></div>');
}
should be:
if (isset($_POST['title_input'])){
$title = $_POST['title_input"'];
echo ('<div id="title_result"><span id="resultval"><h2>Title Echo result:</h2>'.$title.'</span></div>');
}
you had an additional quote in the php here:
$_POST['title_input"']
go through and clean up your code

Categories