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

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
}

Related

show exact result for each div after success AJAX callback

I am struggling trying to get the corresponding result for each item after successful AJAX callback. I am able to get the results, but not individually in each div from the item when there is more than one, each item displayed is getting all the results in the div and not just the corresponding one.
var xhr = $.ajax({
type: "HEAD",
url: image,
success: function(){
$(".block .image-sze").append(xhr.getResponseHeader('Content-Length'));
}
});
Can someone help me to fix the above so it can show individual result for each item?
The selector $(".block .image-sze") is only selecting the first class with block, use $("*.block *.image-sze") instead!
The "*" selects all tag that has the same class!
Hope this help?
maybe you're looking for something like this?
var xhr = $.ajax({
type: 'POST',
dataType: 'json'
url: url,
success: function(json){
$('#image1').html(json['image1']);
$('#image2').html(json['image2']);
}
});
And you're calling from url with something like this
public function somefunction() {
$json = array();
$json['image1'] = 'image1';
$json['image2'] = 'image2';
echo json_encode($json);
}

Only run ajax again if last is fully loaded and success

I got a problem while scrolling down and load content into my page.
The ajax executions load too fast, so the second, third and so... does not get correct information from the first ajax call, which are loaded into the DOM.
How do I make it, so the script only run if last ajax call is done and a success.
It should skip every scrolling up and down until the last ajax call is done. And then the ajax is allow to be executed.
And then over and over again until there no more to load though ajax.
Here is my jQuery script.
<script type="text/javascript">
$(document).ready(function(){
$(window).scroll(function(){
if ($(window).scrollTop() <= $(".wrapper_ac").offset().top + $(".wrapper_ac").height()) {
$(document).ajaxStart(function () {
var ajaxURLvalue = '../../modules/language_text_loading/load_content.php';
var langID = 'x';
var onID = 'x';
var setLimit = 'x';
var setIn = 'after';
var theme = 'x';
var setInWhere = 'x';
var conID = 'x';
loadInstant(ajaxURLvalue, langID, onID, setLimit, setIn, theme, setInWhere, conID);
});
}
});
});
</script>
This is my function.
function loadInstant(ajaxURLvalue, langID, onID, setLimit, setIn, theme, setInWhere, conID) {
var temp_s = $(".ltlID:last").attr("id");
var split_ltlID = temp_s.split(':');
var ltlID = split_ltlID[0];
var acContentBoxID = split_ltlID[1];
var dataString = {
action: 'load',
last_ltlID: ltlID,
//sharedID:acContentBoxID_sharedID,
langID:langID,
setInWhere: setInWhere,
onID:onID,
theme:theme,
conID:conID
};
$.ajax({
type: "POST",
url: ajaxURLvalue,
data: dataString,
cache: false,
success: function(html){
$("#accordionContent"+acContentBoxID+":last").after(html);
});
};
Thank you for your help.
Well what I would do is store the ajax function into a global variable like this:
global_variable = $.ajax({
type: "POST",
url: ajaxURLvalue,
data: dataString,
cache: false,
success: function(html){
$("#accordionContent"+acContentBoxID+":last").after(html);
});
and before the ajax call check if the variable is tru like this:
if(global_variable){
return false;
}
this will stop any ajax call to be called before the one running is over. I hope it helps you!

Javascript function being called again while it is still running

I have a javascript function that is called when the user clicks on a button and performs an AJAX query that adds some data to my database. However, I've been getting complaints that a lot of data hasn't been getting through, and I've isolated the problem to be the time between clicks. When they wait long enough between clicks, the data always gets through, but if they don't wait long enough it's a crapshoot.
So I'm pretty much settled that the problem is that the javascript function is being called again while it is already running, which I shouldn't allow. Is there a way I can lock the user's browser at the beginning of the function and unlock it at the end after the AJAX? I know this may irritate my users, but I can't see any other solution.
It's not totally necessary, but here's what my javascript function looks like:
function addtolist(thisform, sdata)
{
var scntDiv = $('#p_data');
var request = $.ajax({ async: false, url: "php_addtolist.php", type: "POST", data: {data:sdata}, dataType: "html" });
request.done(function(msg) { outdata = parseInt(msg); });
$(outdata).appendTo(scntDiv);
}
You can disable the button when the function is called, then re-enable it with the complete callback:
function addtolist(thisform, sdata)
{
$('#submit_btn').prop('disabled', true);
var scntDiv = $('#p_data');
var request = $.ajax({
async: false,
url: "php_addtolist.php",
type: "POST",
data: {data:sdata}, dataType: "html" },
complete: function() { $('#submit_btn').prop('disabled', false); }
);
request.done(function(msg) { outdata = parseInt(msg); });
$(outdata).appendTo(scntDiv);
}
Basically it seems like the outdata is async. the following should resolve.
function addtolist(thisform, sdata)
{
var scntDiv = $('#p_data');
var request = $.ajax({ async: false, url: "php_addtolist.php", type: "POST", data: {data:sdata}, dataType: "html" });
request.done(function(msg) {
outdata = parseInt(msg);
$(outdata).appendTo(scntDiv);
});
}

Loading data into a field with jQuery AJAX

I have this code below which is called by running the getGrades function.
function getGrades(grading_company) {
// Set file to get results from..
var loadUrl = "ajax_files/get_grades.php";
// Set data string
var dataString = 'gc_id=' + grading_company;
// Set the callback function to run on success
var callback = showGradesBox;
// Run the AJAX request
runAjax(loadUrl, dataString, callback);
}
function showGradesBox(response) {
// Load data into grade field
// Hide condition fields
jQuery('#condition').hide();
jQuery('#condition_text').hide();
// Show grade fields
jQuery('#grade_wrapper').show();
jQuery('#grade_text_wrapper').show();
}
function runAjax(loadUrl, dataString, callback) {
jQuery.ajax({
type: 'GET',
url: loadUrl,
data: dataString,
dataType: 'html',
error: ajaxError,
success: function(response) {
callback(response);
}
});
}
Now as you can see I am passing the AJAX response data to the showGradesBox function; however I'm now not sure how to load it into the field.
I have seen example using .load() but it seems you have to use this with the URL all at once; the only other function I have come across that I could possibly use is .html(); but the description of it doesn't sound right!?
.html() should work ...
When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.
function showGradesBox(response) {
// Load data into grade field
jQuery('#yourgradefieldID').html(response);
// Hide condition fields
jQuery('#condition').hide();
jQuery('#condition_text').hide();
// Show grade fields
jQuery('#grade_wrapper').show();
jQuery('#grade_text_wrapper').show();
}
Assuming a field with ID grade_text and a return of a string from the PHP:
function showGradesBox(response) {
// Load data into grade field
jQuery('#grade_text').val(response);
// Hide condition fields
jQuery('#condition').hide();
jQuery('#condition_text').hide();
// Show grade fields
jQuery('#grade_wrapper').show();
jQuery('#grade_text_wrapper').show();
}
This assigns a value of 'undefined' to your callback.
// Set the callback function to run on success
var callback = showGradesBox;
Try assigning the function to a variable named showGradesBox before your functions like this
var showGradesBox = function(response) {
// Load data into grade field
// Hide condition fields
jQuery('#condition').hide();
jQuery('#condition_text').hide();
// Show grade fields
jQuery('#grade_wrapper').show();
jQuery('#grade_text_wrapper').show();
}
function getGrades(grading_company) {
// Set file to get results from..
var loadUrl = "ajax_files/get_grades.php";
// Set data string
var dataString = 'gc_id=' + grading_company;
// Set the callback function to run on success
var callback = showGradesBox;
// Run the AJAX request
runAjax(loadUrl, dataString, callback);
}
function runAjax(loadUrl, dataString, callback) {
jQuery.ajax({
type: 'GET',
url: loadUrl,
data: dataString,
dataType: 'html',
error: ajaxError,
success: function(response) {
callback(response);
}
});
}

How to bring ajax search onkeyup with jquery

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.

Categories