getJSON async with get - jquery - javascript

i have a getJSON very large, and while this load all data in the document, how i can do to read other getJSON data while this is yet loading?
the event in .on( is detected, but the getJSON not, is detected only when the another getJSON is loaded all
$.getJSON('./master-list.php?q=master', function(data) {
$.each(data, function(i, item) {
if(i >= 120)
return false;
addServer(item);
});
});
$(document).on('click', '.servergetid', function() {
console.log('Hey!');
$('#pd').html('');
$.ajax({
url: './data.php?ip=' + $(this).data('server') + '&data=l_by_id',
dataType: 'json',
type: 'GET',
async: true,
success: function(data) {
$.each(data.players, function(i, item) {
$('#pd').append('<tr><td>' + item.Nickname + '</td><td>' + item.Score + '</td></tr>');
});
}
});
});
function addServer(ip)
{
var response = false;
$.getJSON('./data.php?ip=' + ip + '&data=info', function(data)
{
response = addServerInfo(data, '[x]');
});
return response;
}

Forget it, the solution is change async: true to async: false, thanks.

Related

Fetching data from MSSQL

I got an interface that sends (FROMDATE and TODATE) to the MSSQl and retrieves the selected details and after receiving them the data is shown on the grid.
I'm using the MVC.
This is the js script that I'm using.
$('body').on('submit', '#form', function (e) {
e.preventDefault();
$('#btnSubmit').html('<i class="fa fa-refresh fa-spin" style="font-size:14px"></i> Please wait ....');
$('#btnSubmit').prop('disabled', true);
var fromdate = $('#PeriodFrom').val();
var todate = $('#PeriodTo').val();
if ($('#PeriodFrom').val() > $('#PeriodTo').val())
{
ToastMessage("To date cannot be less than From date ");
return false;
}
debugger;
$.ajax({
url: '/ReservationInquiries/ReservationInquery?fromdate=' + fromdate + '&todate=' + todate,
dataType: 'JSON',
method: 'GET',
beforeSend: function () {
$('#btnSubmit').html('<i class="fa fa-refresh fa-spin" style="font-size:14px"></i> Please wait ....');
$('#btnSubmit').prop('disabled', true);
},
complete: function () {
$('#btnSubmit').html('Save');
$('#btnSubmit').prop('disabled', false);
},
success: function () {
FillGrid();
},
error: function (xhr, status, error) {
console.log(error);
}
});
});
url: '/ReservationInquiries/ReservationInquery?fromdate=' + fromdate + '&todate=' + todate,
When the user picks the date range.By using the following URL it sends the Fromdate and Todate toward the controller then the Service and then the Entry.
It returns backs ReservationNo and Name from MSQL.
So according to my program, everything is fetched to the model (the values which is fetched from MSQL).
As you can see when it redirects back I'm calling a function called **FillGrid();**in my js.
function FillGrid() is the function that I'm using to draw the grid in the HTML.
Even the data is fetched nothing is displayed on my grid is this wrong?
can anyone help me?
function FillGrid() {
debugger;
if ($('#grid').length == 1) {
$('#grid tr').not(':first-child').remove();
$.ajax({
//url: '/ReservationInquiries/select?search=' + $('#txtSearch').val(),
//dataType: 'JSON',
beforeSend: function () {
$('.grid').hide();
$("#loadingProjects").show();
},
complete: function () {
ShowGrid();
$("#loadingProjects").hide();
},
method: 'POST',
success: function (data) {
debugger
//var inquirieslist = JSON.stringify(data.InqueryList)
$('#grid tr:not(:first)').empty();
if (inquirieslist != null) {
$.each(inquirieslist, function (index, item) {
$('<tr>' +
'<td>' + item.ReservationNo + '</td>' +
'<td>' + item.Name + '</td>' +
'</tr>').appendTo($('#grid'));
});
}
},
error: function (xhr, status, error) {
console.log(error);
}
});
}
}

Get the value of input tag for Ajax Request

<input type="text" id="autocomplete">
<ul></ul>
<script>
var value;
var wikiapi;
$('#autocomplete').on('keypress',function(e){
if(e.which==13){
value=$(this).val();
wikiapi="https://en.wikipedia.org/w/api.php?action=query&prop=iwlinks&iwprop=url&titles="+value+"&format=json";
$.ajax({
url:wikiapi,
crossDomain:true,
dataType:"jsonp",
xhrFields: {
withCredentials: true
},
success: function(data){
var links=data.query.pages[171166].iwlinks;
var title=data.query.pages[171166].title;
$.each(links,function(i,val){
$('ul').append('<li><a href='+val.url+'>'+title +'</a></li>');
});
console.log(data.query.pages[171166].iwlinks[0].url);
}
});
}
});
</script>
Hi, I am trying to retrieve the value from input tag. But It seems the method I've tried is not working. The value is not passed to the wikiapi var at all. Hence the ajax request cannot proceed. Can anyone point out the problem please.
I've also tried "..$('#autocomplete').on('click',function(){
........} also but not working.
I did a quick check inside the success function as to what data was storing. After just a couple of examples I noticed the key (the six digits) were different for each example. Therefore, var links=data.query.pages[171166].iwlinks; and var title=data.query.pages[171166].title; will only work for test. In order to get the keys of data.query.pages you need a for loop. I've also added $('ul').empty() to empty out whatever was in the list. Here's the code needed to get it to work:
var value;
var wikiapi;
$('#autocomplete').on('keypress', function(e) {
if (e.which == 13) {
value = $(this).val();
wikiapi = "https://en.wikipedia.org/w/api.php?action=query&prop=iwlinks&iwprop=url&titles=" + value + "&format=json";
$.ajax({
url: wikiapi,
crossDomain: true,
dataType: "jsonp",
xhrFields: {
withCredentials: true
},
success: function(data) {
$('ul').empty();
for (var key in data.query.pages) {
if (data.query.pages.hasOwnProperty(key)) {
var links = data.query.pages[key].iwlinks;
var title = data.query.pages[key].title;
}
}
$.each(links, function(i, val) {
$('ul').append('<li><a href=' + val.url + '>' + title + '</a></li>');
});
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="autocomplete">
<ul>
</ul>
When I paste your code to jsfiddle with this success function success: function(data){ console.log(data) } the ajax call works fine.
So you have an Problem to handle your result from the API.
I have rewritten your code to make it more readable:
$(document).on('keypress', '#autocomplete', function (e) {
if (e.which === 13) {
var options = {
url: "https://en.wikipedia.org/w/api.php",
data: {
action: "query",
prop: "iwlinks",
iwprop: "url",
titles: $(this).val(),
format: "json"
},
crossDomain: true,
dataType: "jsonp",
xhrFields: {
withCredentials: true
}
};
$.ajax( options ).done(function (data) {
var html ='';
$.each(data.query.pages, function(pageKey, pageValue) {
$.each(pageValue.iwlinks, function(linkKey, linkValue) {
html += '<li>' + pageValue.title + '</li>';
});
});
$('ul').html(html);
}).fail(function (err) {
console.log(err);
alert('Ooops');
});
}
});
I have extracted the ajax options and added the GET parameter from the URL to them. I also iterate over result pages and the link object to generate the listitems.
Here can you read about the jQuery ajax method and the options: https://api.jquery.com/jQuery.ajax/

Pushing to an array out of jQuery each loop and jQuery ajax call

I want loop a array if is result, push this result into a javascript array and i get it out of each loop and ajax call. How is it?
I tried to like this:
var ides = ["2254365", "2255017", "2254288", "2220745", "2254452", "2255239", "2232426", "2255143", "2248513", "2254295", "2233629", "2238651", "2254901", "2238430", "2239471", "2255294", "2217888", "2242302", "2242310", "2220380", "56121236", "2255244", "2235716", "2246897"];
var iArray = [];
$.each(ides, function(index, woide) {
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20=%20" + woide + "&format=json",
dataType: 'json',
success: function(data) {
if (data.query.results != null) {
iArray.push(woide+': '+data.query.results.channel.item.condition.code);
}
}
})
})
console.log(iArray); //this don't work
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Your ajax calls are asynchronous so it would take some time to fill the array of your choice. But before ajax completes and each loop finished with its iterations your log call fires.
At this point ajax is still is in process.
You have to move the log inside success handler of the ajax:
var ides = ["2254365", "2255017", "2254288", "2220745", "2254452", "2255239", "2232426", "2255143", "2248513", "2254295", "2233629", "2238651", "2254901", "2238430", "2239471", "2255294", "2217888", "2242302", "2242310", "2220380", "56121236", "2255244", "2235716", "2246897"];
var iArray = [];
$.each(ides, function(index, woide) {
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20=%20" + woide + "&format=json",
dataType: 'json',
success: function(data) {
if (data.query.results != null) {
iArray.push(woide + ': ' + data.query.results.channel.item.condition.code);
}
if (index === ides.length - 1) {
console.log(JSON.stringify(iArray, 0, 0)); // <-----move it here.
}
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try to store promises returned by the Ajax call then later you call in separate loop
var ides = ["2254365", "2255017", "2254288", "2220745", "2254452", "2255239", "2232426", "2255143", "2248513", "2254295", "2233629", "2238651", "2254901", "2238430", "2239471", "2255294", "2217888", "2242302", "2242310", "2220380", "56121236", "2255244", "2235716", "2246897"];
var pArray = [];
var iArray = [];
$.each(ides, function(index, woide) {
var promis = $.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20=%20" + woide + "&format=json",
dataType: 'json',
});
pArray.push(promis);
})
$.each(pArray, function(index,prom){
prom.done(function(data){
if (data.query.results != null) {
iArray.push(data.query.results.channel.item.condition.code);
}
});
});

Variable not accesable in ajax response

I'm having troubles using a global variable in my ajax response.
LastDate is a variable defined in the page I loaded into my second page. (function load_table)
I am able to acces the variable before the ajax call, but I can't seem to acces it in my ajax succes. because it gives undefined. <==== in code
my code:
var dia_date = {};
$(window).load(function()
{
DP("eerste keer")
load_table();
} );
function load_table()
{
DP('load_table');
$.ajax({
type: "POST",
url: "/diagnose_hoofdpagina/table_diagnose/" + DosierID,
success: function (data) {
$("#diagnoses_zelf").html('');
$("#diagnoses_zelf").append(data).trigger('create');
//initialize_table();
update_table();
},
error: function(){
alert('error');
}
});
return false;
}
function update_table()
{
if(LastDate > Datum)
{
alert("LasteDate" + LasteDate);
}
else
{
alert("Datum" + Datum);
}
alert('gast .... ' + LastDate); // <========== this is promted on the screen so there is no problem
$.ajax({
type: "POST",
url: "/refresh_diagnose/" + DosierID,
dataType: "json",
data : JSON.stringify(dia_date),
success: function (data) {
var DataDate = new Date(data.Year, data.Month, data.Day, data.Hour, data.Minute, data.Second);
alert('lastdate :'+ LastDate + 'date.date :' + DataDate);
//<============ BUT HERE HE GIVES LastDate AS UNDEFINED
},
error: function(data){
alert(data);
}
});
return false;
}
I can't see what I'm doing wrong. Can annyone help me plaese ? Thanks in advance.
You can try making a function.
var lastDate = #;
function getLastDate(){return lastDate;}
ajax.blablabla.success :{getLastDate();}

updating to separate DIVs via ajax

I have 2 elements on my page that I am trying to reload via ajax - however I can only ever seem to update one. Below is my code,
$('#messages_send').live('click', function() {
$.ajax({
url: base_url + 'ajax/send_message',
data: {
username: $('#messages_username').val(),
message: $('#messages_message').val(),
saveid: $('#messages_savedid').val(),
},
success: function(data) {
sending_message();
var x = jQuery.parseJSON(data);
if(x) {
if(x.gp_id==80)
{
$('#spn_ucredit').load(base_url + 'ajax/userdata/credits');
$('#overlay_credits').load(base_url + 'ajax/userdata/credits');
}
}
//$('#spn_ucredit').html($('#ncd_id').val());
//tmp_cost = $('#spn_ucredit').html()-$('#ncd_id').val();
//$('#ncd_id').val($('#ncd_id').val()-tmp_cost);
//alert(data);
setTimeout(message_sent, 2000);
setTimeout(remove_modal_box, 3000);
setTimeout(message_revert, 3500);
$("#saved_messages").load(base_url + 'messages #saved_messages > form');
$("#messages_content").load(base_url + 'messages #messages_content > form');
}
});
return false;
});
Am I doing something wrong?
sico,
There's a number of things you can do to debug/improve the code, chief amongst which is to reduce the number of HTTP requests. With $.get() instead of .load(), it should be possible to use the HTTP responses twice each.
Something like this :
$(document).on('click', '#messages_send', function() {
sending_message();
$.ajax({
url: base_url + 'ajax/send_message',
data: {
username: $('#messages_username').val(),
message: $('#messages_message').val(),
saveid: $('#messages_savedid').val(),
},
dataType: 'json',
success: function(data) {
var creditsPromise, messagesPromise;//vars that allow .when() later.
if(data.gp_id == 80) {
creditsPromise = $.get(base_url + 'ajax/userdata/credits', function(data) {
$('spn_ucredit').html(data);
$('#overlay_credits').html(data);
});
}
else {
creditsPromise = (new $.Deferred()).resolve().promise();
}
messagesPromise = $.get(base_url + 'messages', function(data) {
var $data = $(data);
$("#saved_messages").empty().append($data.find('#saved_messages > form'));
$("#messages_content").empty().append($data.find('#messages_content > form'));
});
$.when(creditsPromise, messagesPromise).done(function() {//fires when both $.get()s have successfully responded
message_sent();
setTimeout(remove_modal_box, 1000);
setTimeout(message_revert, 1500);
});
}
});
return false;
});
This reduces the number of HTTP requests from five to three.
You could further reduce the number of HTTP requests to one, though you would need to write a server-side script to perform everything currently performed by ...ajax/send_message, ...ajax/userdata/credits and ...messages, and json-encode a composite response.
The client-side code could then simplify to something like this:
$(document).on('click', '#messages_send', function() {
sending_message();
$.ajax({
url: base_url + 'ajax/send_message',
data: $("#messages form").serialize(),//assumed
dataType: 'json',
success: function(data) {
if(data.gp_id == 80) {
$('#spn_ucredit').html(data.credits);
$('#overlay_credits').html(data.credits);
}
$("#saved_messages").html(data.saved_messages);
$("#messages_content").html(data.messages_content);
message_sent();
setTimeout(remove_modal_box, 1000);
setTimeout(message_revert, 1500);
}
});
return false;
});

Categories