Run jquery ajax request when user finishes typing - php

I Am working on my project i have added feature for image search and i am having little trouble i have bounded min 2 characters when ajax fire but when i type more then 2 chars ajax run after every letter i don't want that to happen instead i want to run ajax only after when user finishes typing i found few questions related to this i have tried as much as i can but they did not helped me.
Update:-
And one more thing when user clears input box my loader is still there i want to hide loader if input is empty
My Jquery:-
$(function() {
var minlength = 2;
$("#image_query").keyup(function() {
$('#span_result').html('<div class="loader">Loading...</div>');
var that = this,
value = $(this).val();
if (value.length >= minlength) {
$.ajax({
type: "GET",
url: "image.php",
data: {
'image_query': value
},
dataType: "text",
success: function(html) {
if (value == $(that).val()) {
$("#span_result").html(html)
}
}
})
}
})
});
My HTML:-
<form method="get" action="">
<input type="text" id="image_query" placeholder="Search Here For Images">
<button type="submit">Go</button>

Although there are probably more optimal ways - I always find this the easiest and best ways. I think this is what you are looking for. Also please note the hide image should go in the ajax success callback.
var timeout = null;
var minlength = 2;
$("#image_query").keyup(function() {
$('#span_result').html('<div class="loader">Loading...</div>');
// clear last timeout check
clearTimeout(timeout);
var that = this;
var value = $(this).val();
if (value.length >= minlength) {
//
// run ajax call 1 second after user has stopped typing
//
timeout = setTimeout(function() {
$.ajax({
type: "GET",
url: "image.php",
data: {
'image_query': value
},
dataType: "text",
success: function(html) {
// hide image
$(#span_result .loader).hide();
if (value == $(that).val()) {
$("#span_result").html(html)
}
}
});
}, 1000);
});
});

I think, then you should use setTimeout() along with keyup event before sending the ajax request. The delay could be 2 or 3 seconds, as per your need.
Edit:
To clear the loader image, you can do following:
$(#span_result .loader).hide();
At the end inside AJAX response.

You could use the jQuery blur() method to capture when the user is finished with input. Then check for minlength inside the blur function before your ajax call.
You can find an example of blur in W3 schools here

Related

Issue with using a value in JQuery/Javascript

I have a PHP populated table from Mysql and I am using JQuery to listen if a button is clicked and if clicked it will grab notes on the associated name that they clicked. It all works wonderful, there is just one problem. Sometimes when you click it and the dialog(JQuery UI) window opens, there in the text area there is nothing. If you are to click it again it will pop back up. So it seems sometimes, maybe the value is getting thrown out? I am not to sure and could use a hand.
Code:
$(document).ready(function () {
$(".NotesAccessor").click(function () {
notes_name = $(this).parent().parent().find(".user_table");
run();
});
});
function run(){
var url = '/pcg/popups/grabnotes.php';
showUrlInDialog(url);
sendUserfNotes();
}
function showUrlInDialog(url)
{
var tag = $("#dialog-container");
$.ajax({
url: url,
success: function(data) {
tag.html(data).dialog
({
width: '100%',
modal: true
}).dialog('open');
}
});
}
function sendUserfNotes()
{
$.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data:
{
'nameNotes': notes_name.text()
},
success: function(response) {
$('#notes_msg').text(response.the_notes)
}
});
}
function getNewnotes(){
new_notes = $('#notes_msg').val();
update(new_notes);
}
// if user updates notes
function update(new_notes)
{
$.ajax({
type: "POST",
//dataType: "json",
url: '/pcg/popups/updateNotes.php',
data:
{
'nameNotes': notes_name.text(),
'newNotes': new_notes
},
success: function(response) {
alert("Notes Updated.");
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
});
}
/******is user closes notes ******/
function closeNotes()
{
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
Let me know if you need anything else!
UPDATE:
The basic layout is
<div>
<div>
other stuff...
the table
</div>
</div>
Assuming that #notes_msg is located in #dialog-container, you would have to make sure that the actions happen in the correct order.
The best way to do that, is to wait for both ajax calls to finish and continue then. You can do that using the promises / jqXHR objects that the ajax calls return, see this section of the manual.
You code would look something like (you'd have to test it...):
function run(){
var url = '/pcg/popups/grabnotes.php';
var tag = $("#dialog-container");
var promise1 = showUrlInDialog(url);
var promise2 = sendUserfNotes();
$.when(promise1, promise2).done(function(data1, data2) {
// do something with the data returned from both functions:
// check to see what data1 and data2 contain, possibly the content is found
// in data1[2].responseText and data2[2].responseText
// stuff from first ajax call
tag.html(data1).dialog({
width: '100%',
modal: true
}).dialog('open');
// stuff from second ajax call, will not fail because we just added the correct html
$('#notes_msg').text(data2.the_notes)
});
}
The functions you are calling, should just return the result of the ajax call and do not do anything else:
function showUrlInDialog(url)
{
return $.ajax({
url: url
});
}
function sendUserfNotes()
{
return $.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data: {
'nameNotes': notes_name.text()
}
});
}
It's hard to tell from this, especially without the mark up, but both showUrlInDialog and sendUserfNotes are asynchronous actions. If showUrlInDialog finished after sendUserfNotes, then showUrlInDialog overwrites the contents of the dialog container with the data returned. This may or may not overwrite what sendUserfNotes put inside #notes_msg - depending on how the markup is laid out. If that is the case, then it would explains why the notes sometimes do not appear, seemingly randomly. It's a race condition.
There are several ways you can chain your ajax calls to keep sendUserOfNotes() from completing before ShowUrlInDialog(). Try using .ajaxComplete()
jQuery.ajaxComplete
Another ajax chaining technique you can use is to put the next call in the return of the first. The following snippet should get you on track:
function ShowUrlInDialog(url){
$.get(url,function(data){
tag.html(data).dialog({width: '100%',modal: true}).dialog('open');
sendUserOfNotes();
});
}
function sendUserOfNotes(){
$.post('/pcg/popups/getNotes.php',{'nameNotes': notes_name.text()},function(response){
$('#notes_msg').text(response.the_notes)
},"json");
}
James has it right. ShowUrlInDialog() sets the dialog's html and sendUserOfNotes() changes an element's content within the dialog. Everytime sendUserOfNotes() comes back first ShowUrlInDialog() wipes out the notes. The promise example by jeroen should work too.

Get next set of data for jquery ajax autoscroll

I'm trying to set up a custom infinite scroll with jQuery and some Ajax. This is what I have so far:
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
$.ajax({
type: "POST",
url: "posts/view/",
data: "",
success: function(results){
$(".container").after(results);
}
})
}
});
It all works fine and dandy, but what I'm struggling to visualize is how to get the next "set" or, "page" of data. I'm using PHP and in my function I'll have something like getMore($page = 1). But how can I have jQuery keep track of what page it's currently on, and know which page is next? Should I set up some sort of increment function inside of jQuery so that it pulls the URL (e.g. posts/page/1/) and then simply add 1 to the url it passes via Ajax?
I feel like I'm really overthinking this, is there an easier way?
Just use a page counter inside the scroll closure:
(function(){
//inner functions will be aware of this
var currentPage = 0;
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
$.ajax({
type: "GET",
url: "posts/view/" + currentPage,
data: "",
success: function(results){
$(".container").after(results);
}
})
currentPage++;
}
});
})();​
And change your server script according to the page param you are passing.
If there is nothing more to retrieve, just answer with an empty body.
By the way, POST is not suitable for retreiving data, use GET instead.
You can go for simpler way.
Put one hidden field like this
<input type hidden value="1" id="page" />
now before every ajax send take the pagevalue from that hidden field. And after every ajax success function increment the hidden fierld value like this.
$('#page').val(parseInt($('#page').val())+1)
Your ajax call will look like this
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
$.ajax({
type: "POST",
url: "posts/view/"+$('#page').val(),
data: "",
success: function(results){
$('#page').val(parseInt($('#page').val())+1);
$(".container").after(results);
}
})
}
});

HTML : Enable Multiple Submission without refreshing

I want to enhance my tool's page where as soon use click a button. Request goes to server and depending upon return type (fail/pass) i change color of button. No Refresh/page reload
Page has multiple buttons : some what like below.
Name 9-11 - 11-2 2-5
Resource1 - Button - Button - Button
Resource2 - Button - Button - Button
Resource1 - Button - Button - Button
I am a c++ programmer so you might feel i asked a simple question
Here's a sample of jQuery Ajax posting a Form. Personally, I'm unfamiliar with PHP but Ajax is the same no matter what. You just need to post to something that can return Success = true or false. This POST happens asynchronously so you don't get a page refresh unless you do something specific in the success: section.
$("document").ready(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: yourUrlHere,
dataType: "json",
cache: false,
type: 'POST',
data: $(this).serialize(),
success: function (result) {
if(result.Success) {
// do nothing
}
}
});
}
return false;
});
});
Of course you don't have to be doing a POST either, it could be a GET
type: 'GET',
And if you don't need to pass any data just leave data: section out. But if you want to specify the data you can with data: { paramName: yourValue },
The cache: false, line can be left out if you want to cache the page. Seeing as how you aren't going to show any changes you can remove that line. jQuery appends a unique value to the Url so as to keep it from caching. Specifying type: "json", or whatever your specific type is, is always a good idea but not necessary.
Try using the $.post or $.get functions in jquery
$.post("url",$("#myform").serialize());
Adding a callback function as Fabrício Matté suggested
$.post("url",$("#myform").serialize(),function(data){alert(data);$("#myform").hide()//?Do something with the returned data here});
Here you go. You will find an example of a form, a button a the necessary ajax processing php page. Try it out and let us know how it goes:
<form action="" method="post" name="my_form" id="my_form">
<input type="submit" name="my_button" id="my_button" value="Submit">
</form>
<script type="text/javascript">
$("document").ready(function () {
$('#my_form').submit(function () {
$.ajax({
url: "ajaxpage.php",
dataType: "json",
type: "POST",
data: $(this).serialize(),
success: function (result)
{
//THere was an error
if(result.error)
{
//So apply 'red' color to button
$("#my_button").addClass('red');
}
else
{
//there was no error. So apply 'green' color
$("#my_button").addClass('green');
}
}
});
return false;
});
});
</script>
<?php
//ajaxpage.php
//Do your processing here
if ( $processed )
{
$error = false;
}
else
{
$error = true;
}
print json_encode(array('error' => $error));
die();
?>

Unresponsive Fade-In Fade-Out in Jquery

I am implementing a twitter-style follow/unfollow functionality with the following jquery.
$(function() {
$(".follow").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$("#loading").html('<img src="loader.gif" >');
$.ajax({
type: "POST",
url: "follow.php",
data: info,
success: function(){
$("#loading").ajaxComplete(function(){}).slideUp();
$('#follow'+I).fadeOut(200).hide();
$('#remove'+I).fadeIn(200).show();
}
});
return false;
});
});
I have a similar unfollow function. However i have the following problem:
When I have N items {1,2..i.N} each with id = followi and I click on the follow button. I find that some of the items respond while others do not. I suspect it is a pure javascript issue...otherwise i figure none of the buttons would respond at all.
Is it a timing issue...all help is appreciated. Also i'd appreciate it if you could point me to a simpler method.
Thanks!
Well you are doing the UI update in your ajax success handler, so the reaction time for the UI updated is based on the speed of the Ajax response. And if the server doesn't return successfully, the UI update won't happen at all.
A simpler method with instant response:
$(function() {
$(document.body).delegate(".follow","click",function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$("#loading").html('<img src="loader.gif"/>');
$('#follow'+I).fadeOut(200); // act instantly since we assume it will go well
$('#remove'+I).fadeIn(200); // act instantly since we assume it will go well
$.ajax({
type: "POST",
url: "follow.php",
data: info,
complete: function(){ //always remove the loader no matter if it goes well or not
$("#loading").slideUp();
},
error: function() {
//handle error
$('#follow'+I).fadeIn(200); // correct mistake
$('#remove'+I).fadeOut(200); // correct mistake
}
});
return false;
});
});

One function to load varrious php pages with jQuery and AJAX

I have the following code that i need some help with, i am trying achieve the same thing with jQuery. I have found some solutions that come close but as yet i am still searching for the perfect solution.
function getData(dataSource, divID)
{
if(XMLHttpRequestObject) {
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
Right now i am triggering the function with:
<input type = "button" value = "TEST" onclick = "getData('subject_selectAJAX.php?course_id=1', 'ajax')">
I would like to achieve the same thing with jQuery. I think the following function although wrong gets close, my problem is that the url changes depending on where the user is within the course. course_select.php is initially loaded into the #ajax div, which then would be replaced with subject_select.php?course_id="whatever" followed by topic_select.php?subject_id="whatever"
function getData() {
//generate the parameter for the php script
$.ajax({
url: "something.php", //i want this to be passed to the function
type: "GET",
data: data,
cache: false,
success: function (html) {
//add the content retrieved from ajax and put it in the #ajax div
$('#ajax').html(html);
//display the body with fadeIn transition
$('#ajax').fadeIn('slow');
}
});
}
I would love some help with this, i'm currently getting confused pretty sure it is something that would help other Ajax jQuery newbies.
This seems to work although i'm sure it could be much cleaner and i would still like to add some sort of loading graphic for slower connections.
<script type="text/javascript">
function getData( url, id ){
$.ajax({
type: "GET",
url: url,
data: "id=" + id,
cache: false,
success: function(html){
$('#ajax').hide();
//add the content retrieved from ajax and put it in the #content div
$('#ajax').html(html);
//display the body with fadeIn transition
$('#ajax').fadeIn('fast');
})
};
</script>

Categories