I've wrote following code for searching via ajax. When key up fired, an ajax request is made after 500ms. But the searching animation doesn't stop (hide() method).
$('#mainsearch .searchinput').keyup(function(e) {
if (e.which !== 0) {
var searchval = $(this).val().trim();
if(aSearch[searchval]) {
$('#mainsearch #sugbox #sugres').html(aSearch[searchval]);
}else if(prevs !== searchval) {
prevs = searchval;
clearTimeout($.data(this, 'timer'));
var wait = setTimeout(function() {search(searchval)}, 500);
$(this).data('timer', wait);
}
}
});
function search(searchval) {
console.log("searching for "+searchval)
if(lastrequest && lastrequest.readystate != 4){ // abort past requests
lastrequest.abort();
lastrequest = null;
delete lastrequest;
$('#mainsearch #finding').hide();
}
if(searchval != "") { // make an ajax call
lastrequest = $.ajax({
url:"/ajaxsearch.php?key_word="+searchval,
type: "GET",
dataType:'json',
cache:true,
beforeSend:function() {
$('#mainsearch #finding').delay(400).show(0);
},
complete: function(jqXHR, status){
console.log('complete');
$('#mainsearch #finding').hide();
},
success:function(result){
$('#mainsearch #finding').hide();
if(result.length > 0 ) {
var outp = searchParse(result);
$('#mainsearch #sugbox #sugres').html(outp);
aSearch[searchval] = outp;
} else
$('#mainsearch #sugbox #sugres').html('<li> Not Found </span></li>');
$('#mainsearch #finding').hide();
},
error : function (xhr, ajaxOptions, thrownError) {
$('#mainsearch #finding').hide();
}
});
}
}
I get desired results in search with no error. but the hide() isn't hiding the animation. However, entering $('#mainsearch #finding').hide(); hides the animation.
Note : Here #mainsearch #finding is a div which is animated by css3.
Take away the delay i think ajax returns faster than delay...
$('#mainsearch #finding').delay(400).show(0);
$('#mainsearch #finding').show(0);
Related
I have the following JavaScript function, which is executed when a button is clicked:
function calculate(resource) {
document.getElementById('loading-label').innerHTML = 'Calculating...';
$.ajax({
url: resource,
type: 'GET',
async: false,
headers: {
'Content-Type': 'application/json'
},
beforeSend: function () {
document.body.style.cursor('wait');
},
complete: function () {
document.body.style.cursor('default');
}
}).done(function (data, textStatus, jqXHR) {
if (data == true) {
document.getElementById('loading-label').innerHTML = 'Done!';
document.getElementById('loading-label').style.color = 'green';
} else {
document.getElementById('loading-label').innerHTML = 'Error!';
document.getElementById('loading-label').style.color = 'red';
}
});
}
But it doesn't work as I want. Maybe because I'm not using beforeSend and complete callbacks properly.
As it can be seen, when the button is clicked, a label changes its content and I would like to change the cursor to waiting until the synchronous call is finished (and then return to default). How could I do that?
You can't when you make a non-async request.
Aside from your trivial error (you need to assign new values to cursor with =, it isn't a function).
Synchronous requests block the event loop (which is why they are deprecated). Since the event loop is blocked, the browser doesn't perform a repaint, and the cursor doesn't change.
Write asynchronous code instead.
function calculate(resource) {
document.getElementById('loading-label').innerHTML = 'Calculating...';
document.body.style.cursor = 'wait';
$.ajax({
url: resource,
}).done(function (data, textStatus, jqXHR) {
if (data == true) {
document.getElementById('loading-label').innerHTML = 'Done!';
document.getElementById('loading-label').style.color = 'green';
document.body.style.cursor = 'default';
} else {
document.getElementById('loading-label').innerHTML = 'Error!';
document.getElementById('loading-label').style.color = 'red';
document.body.style.cursor = 'default';
}
});
}
I have auto scroll-er on my index page and also I have a search functionality on that page when I search for the record they give the result. When I scroll down the page a new record is added automatically. I want to disable the auto loader when I search the record that's it. Does anybody have an idea?
<script type="text/javascript" language="javascript">
$().ready(function () {
$("#hdnStudentCount").val(5);
});
function AddStudentRecord() {
$.ajax({
type: 'Get',
url: '/Home/getdeal',
data: {
lastdeal: parseInt($("#hdnStudentCount").val()) + 1,
},
async: false,
dataType: "html",
success: function (data) {
data = JSON.parse(data);
for (var i = 0; i < data.length; i++) {
if (data[i] != '') {
$("#studentTemplate").tmpl(data[i]).appendTo("#divMain");
var DealID = (data[i]["DealID"]);
$("#hdnStudentCount").val(parseInt(DealID));
$('div#last_msg_loader').html('<img src="/Images/ajax-loade.gif">');
}
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
AddStudentRecord();
}
});
$('#developer').click(function (e) {
// do something fancy
return false; // prevent default click action from happening!
e.preventDefault(); // same thing as above
});
</script>
If you are having a form for search so there might be some changes in url of page ie it might be changing url of page to something like
...../search?attr_name=value&.....
You can check if there is 'search' in 'window.location.href' like
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height() && (window.location.href.indexOf('/search') === -1)) {
AddStudentRecord();
}
});
Else
When your search request is sent then you can set some variable on window object like
window.isSearching = true
And you can check that variable in if condition like
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height() && (typeof(window.isSearching) === 'undefined')) {
AddStudentRecord();
}
});
I am using the following script with a contact form, however I need to have a small modification and can not figure out how to achieve this.
As it is at the moment the #note message slides open and stays open.First off all I will change the .slideUp to fadeIn, and then I would need to close the message after a couple a seconds, so I suppose I should to add .delay(2000).fadeOut() but I don't understand how to implement this changes. Thank you
The jQuery
var close_note = $("#note");
close_note.click(function () {
jQuery("#note").slideUp(1000, function () {
jQuery(this).hide();
});
});
$("#ajax-contact-form").submit(function() {
$('#load').append('<center><img src="images/ajax-loader.gif" alt="Currently Loading" id="loading" /></center>');
var fem = $(this).serialize(),
note = $('#note');
$.ajax({
type: "POST",
url: "contact.php",
data: fem,
success: function(msg) {
if ( note.height() ) {
note.slideUp(1000, function() {
$(this).hide();
});
}
else note.hide();
$('#loading').fadeOut(300, function() {
$(this).remove();
if(msg === 'OK') { $("#ajax-contact- form").find('input, textarea').val(""); }
// Message Sent? Show the 'Thank You' message and hide the form
result = (msg === 'OK') ? '<div class="success">Your message has been sent. Thank you!</div>' : msg;
var i = setInterval(function() {
if ( !note.is(':visible') ) {
note.html(result).slideDown(1000);
clearInterval(i);
}
}, 40);
}); // end loading image fadeOut
}
});
return false;
});
You can use something like this to do show the #note for a few seconds, then fade it out
$('#note').hide().html(msg).fadeIn(1000, function() {
$(this).delay(3000).fadeOut(1000);
});
So the code would look like
$("#ajax-contact-form").on('submit', function() {
$('#load').append('<center><img src="images/ajax-loader.gif" alt="Currently Loading" id="loading" /></center>');
$.ajax({
type: "POST",
url: "contact.php",
data: $(this).serialize()
}).done(function(msg) {
$('#loading').fadeOut(300, function() {
$(this).remove();
if(msg === 'OK') {
$("#ajax-contact-form").find('input, textarea').val("");
msg = '<div class="success">Your message has been sent. Thank you!</div>';
}
$('#note').hide().html(msg).fadeIn(1000, function() {
$(this).delay(3000).fadeOut(1000);
});
});
});
return false;
});
This is my code that I have built from several different pieces of information online:
http://jsfiddle.net/spadez/qKyNL/6/
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 5000,
beforeSend: function () {
// Fadeout the existing content
$('#content').fadeTo(500, 0.5);
},
success: function (data, textStatus) {
// TO DO: Load in new content
// Scroll to top
$('html, body').animate({
scrollTop: '0px'
}, 300);
// TO DO: Change URL
// TO DO: Set number as active class
},
error: function (x, t, m) {
if (t === "timeout") {
alert("Request timeout");
} else {
alert('Request error');
}
},
complete: function () {
// Fade in content
$('#content').fadeTo(500, 1);
},
});
My question is, how do I trigger the ajax request from clicking on one of the pagination list links (like 1 or 2) whilst using e.prevent default so it is degradable (it will still work if JavaScript is disabled). I guess what I am trying to do is the following in pseudo code:
Listen for a click of the pagination link
Grab the number of the link clicked (ie was 1 or 2 clicked)
try
$('a').click(function(){
var number = $(this).attr('href');//get the pg=1 value on the href
alert(number);
//ajax here
});
I'm not sure I completely understand your question, however something like this should work:
$(function() {
var clicks = {};
var sendAjax = function(href) {
//do something with href
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 5000,
beforeSend: function () {
// Fadeout the existing content
$('#content').fadeTo(500, 0.5);
},
success: function (data, textStatus) {
// TO DO: Load in new content
// Scroll to top
$('html, body').animate({
scrollTop: '0px'
}, 300);
// TO DO: Change URL
// TO DO: Set number as active class
},
error: function (x, t, m) {
if (t === "timeout") {
alert("Request timeout");
} else {
alert('Request error');
}
},
complete: function () {
// Fade in content
$('#content').fadeTo(500, 1);
},
});
};
$('a').click(function() {
var href = $(this).attr('href');
clicks[href] = clicks[href] ? clicks[href] + 1 : 1;
sendAjax(href);
return false; //disable the link
});
});
can't you just set an onclick on those link 1 and link 2?
ex:
link1.click(function() {
// do stuff with the ajax
});
Updated with latest code:
Here is the latest code, still has 2 buttons and 2 functions. Each button should run the relievant function and set the code to run the same button after every minute via the setInterval. For some reason, the very first setInterval always seems to stay set, even after clicking the second button which should change it. Not sure what I'm doing wrong:
$(document).ready(function() {
var myTimer = null;
get_popular();
clearInterval(myTimer);
myTimer = null;
myTimer = setInterval(function() {$('a.btnPopular').click();}, 60*1000);
$('a.btnPopular').click( function(event) {
event.preventDefault();
get_popular( $(this) );
clearInterval(myTimer);
myTimer = null;
myTimer = setInterval(function() {$('a.btnPopular').click();}, 60*1000);
});
function get_popular( that ) {
$.ajax({
url: 'get_popular.aspx?rand=' + Math.random(),
type: 'GET',
error: function(xhr, status, error) {
// error message here
},
success: function(results) {
if ( typeof that != "undefined" ) {
that.closest('.outer_div').find('.inner_div').empty().append( results );
} else {
$('.inner_div.new').empty().append( results ).removeClass('new');
}
}
});
}
$('a.btnLatest').click( function(event) {
event.preventDefault();
get_latest( $(this) );
clearInterval(myTimer);
myTimer = null;
myTimer = setInterval(function() {$('a.btnLatest').click();}, 60*1000);
});
function get_latest( that ) {
$.ajax({
url: 'get_latest.aspx?rand=' + Math.random(),
type: 'GET',
error: function(xhr, status, error) {
// error message here
},
success: function(results) {
if ( typeof that != "undefined" ) {
that.closest('.outer_div').find('.inner_div').empty().append( results );
} else {
$('.inner_div.new').empty().append( results ).removeClass('new');
}
}
});
}
});
Try:
setInterval(function() {$('a.btnPopular').click();}, 60*1000);
Edit:
Also you can't call get_popular(); without a parameter ;)
Edit 2:
This should solve your problems:
var myTimer = null;
$('a.btnPopular').click(function(event) {
event.preventDefault();
get_popular($(this));
clearTimeout(myTimer);
myTimer = setTimeout(function(){$('a.btnPopular').click();}, 60*1000);
});
$('a.btnLatest').click(function(event) {
event.preventDefault();
get_latest($(this));
clearTimeout(myTimer);
myTimer = setTimeout(function(){$('a.btnLatest').click();}, 60*1000);
});
setInterval(function() {$('a.btnPopular').trigger('click');}, 60*1000);
// Ad do this
$(elem).click(function(){}) => $(elem).on('click', function(){});