Hopefully you can help on this javascript puzzle in my code. I m still learning javascript and jquery. I admit I am a bit rusty and trying to get back into coding again. I have created a searchbox autocomplete. I have created the javascript in my main html, and created an additional php page called autocomplete.php. My auto complete is working but now I want to have is... When a user click on one of the autocomplete choices below it will pop up the value which will then put an id in the search box for our system to search easier, but I also want to add a permanent place holder or text describing what they click on along with the id, but the text cannot be read by the search. I just want to read the id. In case, that is why I thought of a permanent placeholder.
On the PHP page I have created the onclick portion of the code:
<ul id="country-list" >
<?php
while($row=pg_fetch_assoc($result)){
?> <li onClick="selectCountry('<?php echo $row["id"]; ?>'); selectPlaceholder('<?php echo $row["country"].", ".$row["state"]; ?>');"> <?php echo "<strong>(".$row["id"].")</strong> ".$row["country"].", ".$row["state"]; ?> </li>
<?php } ?>
</ul>
So I have created two type of onClicks which are selectCountry() and selectPlaceholder().
Here is my javascript code on the index page:
$(document).ready(function(){
$("#search-box").keyup(function(){
$.ajax({
type: "POST",
url: "/VCSWeb/wp-content/themes/i-excel-child/autocomplete.php",
data:'keyword='+$(this).val(),
beforeSend: function(){
$("#search-box").css("background","#FFF url(LoaderIcon.gif) no-repeat 165px");
},
success: function(data){
$("#suggesstion-box ").show();
$("#suggesstion-box").html(data);
$("#search-box").css("background","#FFF");
}
});
});
});
function selectCountry(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
function selectPlaceholder(val) {
$("placeholder").val("data-placeholder='"+val+"' ");
}
As you can see at the bottom I am trying to turn the selectPlaceholder() into a variable and then pop it into my tag to create something like data-placeholder='selectPlacehoder(value)'.
Here is my HTML
<div class="frmSearch placeholder" style="width:90%; float:left;" ---> data-placeholder='text' <---(place javascript variable here) >
<label>
<input size="59" maxlength="75" type="search" name="search" class="search_keyword" id="search-box" placeholder="Enter Jurisdiction, County, City, or Client Name" />
<div class="box" id="suggesstion-box"></div>
</label>
</div>
Here is my CSS to make the placeholder permanent in the location
.placeholder
{
position: relative;
}
.placeholder::after
{
position: absolute;
left:150px;
top: 10px;
font-size:18px;
content: attr(data-placeholder);
pointer-events: none;
opacity: 0.6;
}
Overall, need help with the javascripting turing the attribute into a variable, then taking the variable and poping it within a html div type tag.
function selectPlaceholder(val) {
$("placeholder").val("data-placeholder='"+val+"' ");
}
So is this possible? How can we do this? Do I need to create an id and then place it? Would I need to put this in a .prop? Is there a better way?
If I understand your problem, you want the user to see the text of the autocomplete option they selected, but you only want to send the row ID to the server. I would consider not making the auto-complete search box the input that gets sent to the server. Instead, I would create a hidden input with name=[search] and update that with the row ID to be sent to your server, then let the autocomplete input show the full description to the user. This is more conventional, in my opinion.
So in the PHP auto complete rows:
<ul id="country-list" >
<?php
while($row=pg_fetch_assoc($result)){
?> <li onClick="selectCountry('<?php echo $row["id"]; ?>'); updateSearchBox(this);"> <?php echo "<strong>(".$row["id"].")</strong> ".$row["country"].", ".$row["state"]; ?> </li>
<?php } ?>
</ul>
Javascript:
function selectCountry(val) {
$("#search-id").val(val);
$("#suggesstion-box").hide();
}
function updateSearchBox(el) {
$("#search-box").val($(el).html());
}
Main HTML:
<div class="frmSearch" style="width:90%; float:left;">
<label>
<input size="59" maxlength="75" type="search" class="search_keyword" id="search-box" placeholder="Enter Jurisdiction, County, City, or Client Name" />
<input type="hidden" name="search" id="search-id"/>
<div class="box" id="suggesstion-box"></div>
</label>
</div>
Related
I have a insert query through ajax. It is working correctly. But when I reload browser then result disappears from div section and if I insert form through ajax again then result is showing.
I have a file first.php (in which, form is present), a AJAX code and a firstcall.php where query will be execute.
My first.php (html form) is:
<form class="reservation-form mb-0" action="" method="post" autocomplete="off">
<input name="name1" id="name1" class="form-control" type="text" placeholder="Enter Name" required aria-required="true">
<input name="age" id="age" class="form-control" required type="number" placeholder="Enter Age" aria-required="true">
<input type="checkbox" id="checkbox" class="checkbox1" name="namec[]" value="<?php echo $value['id']; ?>" >
<input type="button" class="pull-right btn btn-warning" value="Submit" id="submit">
</form>
Here data should be display:
<div class="col-md-5">
<div class="panel panel-primary" id="showdata">
<!-- Here is the results, but when reload browser then result disapper-->
</div>
</div>
AJAX is:
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var name1 = $("#name1").val();
var age = $("#age").val();
var chkArray=[];
$('.checkbox1:checked').each( function() {
chkArray.push($(this).val());
} );
var selected;
selected = chkArray.join(',') ;
if(selected.length > 1){
$.ajax( {
url:'firstcall.php',
type:'POST',
data:{name1: name1,age: age,namec: chkArray},
}).done(function(data){
$("#showdata").html(data);
});
}
else{
alert("Please at least one of the checkbox");
}
});
});
</script>
firstcall.php is:
<div class="panel panel-primary" id="showdata">
<?php
foreach($_POST['namec'] as $selected){
echo $selected;
$_SESSION['name1']=$_POST["name1"];
$_SESSION['age']=$_POST["age"];
echo $name1=$_SESSION['name1'];
echo $age=$_SESSION['age'];
$query=mysql_query("insert into patient_details (p_name,p_age,g_number) values ('$name1','$age','$selected')") or die(mysql_error());
}
?>
First of all fix your query to use MySQLi, instead of MySQL, check this or the PHP manual
Also don't ever add direct $_POST or $_GET variables into your mysql query, filter them first using mysqli_real_escape.
$name1 = mysqli_real_escape($link, $_POST["name1"]);
$age = mysqli_real_escape($link, $_POST["age"]);
After that, to show the data when the page reloads, you need to load the data with the page, easiest way to do that is just add in your HTML PHP tags with an echo command inside, adding your variables.
If I understand your question correctly, you want the Ajax result to also show on page load?
Right now you only execute the JS after a click (so on page load/relaod you will just see the html), you might want to execute it after page load aswell (so execute the script without the .click)
You could create a function once, and call it when the page is ready and on click.
user type london record fetch from data base and show below the input field
<input type="text" id="inputSuccess" name="name" onkeyup="autosearch(this.value)" > //user type london
when user click on london than london add in input field but it cannot set in input field what jquery script require to select the value from p tag and show in input field
<script>
function autosearch(name){
//get data from database
$.ajax({
url:"ajax.php",
type:'post',
data: {name: name},
success:function(result){
$('.result').html(result);
}
});
}
</script>
ajax.php
<div style="border: 1px solid #ccc;width:100%;" >
<a href="javascript:void(0)">
</div>
<div>
<p><?php echo $data['cityName']; ?> </p> //london show here
</div>
</a>
</div>
If I got your question then Here is an example to let you clear how to add text in the input. Please checkout below:
HTML:
<input type="text" id="inputSuccess" name="name" onkeyup="autosearch(this.value)" >
<a href="javascript:void(0)" data-val="textToShow" onclick="addTextInInput($(this).data('val'))">
<div>
<p>asd </p>
</div>
</a>
JS:
function addTextInInput(txt){
//get data from database
$("#inputSuccess").val(txt)
}
Replace the textToShow in data-val with your PHP code and try it. Also, find working example here https://jsbin.com/witilohinu/1/edit?html,js,console,output
Please give your feedback in the comment.
I am not sure its you want. But this i understand from your code. if its wrong say me. I will help you fix this.
Add the class for your <input> and set it Ajax result.
<input type="text" id="inputSuccess" name="name" class='result'
onkeyup="autosearch(this.value)" > //user type london
<script>
function autosearch(name){
//get data from database
$.ajax({
url:"ajax.php",
type:'post',
data:{name:name},
success:function(result){
$('.result').html(result);
}
});
}
</script>
You not need this Field.
<p><?php echo $data['cityName']; ?> </p> //london show here
</div>
im trying to make a facebook style post and comment section but i dont know how to display the data inserted to my database without refreshing the page...
this code is for saving the data to my db. i use window.location.reload(); to reload my page so that the data will be displayed on my page..
<script>
$(document).ready(function() {
$('input[name="mycomment"]').on('keyup', function(e){
e.preventDefault();
var comments = $(this).val();
var sid = $(this).closest("div#userspost").find("input[type='hidden']").val();
if(e.keyCode == 13){
if(comments.length)
$.ajax({
url: "../controller/post_controller.php",
type: "POST",
data:{
"id":sid,
"comments":comments,
},
success: function(data)
{
window.location.reload();
}
});
else
alert("Please write something in comment.");
}
});
});
</script>
using this script i can display my comment on a post i need to refresh the page first for me to be able to show the comment.
<?php
foreach ($post_model->getcomment() as $value) {
if($postid == $value['post_uid']){
?>
<div id="mycomments">
<div class="col-lg-12" style="background:#eff9c7;">
<img src="./<?php echo $value['image']?>" class="pull-left" style="border-radius:50%;margin-top:10px;" width="7%" height="7%" />
<p style="margin-top:18px;line-height:15px;"><strong class="font-1" style="margin-left:10px;"><?php echo $value['firstname'].' '.$value['lastname']?></strong> <?php echo $value['pc_comment']?><br>
<span class="" style="margin-left:10px;font-size:.9em;color:gray;"><abbr class="timeago" title="<?php echo $value['pc_datesend']?>"></abbr></span>
</p>
</div>
</div>
<?php
}
}
?>
what im trying to do is that this is where i want to display my comments from my db. i tried researching about append/load but i dont exactly know how this works. is there any idea that i can display my comment in this script?
<div id="mycomments">
<div class="col-lg-12" style="background:#eff9c7;">
<img src="./<?php echo $value['image']?>" class="pull-left" style="border-radius:50%;margin-top:10px;" width="7%" height="7%" />
<p style="margin-top:18px;line-height:15px;"><strong class="font-1" style="margin-left:10px;"><?php echo $value['firstname'].' '.$value['lastname']?></strong> <?php echo $value['pc_comment']?><br>
<span class="" style="margin-left:10px;font-size:.9em;color:gray;"><abbr class="timeago" title="<?php echo $value['pc_datesend']?>"></abbr></span>
</p>
</div>
</div>
I decided to write some pseudo code for you here. If you don't know how to store and fetch comments I would recommend looking into MYSQL. It's relatively simple (for simple things), so that shouldn't be too big of a problem. YouTube tutorials will be your blessing there.
You should have at least three files to properly implement this:
uploadComment.php
<?php
//process the comment upload
echo $_POST['comment'];
?>
getComment.php
<?php
//however you serve commnets, MYSQL, maybe?
//make sure it's properly formatted with HTML
?>
index.html
<form>
<input type="text" name="comment" id="comment" value="Comment here" />
<button id="submit">Submit</button>
</form>
<div id="comments">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$("#submit").click(function () {
$.post("uploadComment.php", {
comment : $("#comment").val()
}, function (data) {
//comment posted.
refreshComments();
});
});
function refreshComments() {
$.get("getComments.php", function(data) {
$("#comments").html(data);
});
}
setInterval(refreshComments,5000);
</script>
Note: Although it may be annoying, if you want immediate satisfaction, append the new comment to the end and then invoke refreshComments. (But I wouldn't recommend doing this because it would force you to update multiple locations in your code whenever you change your comment HTML format).
I have a html file which loads a list from my database and allows the front end user to remove a particular entry.
The HTML Code looks like this:
<script type="text/javascript">// <![CDATA[
function sendForm() {
var dataSend=$("#clientid").val();
$("#responseDiv").html("<h2>Removing from Database...</h2>");
$.post("RemoveClient.php",{
ClientId: dataSend
},function(data) {
$("#responseDiv").html(data);
$("#clientlist").empty();
$("#clientlist").html("{client_list nocache}");
});
return false;
}
// ]]></script>
</p>
<div id="MainForm"><form class="form" onsubmit="return sendForm()">
<h2 class="formstyle">Client Wizard</h2>
<p>Please fill all the required fields.</p>
<div id="clientlist">{client_list nocache}</div>
<p><input style="font-size: 1.5em; font-color: #000000;" onclick="sendForm()" type="submit" value="Delete" /></p>
</form>
<div id="responseDiv"> </div>
</div>
The UDT called for {client_list} is given below.
$dbhost='127.0.0.1';
$dbuser='user';
$dbpass='pass';
$dbname='dbname';
$conn=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if(!$conn)
{
die('Could not connect:'.mysqli_connect_error());
}
$sql="SELECT clientid,clientname FROM client order by clientid";
echo "<label> Select Client: </label>";
echo "<select id=clientid name=clientid>";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($result))
{
echo "<option value=".$row['clientid'].">".$row['clientname']."</option>";
}
echo "</select>";
Now, once I click on delete, I want the drop down list to refresh with the new list not having the deleted client. I tried doing that by emptying the div and then reloading the UDT. Unfortunately this does not seem to be working, the way I want it to, as the list does not get refreshed until and unless I refresh the page. Is there anyway I can make this work?
The quick/easiest option would be to assign it an id and to remove the entry via javascript.
Second, would be to have RemoveClient.php return it as part of the response from the AJAX.
var response = data.split('|');
$("#responseDiv").html(response[0]);
$("#clientlist").html(response[1]);
Third, I would strongly advise against this way but it is the question you ask, put the UDT alone on new page then load the page with the ?showtemplate=false parameter.
$("#clientlist").load("//www.mydomain.com/myudt.html?showtemplate=false");
I am getting JSON data list of collage within given distance in K.M. Now I have to add this collage list to the JQuery Mobile List View. In register page student information will fill. Then after pressing Register button javascript will execute and In Java script we are passing the distance as parameter, On server will fetch list of collage located within given distance. I intentionally did not mentioned longitude and latitude simplify reason. Letter We will pass two parameter current longitude and latitude instead of distance. Now fetched data which will in json formate I have to add this information to page CollageOptions under ul view. Please tell me what should I write inside
success: function(response) in javascript.
Structure of database is
<div data-role="page" id="register" data-theme="d" style="width: 100%;">
Name :<input type="text" placeholder="Name" name="userName">
Email: <input type="text" placeholder="Email" name="eMail">
Mobile: <input type="number" placeholder="Mobile" name="mobNumber">
Distance: <input type="text" id="distance_id" name="distance" />
<a href="#CollageOptions" class="ui-btn" style="background-color: #B6B6BC; color: black;"
id="btnReg">Register</a>
</div>
<div data-role="page" id="CollageOptions">
<div style="width: 100%; margin-top:21%; margin-left: 1%; color: black; id="details" data-
role="listview">
<ul id="listOfCollage" data-role="listview">
Here I have to list list of collage available with in given distance
</ul>
</div>
Now suppose distance is 35 k.m. then list of collage will fetch
<?php
header('Access-Control-Allow-Origin: *');//Should work in Cross Domaim ajax Calling request
mysql_connect("localhost","root","1234");
mysql_select_db("foodybuddy");
if(isset($_GET['type']))
{
if($_GET['type']=="login"){
$distanceInKM=$_GET['Distance'];
$query="Select * from collage where Distance<='$distanceInKM'";
$result=mysql_query($query);
$totalRows=mysql_num_rows($result);
if($totalRows>0){
$recipes=array();
while($recipe=mysql_fetch_array($result, MYSQL_ASSOC)){
$recipes[]=array('Chef'=>$recipe);
}
$output=json_encode(($recipes));
echo $output;
}
}
}
else{
echo "Invalid format";
}
<script>
$(document).ready(function(){
$("#btnReg").click(function(){
var distance = document.getElementById('distance_id').value;
$.ajax({
url:"http://192.168.1.4/Experiements/webservices/getBuddy.php",
type:"GET",
dataType:"json",
data:{type:"login", Distance:distance},
ContentType:"application/json",
success: function(response){
},
error: function(err){
alert(JSON.stringify(err));
}
}) //ajax
}); //click
}); //ready
</script>
You can use an each loop to read the Json Data and prepare the list items
var output = ""; // declare an empty variable inside click function
$("#listOfFoodOptions").empty(); // empty the list
.
.
.
success: function(response){
$.each(response, function(index,value){ // loop through the data
output += "<li>"+value.Chef.Name+"</li>";
});
$("#listOfFoodOptions").append(output).listview().listview('refresh'); // refresh the list
}
.
.
.
.