How to bring ajax search onkeyup with jquery - javascript

My Script to call ajax
<script language="javascript">
function search_func(value)
{
$.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg){
//Receiving the result of search here
}
});
}
</script>
HTML
<input type="text" name="sample_search" id="sample_search" onkeyup="search_func(this.value);">
Question: while onkeyup I am using ajax to fetch the result. Once ajax result delay increases problem occurs for me.
For Example
While typing t keyword I receive ajax result and while typing te I receive ajax result
when ajax time delay between two keyup sometime makes a serious issue.
When I type te fastly. ajax search for t keyword come late, when compare to te. I don't know how to handle this type of cases.
Result
While typing te keyword fastly due to ajax delays. result for t keyword comes.
I believe I had explained up to reader knowledge.

You should check if the value has changed over time:
var searchRequest = null;
$(function () {
var minlength = 3;
$("#sample_search").keyup(function () {
var that = this,
value = $(this).val();
if (value.length >= minlength ) {
if (searchRequest != null)
searchRequest.abort();
searchRequest = $.ajax({
type: "GET",
url: "sample.php",
data: {
'search_keyword' : value
},
dataType: "text",
success: function(msg){
//we need to check if the value is the same
if (value==$(that).val()) {
//Receiving the result of search here
}
}
});
}
});
});
EDIT:
The searchRequest variable was added to prevent multiple unnecessary requests to the server.

Keep hold of the XMLHttpRequest object that $.ajax() returns and then on the next keyup, call .abort(). That should kill the previous ajax request and let you do the new one.
var req = null;
function search_func(value)
{
if (req != null) req.abort();
req = $.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg){
//Receiving the result of search here
}
});
}

Try using the jQuery UI autocomplete. Saves you from many low-level coding.

First i will suggest that making a ajax call on every keyup is not good (and this why u run in this problem) .
Second if you want to use keyup then show a loading image after input box to show user its still loading (use loading image like you get on adding comment)

Couple of pointers. Firstly, language is a deprecated attribute of javascript. In HTML(5) you can leave the attribute off, or use type="text/javascript". Secondly, you are using jQuery so why do you have an inline function call when you can do that with jQuery too?
$(function(){
// Document is ready
$("#sample_search").keyup(function()
{
$.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg)
{
//Receiving the result of search here
}
});
});
});
I would suggest leaving a little delay between the keyup event and calling an ajax function. What you could do is use setTimeout to check that the user has finished typing before then calling your ajax function.

Related

(this).parent().find not working for getting response in ajax call

$(".content-short").click(function() {
$(".content-full").empty();
var contentid=$(this).parent().find(".content-full").attr('data-id');
var content=$(this).parent().find(".content-full");
alert(contentid);
var collegename = $(this).attr('data-id');
$.ajax({
type: "post",
url: "contenthome.php",
data: 'collegename=' + collegename,
dataType: "text",
success: function(response) {
$content.html(response);
}
});
});
here the alert displays the specific data-id but
content=$(this).parent().find(".content-full");
this didn't displays data in content-full div with that specific data-id
anything wrong in the code or something else?
the query displays data if i use(."content-full"); instead of
$(this).parent().find(".content-full");
Inside the ajax callback you are using $content, but you declare your variable as content. May that be the problem?
Your question is not clear. What are you trying to achieve?

AJAX success callback only carrying out first function

I've got a simple form submission that upon success I've got an alert and a call to clear the form. I do get the alert, the info gets successfully added to the database, but the second call--for the form to clear, is not being carried out. I'm sure it's something simple I'm doing wrong, but I can't figure it out.
$('#contact_submit').click(function(e){
if ($("#submit_form_contact").valid()) {
var post_data = {
"name" : $('#name').val(),
"email" : $('#email').val(),
"inquiry" : $('#inquiry_dropdown option:selected').text(),
"message" : $('#message').val()
};
$.ajax({
type: "POST",
url: "process-contact.php",
data: post_data,
success: function(data) {
alert("Thank you for contacting us.");
$('#submit_form_contact').reset();
}
});
e.preventDefault();
}
Also, the submit button is just a button, not a submit input. Is it necessary to preventDefault()? I'm new at this.
jQuery doesn't have a .reset() method.
Do this instead:
$('#submit_form_contact')[0].reset();
This grabs the first DOM element, and invokes the native .reset(). If there's any chance the form won't be found, then test for the element.
var f = $('#submit_form_contact')[0];
if (f)
f.reset();
And of course you don't really need jQuery to get an element by ID, especially if you're not going to use any jQuery methods.
var f = document.getElementbyId('submit_form_contact');
if (f)
f.reset();
Another alternative would be to set the submit button as the context: of the ajax call, then use its form property.
$.ajax({
context: this,
type: "POST",
url: "process-contact.php",
data: post_data,
success: function(data) {
alert("Thank you for contacting us.");
this.form.reset();
}
});
this line can be used too
$("#submit_form_contact").trigger('reset');

Chrome issue - chat lines return multiple times

I wrote a little chat plugin that i'll need to use on my site. It works with a simple structure in HTML, like this:
<div id="div_chat">
<ul id="ul_chat">
</ul>
</div>
<div id="div_inputchatline">
<input type="text" id="input_chatline" name="input_chatline" value="">
<span id="span_sendchatline">Send</span>
</div>
There's a 'click' bound event on that Span element, of course. Then, when the user inserts a message and clicks on the "Send" span element, there's a Javascript function with calls an Ajax event that inserts the message into the MySQL database:
function function_write_newchatline()
{
var chatline = $('#input_chatline').val();
$.ajax
({
type: "POST",
url: "ajax-chat-writenewline.php", //1: ok, 0: errore
data: ({'chat_line': chatline}),
dataType: "text",
cache: false,
success: function(ajax_result)
{
function_get_newchatlines();
}
});
}
And, in case the message is successfully inserted into DB, it calls a function to read new lines and put them in HTML structure i posted before:
function function_get_newchatlines()
{
$.ajax
({
type: "POST",
url: "ajax-chat-loadnewlines.php", //1: ok, 0: errore
data: '',
dataType: "text",
cache: false,
success: function(ajax_result) //example of returned string: 'message1>+<message2>+<message3'
{
//explode new chat lines from returned string
var chat_rows = ajax_result.split('>+<');
for (id_row in chat_rows)
{
//insert row into html
$('#ul_chat').prepend('<li>' + chat_rows[id_row] + '</li>');
}
$('#span_sendchatline').html('Send');
}
});
}
Note: 'ajax_result' only contains html entities, not special chars, so even if a message contains '>+<', it is encoded by the php script called with Ajax, before being processed from this JS function.
Now, comes the strange behaviour: when posting new messages Opera, Firefox and even IE8 works well, as intended, like this:
But, when i open Chrome window, i see this:
As you can see, in Chrome the messages are shown multiple times (increasing the number each time, up to 8 lines per message). I checked the internal debug viewer and it doesn't seem that the "read new lines" function is called more than one time, so it should be something related to Jquery events, or something else.
Hope i've been clear in my explanation, should you need anything else, let me know :)
Thanks, Erenor.
EDIT
As pointed out by Shusl, i forgot to mention that the function function_get_newchatlines() is called, periodically, by a setInterval(function_get_newchatlines, 2000) into Javascript.
EDIT2
Here's is a strip of the code from the PHP file called by Ajax to get new chat lines (i don't think things like "session_start()" or mysql connection stuff are needed here)
//check if there's a value for "last_line", otherwise put current time (usually the first time a user logs into chat)
if (!isset($_SESSION['prove_chat']['time_last_line']) || !is_numeric($_SESSION['prove_chat']['time_last_line']) || ($_SESSION['prove_chat']['time_last_line'] <= 0))
{
$_SESSION['prove_chat']['time_last_line'] = microtime(true);
}
//get new chat lines
$result = mysql_query("select * from chat_module_lines where line_senttime > {$_SESSION['prove_chat']['time_last_line']} order by line_senttime asc; ", $conn['user']);
if(!$result || (mysql_num_rows($result) <= 0))
{
mysql_close($conn['user']); die('2-No new lines');
}
//php stuff to create the string
//....
die($string_with_chat_lines_to_be_used_into_Javascript);
Anyway, i think that, if the problem was this PHP script, i would get similar errors in other browsers, too :)
EDIT4
Here's the code that binds the click event to the "Send" span element:
$('#span_sendchatline').on('click', function()
{
//check if there's already a message being sent
if ($('#span_sendchatline').html() == 'Send')
{
//change html content of the span element (will be changed back to "send"
//when the Ajax request completes)
$('#span_sendchatline').html('Wait..');
//write new line
function_write_newchatline();
}
//else do nothing
});
(Thanks to f_puras for adding the missing tag :)
I would do one of the following:
option 1:
stop the timer just before the ajax call in function_write_newchatline() and start the timer when the ajax call returns.
function function_write_newchatline()
{
var chatline = $('#input_chatline').val();
stop_the_timer();
$.ajax
({
type: "POST",
url: "ajax-chat-writenewline.php", //1: ok, 0: errore
data: ({'chat_line': chatline}),
dataType: "text",
cache: false,
success: function(ajax_result)
{
function_get_newchatlines();
},
complete: function() {
start_the_timer();
}
});
}
option 2:
Not call function_get_newchatlines() at all in the success event of the ajax call. Let only the timer retrieve the chat entries.
function function_write_newchatline()
{
var chatline = $('#input_chatline').val();
$.ajax
({
type: "POST",
url: "ajax-chat-writenewline.php", //1: ok, 0: errore
data: ({'chat_line': chatline}),
dataType: "text",
cache: false,
success: function(ajax_result)
{
// do nothing
}
});
}
I think there is some race condition between the function_get_newchatlines() that is called after a chat entry is added by the user and the periodical call of function_get_newchatlines() by the timer.
option 3:
Use setTimeout instead of setInterval. setInterval can mess things up when the browser is busy. So in the end of the setTimeout function call setTimeout again.

Calling a function from if block in success

Hello fellow programmers. I am newbie to jquery ajax.
How do i call function checkreturn() from if block or is it possible to access msg outside the success if yes then please let me know how. I need it because only if condition proves true i have to enable the subsequent textbox. Here is my code.Thanks in advance for your time and reply.Rajesh.
<script type="text/javascript" >
function checkreturn() {
document.getElementById("txtAns").removeAtrribute("disabled");
}
function cQtn(e){
var uname= $("#<%=Username.ClientID%>").val();
var sq=$("#<%=SecQuest.ClientID%>");
var sqtn = $("#<%=SecQuest.ClientID%> option:selected").text();
var sans=$("#txtAns");
var msgbox = $("#Dstatus");
$.ajax({
type: "POST",
url: "forgotpassword.aspx/CheckValidSQtn",
data: "{'uname':'"+uname+"','args':'"+sqtn+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d == 'Available') {
sq.removeClass("notavailablecss");
sq.addClass("availablecss");
msgbox.html('<img src="proj_mages/a.png"> <font color="Green"> Valid </font>');
//how do i call from here??
}
else {
sq.removeClass("availablecss");
sq.addClass("notavailablecss");
msgbox.html(msg.d);
}
}
});
}
</script>
You have a typo in your checkreturn function. You want to use removeAttribute, instead of removeAtrribute (double t,not double r).
Also, you can use jQuery functions:
function checkreturn(){
$('#txtAns').prop('disabled',false);
}
, instead of native DOM functions (document.getElementById, setAttribute):
not sure what why the normal way is not working but you could try forcing what the browser is supposed to do,
function checkreturn(){
document.getElementById("txtAns").removeAtrribute("disabled");
}
Becomes
window.checkreturn = function(){
document.getElementById("txtAns").removeAtrribute("disabled");
}
Then try calling via window.checkreturn(); or checkreturn(); you can also so try this the other way arround so you can leave your function and try calling window.checkreturn();
If none of these are working it would say your function is not entering the window(Global) scope for your page use Firebug or Inspector and try to all checkreturn(); see what exception you get back,
if you get a not found your not showing us some thing in your code maybe a closure or some thing
I'll look into it further but try setting async for the ajax call to false:
function checkreturn() {
document.getElementById("txtAns").removeAtrribute("disabled");
}
function cQtn(e) {
var uname= $("#<%=Username.ClientID%>").val(),
sq=$("#<%=SecQuest.ClientID%>"),
sqtn = $("#<%=SecQuest.ClientID%> option:selected").text(),
sans=$("#txtAns"),
msgbox = $("#Dstatus");
$.ajax( {
async: false,
type: "POST",
url: "forgotpassword.aspx/CheckValidSQtn",
data: "{'uname':'"+uname+"','args':'"+sqtn+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d == 'Available') {
sq.removeClass("notavailablecss");
sq.addClass("availablecss");
msgbox.html('<img src="proj_mages/a.png"> <font color="Green"> Valid </font>');
//how do i call from here??
} else {
sq.removeClass("availablecss");
sq.addClass("notavailablecss");
msgbox.html(msg.d);
}
}
} );
}
Now, when the ajax call is made, the rest of the script will wait til it completes instead of how everything continues when async is true.

jQuery script supposed to run async but works only sync? why?

I have this small jquery script that does not work if I remove the 'async:false' part... And I don't understand why (the alert() part is there just to check if it works or not). My guess was it would work asynchronously but it just doesn't. Can somebody explain to me why? And what should I change to make it async?
$(document).ready(function(){
var artistName = new Array();
var artistPlaycount = new Array();
$('#inputForm').submit(function(){
var userName = $('#username').attr('value');
var amount = $('#amount').attr('value');
userName = "someUsername";
$.ajax({
type: "POST",
url: "prepXML.php",
data: "method=getartists&user="+userName+"&amount="+amount,
dataType: "xml",
async:false,
success: function(xml){
var i = 0;
$("artist",xml).each(function(){
artistName[i] = $(this).find("name").text();
artistPlaycount[i] = $(this).find("playcount").text();
i++;
});
}
});
});
alert(artistName[2]); //or any other iteration number
});
thank you
To do this asynchronously you need to move the alert into the callback and remove the async option, like this:
$.ajax({
type: "POST",
url: "prepXML.php",
data: "method=getartists&user="+userName+"&amount="+amount,
dataType: "xml",
success: function(xml){
$("artist",xml).each(function(i){
artistName[i] = $(this).find("name").text();
artistPlaycount[i] = $(this).find("playcount").text();
});
alert(artistName[2]);
}
});
Otherwise that success function populating the array happens after the alert does...so what you want isn't quite there yet. Not until the request comes back from the server does the success handler execute.
Also, the first parameter to the .each() callback is the index, you can use it, no need to keep your own incrementing variable :)
It doesn't work because the callback is fired after the alert. Put the alert in the callback.
you need to move the alert into your success handler.
alert(artistName[2]); //or any other iteration number
should go right after you loop through the xml.
so you should have:
success: function(xml){
var i = 0;
$("artist",xml).each(function(){
artistName[i] = $(this).find("name").text();
artistPlaycount[i] = $(this).find("playcount").text();
i++;
});
alert(artistName[2]); //or any other iteration number
}

Categories