function showComments(wallID){
$.ajax({
url: "misc/showComments.php",
type: "POST",
data: { mode: 'ajax', wallID: wallID },
success: function(msg){
var $msg = $('#showWallCommentsFor'+wallID).find('.userWallComment');
// if it already has a comment, fade it out, add the text, then toggle it back in
if ( $msg.text().length ) {
$msg.fadeOut('fast', function(){
$msg.text( msg ).slideToggle(300);
});
} else {
// otherwise just hide it, add the text, and then toggle it in
$msg.hide().text( msg ).slideToggle(300);
}
}
});
}
msg, the response i get: ( firebug )
<span class='userWallComment'>
<span style='float: left;'>
<img style='border: 1px solid #ccc; width: 44px; height: 48px; margin-right: 8px;' src='images/profilePhoto/thumbs/noPhoto_thumb.jpg'>
</span></span>
<span style='font-size: 10px; margin-bottom: 2px;'>
<a href='profil.php?id=1'>Navn navn</a> - igår kl. 01:55
</span>
<br>
DETTE ER EN TEST
<br>
<div class="clearfloat"></div>
</span>
It sends and execute the ajax call properly, and it have something in response, but it doesnt toggle it?
This is the div:
<div id="showWallCommentsFor<?php echo $displayWall["id"]; ?>" style="display: none;">
</div>
The Problem
Your if - else statement has a flaw:
if ( $msg.text().length ) {
// ...
} else {
// $msg has a length of ZERO by definition here!!!
$msg.hide().text( msg ).slideToggle(300);
}
The very first time the AJAX call is fired #showWallCommentsFor is empty, so it doesn't have .userWallComment inside it so, $msg will not be defined.
The Solution
You should add text directly to the original div in your else, using:
if ( $msg.text().length ) {
// ...
} else {
// otherwise just hide it, add the text, and then toggle it in
// You cannot use $msg here, since it has a length of 0.
// Add text directly to the original div instead.
// You do not need to hide the DIV first since it is already
// invisible.
$('#showWallCommentsFor'+wallID).text( msg ).slideToggle(300);
}
Finally, in your else, there's no need to .hide() the #showWall... div, since the div is orginally invisible due to style="display: none;".
Related
I was trying to parse data to my controller so I can insert it into the database using JQuery and it was returning null. It's for a review star system so doesn't use conventional form fields however the network tab in inspect elements shows that data is actually posted to the controller just, not able to read it for some weird reason.
Update: The data is being inserted fine on desktop however the confirmation (flashdata) message is shown correctly not sure why. Additionally on mobile view no data or message is shown. Does anyone know why? I have updated the code below..
Here's the code from my view:
<?php if($this->session->flashdata('review_submitted')){ ?>
<div class="alert alert-success alert-dismissible container show" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong>Thank you!</strong> Your review has been submitted.
</div>
<?php } ?>
<form id="myForm" name="myForm">
<br>
<div class="form-group text-left div-style">
<h3 style="font-family: MontserratLight;letter-spacing: 2px; line-height: 32px;">Full Name <b>*</b></h3>
<input name="name" class="form-control" style="background: #f7f7f7; border: 1px solid #801424;" required />
</div>
<div class="rate">
<div id="1" class="btn-1 rate-btn"></div>
<div id="2" class="btn-2 rate-btn"></div>
<div id="3" class="btn-3 rate-btn"></div>
<div id="4" class="btn-4 rate-btn"></div>
<div id="5" class="btn-5 rate-btn"></div>
</div>
<script>
$(function(){
$('.rate-btn').hover(function(){
$('.rate-btn').removeClass('rate-btn-hover');
var therate = $(this).attr('id');
for (var i = therate; i >= 0; i--) {
$('.btn-'+i).addClass('rate-btn-hover');
};
});
$('.rate-btn').click(function(){
var therate = $(this).attr('id');
var dataRate = 'rate='+therate; //
$('.rate-btn').removeClass('rate-btn-active');
for (var i = therate; i >= 0; i--) {
$('.btn-'+i).addClass('rate-btn-active');
};
$('#myForm').on('submit', function(e){
var url = "<?php echo base_url(); ?>index.php/reviews/add_review";
// $('#myForm').append(therate);
var dataPost = $('#myForm').serialize() + "&rate=" + therate;
$.ajax({
type : "POST",
url : url,
data: dataPost,
success:function(){
}
});
});
});
});
</script>
and using the controller I simply use the following to get the data and add it to the database:
public function add_review(){
$name = $this->input->post('name');
$rating = $this->input->post('rate');
$dataDB = array(
'full_name' => $name,
'rating' => $rating
);
if($this->functions->submit($dataDB)){
$this->session->set_flashdata('review_submitted', true);
redirect(base_url() . 'reviews/index', 'refresh');
}
}
Here's some CSS that I used, perhaps the problem is to do with the mobile browser not having a cursor?
.rate{
width:245px; height: 40px;
margin-bottom:0px;
}
.rate .rate-btn{
width: 45px; height:40px;
float: left;
background: url(rate-btn.png) no-repeat;
cursor: pointer;
cursor:hand;
pointer-events: auto;
}
.rate .rate-btn:hover, .rate .rate-btn-hover, .rate .rate-btn-active{
background: url(rate-btn-hover.png) no-repeat;
}
When passing data through ajax, I think it is better to use JSON dataType. Reform the data type (string -> data object). Besides, I don't think it is really necessary to concat the 'to-be-sent' data into a string.
If you want dynamic data to be sent, you can push elements by condition
$.ajax({
type : "POST",
dataType: 'text' //it is not necessary if you are not returning any data (if you return json, put 'JSON'),
url : "<?php echo base_url(); ?>index.php/reviews/add_review",
data: dataRate, //change to {key:value,key:value}
success:function(data){
}
});
This is just to address your issue with your AJAX Posted Values not appearing where you are expecting them ONLY.
There are a zillion ways you can code this but here is just one which I have changed about to perform debugging. Even I learned a new trick doing this.
Just Nit Picking but what stuck out when reading your code is your use of therate when everywhere else in your JS you use camel case so it should be theRate.It's a good idea to choose a standard and stick to it.
Plus you had what appeared to be nested events in your JS. Some attempt at getting theRate to work correctly? Anyway...
First things. Get back to something basic and work your way back up. (Although in this case I didn't strip your view back to bare bones, but I did with your controller.
Your View.
I had to change this up a bit and hopefully the comments explain things.
I called it rating_view.php
<form name="my-form" id="my-form">
<div class="rate">
<div id="1" class="btn-1 rate-btn">1</div>
<div id="2" class="btn-2 rate-btn">2</div>
<div id="3" class="btn-3 rate-btn">3</div>
<div id="4" class="btn-4 rate-btn">4</div>
<div id="5" class="btn-5 rate-btn">5</div>
</div>
<input type="submit">
</form>
<!-- Added for viewing debug response -->
<div id="json-debug-output"></div>
<!-- Some styles added as non were provided -->
<style>
.rate-btn-hover {
background: blue;
}
.rate-btn-active {
background: yellow;
}
</style>
<script src= <?= base_url('assets/js/jquery_v3.4.1.js'); ?>></script>
<script>
$(document).ready(function () {
// Define your Dom Elements ONCE for efficiency etc
let domRateButton = $('.rate-btn');
let domMyForm = $('#my-form');
let theRate = 0; // Declares this as a Global Var.
let domJsonDebugOutput = $('#json-debug-output');
// Hover
domRateButton.hover(function () {
domRateButton.removeClass('rate-btn-hover');
let theRate = $(this).attr('id');
for (let i = theRate; i >= 0; i--) {
$('.btn-' + i).addClass('rate-btn-hover');
}
});
// Click
domRateButton.click(function () {
console.log('Rating Button Clicked');
theRate = $(this).attr('id');
domRateButton.removeClass('rate-btn-active');
for (let i = theRate; i >= 0; i--) {
$('.btn-' + i).addClass('rate-btn-active');
}
});
// Submit
domMyForm.on('submit', function (e) {
e.preventDefault(); // This was missing
console.log('Posting Rate = ' + theRate);
$.ajax({
type: "POST",
// dataType: 'text',
dataType: "json",
url: "<?php echo base_url(); ?>reviews/add_review",
data: {'act': 'rate', 'post_id':<?= $post_id; ?>, 'rate': theRate},
success: function (data) {
let debugData = JSON.stringify(data);
domJsonDebugOutput.text(debugData); // Display in our Debug Div
},
error: function (data) {
let debugData = JSON.stringify(data);
domJsonDebugOutput.text(debugData); // Display in our Debug Div
}
});
});
});
</script>
Note in the AJAX the changes to dataType from text to json. Also note that data is an array.
I also changed the scope of theRate from local to a global so it was "findable" amongst the functions.
NOT SURE how your form was setup but I added e.preventDefault(); to prevent the form submitting for testing.
Personally I cringe at having PHP vars embedded in any JS code and I usually have my JS as external files and pass in the values from PHP by reading them using JS but that's got it's Pros and Cons as well. So I left that alone for the sake of not going too far with this.
For your Controller - Called Reviews.php
public function show() {
$data['post_id'] = 1; // This comes from somewhere
$content = $this->load->view('rating_view', $data, TRUE);
echo $content;
}
/**
* Called by AJAX
* Do we need to test this is only called by AJAX?
*/
public function add_review() {
// Return everything that was sent for debugging
echo json_encode($this->input->post());
// var_dump($this->input->post());
exit();
}
So here I just had a method show() show the form and the add_review to simply bounce back what was sent. You can do all sorts of things with this. One nice aspect in this case is you do not need to use console.log) as you can view it all on the page (BUT ONLY FOR DEBUGGING). It's another option.
So have a play with that and start making changes to your code and see what works. Remember - get back to basics and pick on the bit that isn't working.
Next you will find you might be getting tripped up on your redirect. But that's for another post.
I am using AJAX to receive data from my database on to my main PHP page.
I have a piece of code that worked, but on with PHP.
When I have just tried to put it in to AJAX (receiving format), the code that I return is not being shown.
I know my AJAX method works as I'm using it to get some other database values.
It's just the Get online users individually won't work.
When I load the page, the code shows what's inside my div id - Loading Info... and then goes blank, so I know it's trying to update it but it's not getting it correctly.
Picture showing that nothing is displayed
My PHP request code is :
//Get online users individually and echo if they're online or not in a div class
$user_grab = mysqli_query($con, "SELECT * FROM users");
while($users_ = mysqli_fetch_array($user_grab)) {
$last_online = strtotime($users_['lastonline']);
if(time() - $last_online < 30) {
$client_is_online = '
<div class="chat-list-item -available" style="background: rgba(255,255,255,0.1); padding: 5px;">
<img class="chat-list-avatar" src="'.$users_['profile_picture'].'" style="width: 40px; height: 40px; padding: 7px; border-radius: 20px;" /><i class="fa fa-circle chat-list-status"> </i>
<div class="chat-list-user">'.$users_['username'].' (<font size="2">'.get_users_level_all($users_['userLevel']).'</font>)</div>
<div class="chat-list-excerpt">Online</div>
</div>
';
} else {
$client_is_online = '
<div class="chat-list-item -offline" style="background: rgba(255,255,255,0.1); padding: 5px;">
<img class="chat-list-avatar" src="'.$users_['profile_picture'].'" style="width: 40px; height: 40px; padding: 7px; border-radius: 20px;" /><i class="fa fa-circle chat-list-status"> </i>
<div class="chat-list-user">'.$users_['username'].' (<font size="2">'.get_users_level_all($users_['userLevel']).'</font>)</div>
<div class="chat-list-excerpt">Offline</div>
</div>
';
}
}
//I then echo it back to my home PHP page so it can read the values
//Ignore my other code definitions below as I know they work
//$client_is_online is the only one which doesn't
echo $totalUsers.",".$totalOnline.",".$freemode.",".$bypasses.",".$client_is_online;
My AJAX recieve code is :
<script>
function fetchOnline() {
$.ajax({
url: "includes/get_dash_settings.php",
context: document.body,
success: function(value){
var data = value.split(",");
$('#totalUsers').html(data[0]);
$('#totalOnline').html(data[1]);
$('#freeModeStatus').html(data[2]);
$('#bypassesStatus').html(data[3]);
$('#isOnline').html(data[4]);
},
complete:function(){
setTimeout(fetchOnline,5000);
}
})
}
$(document).ready(function() { setInterval(fetchOnline,5000); });
</script>
I then try storing the returned data in-side my div id :
<div class="sidebar-tab-content" id="staff">
<div class="chat-list sidebar-content-section" id="isOnline">
Loading Info...
</div>
</div>
Return the json data like this
1st : your overwriting the variable . you need to concatenate all user like this
$client_is_online=""; //declare empty string before while loop start
//while loop start here
$client_is_online .= 'html here';
// while end here
2nd : Return the json data like this
$response = array ('totalUsers'=> $totalUsers, 'totalOnline'=> $totalOnline,'freemode'=>$freemode,'bypasses'=>$bypasses,'client_is_online'=>$client_is_online);
header('Content-Type: application/json');
echo json_encode($response);
3rd : Don't forgot to add dataType in ajax
dataType: "json",
4rd : success function should be changed like this
ajax :
success: function(value){
var data = JSON.parse(value);
$('#totalUsers').html(data['totalUsers']);
$('#totalOnline').html(data['totalOnline']);
$('#freeModeStatus').html(data['freemode']);
$('#bypassesStatus').html(data['bypasses']);
$('#isOnline').html(data['client_is_online']);
},
I am trying to create an input that queries the database and returns whether or not a result exists in the database. I have it partially working, but my box is glowing green whenever I only type in one letter. It would be better if it stayed red until it actually found a exact match and then turned green. Edit: I just realized there is also something wrong with my query. It is correctly querying the database now. The original issue is my main problem.
$(document).ready(function(){
$("#load").keyup(function (e){
e.preventDefault();
;
searchRequest = $.ajax({
url: 'check_load_no.php',
data: $('#load').serialize(),
type: 'POST',
success: function (data) {
$(".verify").css('box-shadow', '0px 0px 9px 2px #84f850');
$(".error").css('display', 'none');
$(".success").css('display', 'block');
},
error: function (data) {
$(".verify").css('box-shadow', '0px 0px 9px 2px #ad0037');
$(".success").css('display', 'none');
$(".error").css('display', 'block');
}
});
});
});
Below is my php
<?php include('../model/conn.php'); ?>
<?php include('../model/conn2.php') ?>
<?php
$sql = "SELECT cmt_2 FROM oeordhdr_sql WHERE cmt_2 = '{$_POST['load']}'";
$query = (odbc_exec($conn,$sql));
$row = (odbc_fetch_row($query));
if($row['cmt_2']){
echo 'yeah';
}
HTML
<h1>Please add the info based on your load number</h1>
<form action="" method="post">
<div class="card" >
<input class="verify" id="load" type="text" name="load" placeholder="Load Number" required/>
<span class="error" style="display: none;"><i class="fa fa-exclamation-triangle fa-lg" aria-hidden="true"> </i>I'm not finding anything</span>
<span class="success" style="display: none;"> <i class="fa fa-check-cube fa-lg" aria-hidden="true"> </i> Congratulations, that record exists!</span><br>
<button class="update_button" type="submit" name="add" value="update">Update</button></div></form>
Your error handler will not be called even if "yeah" is not echoed out by PHP script, as the server response would still be HTTP 200. For this reason, your success handler will always trigger (unless of course there is an actual problem with your server/application).
If you want to trigger the error handler, you would have to have the server send a 400 or 500 series HTTP response code (likely 404 in this case) for the case when no match is found.
Alternately, you could just put all your logic in the success handler and not change your server-side code at all. You would just have to test for the value of "yeah" being present or not.
You should also consider adding/removing CSS classes on your DOM elements rather than specifically specifying the CSS in your function. This would allow you to later change the CSS if needed, without having to alter this function.
success: function (data) {
if(data==="yeah")
{
$(".verify").css('box-shadow', '0px 0px 9px 2px #84f850');
$(".error").css('display', 'none');
$(".success").css('display', 'block');
}
else
{
$(".verify").css('box-shadow', '0px 0px 9px 2px #ad0037');
$(".success").css('display', 'none');
$(".error").css('display', 'block');
}
}
check if response is what you need and only then add .success class
Decided to output the error/success message using php instead of changing css
$("#load").keyup(function (e){
e.preventDefault();
searchRequest = $.ajax({
url: 'check_load_no.php',
data: $('#load').serialize(),
type: 'POST',
success: function (data) {
console.log(data);
if(data==="yeah")
{
$(".validate").html(data);
}
else
{
$(".validate").html(data);
}
}
});
});
My php
$sql = "SELECT cmt_2 FROM oeordhdr_sql WHERE cmt_2 LIKE '{$_POST['load']}'";
$query = odbc_exec($conn,$sql);
$row = (odbc_fetch_row($query));
if($row){
echo '<span class="success" style="display: block;"> <i class="fa fa-check-cube fa-lg" aria-hidden="true"> </i> Congratulations, that record exists!</span>';
}else{
echo'<span class="error" style="display: block;"><i class="fa fa-exclamation-triangle fa-lg" aria-hidden="true"> </i>I\'m not finding anything</span>';
}
My HTML
<h1>Please add the info based on your load number</h1>
<form action="" method="post">
<div class="card" >
<input class="verify" id="load" type="text" name="load" placeholder="Load Number" required/>
<div class="validate"></div><br>
<button class="update_button" type="submit" name="add" value="update">Update</button></div></form>
I have an HTML form that is split into three major components. The top portion is essentially a header for displaying a magazine name. This information does not change.
The middle portion is a table developed through a MySQL query for displaying the story information as a table of contents after it is entered in the bottom portion, which is a data entry screen.
The bottom portion, is a data entry screen for entering the information concerning each story contained in the magazine issue.
After entering the data and pressing the submit button in the bottom portion, the middle portion should be updated through the MySQL query to reflect the newly entered story. That was not happening.
Note: The code previously associated with this question has been removed for purposes of clarity. The solution was associated with how the various forms were called. My thanks to Sulthan Allaudeen for providing potential solutions. Currently, I am not familiar with utilizing jquery-ajax. Eventually I will need to learn.
As the OP wanted to know how do the jquery and ajax call
Step 1 :
Recognize the Input
Have a button with a class trigger
$(".trigger").click(function()
{
//your ajax call here
}
Step 2 :
Trigger your ajax call
$.ajax({
type: "POST",
url: "yourpage.php",
data: dataString,
cache: false,
success: function(html)
{
//your action
}
});
Step 3 :
Inside your success function show the result
$("#YourResultDiv").html(data);
For that you should create a div named as YourResultDiv
Note :
Inside your yourpage.php You should just print the table and it will be displayed as the output
Here's a brief example of displaying the results of submitting a form without leaving the current page. Form submission is done with the help of Ajax.
Each form has it's own button for submission, hence the loop over matching elements in onDocLoaded.
1. blank.php form is submitted to this script
<?php
echo "-------------------------------<br>";
echo " G E T - V A R S<br>";
echo "-------------------------------<br>";
var_dump( $_GET ); echo "<br>";
echo "-------------------------------<br>";
echo " P O S T - V A R S<br>";
echo "-------------------------------<br>";
var_dump( $_POST ); echo "<br>";
echo "<hr>";
if (count($_FILES) > 0)
{
var_dump($_FILES);
echo "<hr>";
}
?>
2. blank.html Contains 2 forms, shows the result of submitting either of them to the above script.
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
function allByClass(className,parent){return (parent == undefined ? document : parent).getElementsByClassName(className);}
function allByTag(tagName,parent){return (parent == undefined ? document : parent).getElementsByTagName(tagName);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
function toggleClass(elem, className){elem.classList.toggle(className);}
function toggleClassById(targetElemId, className){byId(targetElemId).classList.toggle(className)}
function hasClass(elem, className){return elem.classList.contains(className);}
function addClass(elem, className){return elem.classList.add(className);}
function removeClass(elem, className){return elem.classList.remove(className);}
function forEachNode(nodeList, func){for (var i=0, n=nodeList.length; i<n; i++) func(nodeList[i], i, nodeList); }
// callback gets data via the .target.result field of the param passed to it.
function loadFileObject(fileObj, loadedCallback){var reader = new FileReader();reader.onload = loadedCallback;reader.readAsDataURL( fileObj );}
function myAjaxGet(url, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("GET", url, true);
ajax.send();
}
function myAjaxPost(url, phpPostVarName, data, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send(phpPostVarName+"=" + encodeURI(data) );
}
function myAjaxPostForm(url, formElem, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("POST", url, true);
var formData = new FormData(formElem);
ajax.send( formData );
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
forEachNode( allByClass('goBtn'), function(elem){elem.addEventListener('click', onGoBtnClicked, false);} );
}
function onGoBtnClicked(evt)
{
evt.preventDefault();
var thisElem = this;
var thisForm = thisElem.parentNode;
myAjaxPostForm('blank.php', thisForm, onPostSuccess, onPostFailed);
function onPostSuccess(ajax)
{
byId('tgt').innerHTML = ajax.responseText;
}
function onPostFailed(ajax)
{
//byId('tgt').innerHTML = ajax.responseText;
alert("POST FAILED!!!!");
}
return false;
}
</script>
<style>
#page
{
display: inline-block;
border: solid 1px gray;
background-color: rgba(0,0,0,0.2);
border-radius: 6px;
}
.controls, .tabDiv
{
margin: 8px;
border: solid 1px gray;
border-radius: 6px;
}
.tabDiv
{
overflow-y: hidden;
min-width: 250px;
background-color: white;
border-radius: 6px;
}
.tabDiv > div
{
padding: 8px;
}
</style>
</head>
<body>
<div id='page'>
<div class='tabDiv' id='tabDiv1'>
<!-- <div style='padding: 8px'> -->
<div>
<form id='mForm' enctype="multipart/form-data" >
<label>Name: </label><input name='nameInput'/><br>
<label>Age: </label><input type='number' name='ageInput'/><br>
<input type='file' name='fileInput'/><br>
<button class='goBtn'>GO</button>
</form>
</div>
</div>
<div class='tabDiv' id='tabDiv2'>
<!-- <div style='padding: 8px'> -->
<div>
<form id='mForm' enctype="multipart/form-data" >
<label>Email: </label><input type='email' name='emailInput'/><br>
<label>Eye colour: </label><input name='eyeColourInput'/><br>
<label>Read and agreed to conditions and terms: </label><input type='checkbox' name='termsAcceptedInput'/><br>
<button class='goBtn'>GO</button>
</form>
</div>
</div>
<!-- <hr> -->
<div class='tabDiv'>
<div id='tgt'></div>
</div>
</div>
</body>
</html>
The solution to refreshing the form to display the addition of new data was to re-call it through the following line: "include("new_stories.inc.php");". This line is imediately executed just after the MySQL insert code in the data entry section of the form.
The middle section of the form "new_stories.inc.php" (the table of contents) queries the MySQL data base to retrieve the story information related to the current magazine issue. Re-calling the form is equivalent to a re-query.
I need the jquery script for the following
while typing inside the text field, the 'Load' text need to be displayed near the text field.
If i stop typing the 'Load' text need to change as 'Del'
If click this 'Del' Text the text field should be cleared.
In the mean time i need to display the search result for the entered text.
For this i used the following script
$("#lets_search").keyup(function() {
var value = $('#str').val();
$.post('db_query.php',{value:value}, function(data){
$("#search_results").html(data);
});
return false;
});
});
Here is the html part of the file
<form id="lets_search" action="" style="width:400px;margin:0 auto;text-align:left;">
Search:
<div> </div>
<div style="float:left; width:250px;">
<div style="background-color:#fff; padding:3px; width:200px; float:left; border-left:1px solid #eee; border-top:1px solid #eee; border-bottom:1px solid #eee;">
<input name="str" id="str" type="text" style="border:0px; width:150px;">
<div style="float:right; padding-top:3px;" id="loader">Load</div>
</div>
</div>
</form>
<div id="search_results"></div>
In this <div style="float:right; padding-top:3px;" id="loader">Load</div>
I have to display the text (del, Loading etc...)
Please do the needful. Thanks
I think the best way to do this is with a setTimeout, like so:
var pTimeout = null;
$("#lets_search").keyup(function()
{
var value = $('#str').val();
$('#loader').text('Loading...').unbind('click');
if(pTimeout) clearTimeout(pTimeout);
pTimeout = setTimeout(function () { GetResult(value); }, 50);
});
function GetResult(value)
{
$.post('db_query.php',{value:value}, function(data){
pTimeout = null;
$('#loader').text('del').click(function () {
$("#search_results").empty();
$('#str').val('');
});
$("#search_results").html(data);
});
}
There is always a better way of doing it, but must give you the idea.
PS I did not test the code :)
var searchTimeout = null;
$("#str").keyup(function() {
// Clear any existing timeout
if (searchTimeout) {
clearTimeout(searchTimeout);
}
// Put "Load" text in
$('#loader').html('Load');
// Set a timeout for end of typing detection
searchTimeout = setTimeout(function() {
$('#loader').html('Del');
}, 500);
// Get the value from the text field and send it to the server
var value = $(this).val();
$.post('db_query.php',{value:value}, function(data){
$("#search_results").html(data);
});
});
// Clears the search box value
function clearSearch() {
$("#str").val('');
};