javascript code not executing in order [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
So I'm trying to fetch data from a server in json format.
with this code
for (var i = 0; i < hosts.length; i++) {
var tempUrl = url + hosts[i];
jQuery.ajax({
type : "GET",
dataType : "json",
username : "user",
password : "password",
url : url,
async : true,
success : function (data) {
//var obj = data.data.host.status;
//console.log(obj);
jsonHosts.push(data.data);
console.log("added data");
}
});
}
followed by this code block
for (var i = 0; i < jsonHosts.length; i++) {
console.log("dog");
console.log(jsonHosts[i].host.status);
document.getElementById('test').innerHTML += "<br>" + jsonHosts[i].host.status;
document.getElementById('test').innerHTML += '<br>Some new content!';
}
console.log("done");
problem is, my console will show "done" then "added data" and my webpage will be blank.
I've tried putting the first section in a function and trying to get my code to wait for the function to finish executing but to no avail.
anyway I can make this code execute in order/have the second block wait on the first block

Move below portion of code into success callback function
success : function (data) {
//var obj = data.data.host.status;
//console.log(obj);
jsonHosts.push(data.data);
for (var i = 0; i < jsonHosts.length; i++) {
console.log("dog");
console.log(jsonHosts[i].host.status);
document.getElementById('test').innerHTML += "<br>" + jsonHosts[i].host.status;
document.getElementById('test').innerHTML += '<br>Some new content!';
}
console.log("done");
}

The ajax is async so the success function runs after your loop. try this:
for (var i = 0; i < hosts.length; i++) {
var tempUrl = url + hosts[i];
jQuery.ajax({
type : "GET",
dataType : "json",
username : "user",
password : "password",
url : url,
async : true,
success : function (data) {
//var obj = data.data.host.status;
//console.log(obj);
console.log("done");
jsonHosts.push(data.data);
console.log("added data");
DataCame(jsonHosts);
}
});
}
function DataCame(jsonHosts){
for (var i = 0; i < jsonHosts.length; i++) {
console.log("dog");
console.log(jsonHosts[i].host.status);
document.getElementById('test').innerHTML += "<br>" + jsonHosts[i].host.status;
document.getElementById('test').innerHTML += '<br>Some new content!';
}
}

Related

How to pass json data store in the variable from one page to another page in javascript function? [duplicate]

This question already has answers here:
Share Json between html pages
(3 answers)
Closed 5 years ago.
I have stored JSON data response from server intooldJson variable. I want to pass this variable data to new page where another JS function is found.
Here is the first page code
$(document).ready(function(){
$("#submitform").click(function(e)
{
var MyForm = JSON.stringify($("#myform").serializeJSON());
console.log(MyForm);
$.ajax(
{
url : "http://localhost:8080/e-learner/v1/signIn",
type: "post",
headers: { 'Content-Type': 'application/json' },
data : MyForm,
success:function(data,status){
console.log(data);
if(data.status==1)
{
alert(data.errorMessage);//alert ur data here by checking data
}
else if(data.clientType == "Admin")
{
var oldJson = JSON.stringify(data);
console.log(oldJson);
$('#temp').data('oldJson', jData);
// alert("Your account created Successfully. Your Reference Key is"+data.referenceKey);
window.location.href = "Report.html"
//redirect code to dashboard page console.log(JSON.stringify(data));
}
else
{
window.location.href = "index.html"
}
},
error:function(err){
console.log(err);
alert(err.statusText);
}
});
});
});
</script>
Second page code
$.getJSON('jData', function(jsonData) in this function I want to pass oldJson data variable
<script>
$(document).ready(function () {
jData = $('#temp').data('oldJson');
$.getJSON('jData', function(jsonData) {
console.log(jsonData);
var s1=jsonData.data.student;
for (var i = 0; i < s1.length; i++) {
var counter = s1[i];
if(jsonData.status!="error")
{
tr = $('<tr/>');
tr.append("<td>" + counter.referencekey + "</td>");
tr.append("<td>" + counter.email + "</td>");
tr.append("<td>" + counter.clients+ "</td>");
$('table').append(tr);
}
else
{
alert(jsonData.message);
}
}
});
});
</script>
while redirecting use following code
else if(data.clientType == "Admin")
{
var oldJson = JSON.stringify(data);
window.location.href = "Report.html?data=" + oldJson;
}
for second page to get value
add following function
function getUrlVars (url) {
var vars = {};
url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) { vars[key] = value; });
return vars;
}
and then to get the old value, do following
var urlValues = getUrlVars(window.location.href);
var oldValue = JSON.parse(decodeURIComponent(vars.data));

Getting type error while using Ajax call in JavaScript/jQuery [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
I am getting the following error while extracting some value inside loop using jQuery. I am showing my error below.
Uncaught TypeError: Cannot read property 'no_of_optional' of undefined
I am providing my code below.
var data = $.param({
'op': 'setPollField',
'sid': id
});
$.ajax({
method: 'POST',
url: "dbcon/DBConnection.php",
data: data
}).done(function(msg) {
var qdata = JSON.parse(msg);
var get = $("#ques").val();
var cntr = 0;
for (var i = 1; i < get; i++) {
if (i != 0) {
$("#questions0").val(qdata[0].questions);
$('#noofoption0').val(qdata[0].no_of_optional);
var data = $.param({
'op': 'getOptional',
'id': qdata[0]['_id']['$id']
});
$.ajax({
method: 'POST',
url: "dbcon/DBConnection.php",
data: data
}).done(function(msg) {
var optdata = JSON.parse(msg);
var cnt = 0;
for (var j = 0; j < qdata[0].no_of_optional; j++) {
}
}
cnt++;
}
})
}
if (i == 1) {
$('#questions' + i).val(qdata[i].questions);
$('#noofoption' + i).val(qdata[i].no_of_optional);
var data = $.param({
'op': 'getOptional',
'id': qdata[i]['_id']['$id']
});
$.ajax({
method: 'POST',
url: "dbcon/DBConnection.php",
data: data
}).done(function(msg) {
var optdata = JSON.parse(msg);
var cnt = 0;
console.log('first question', qdata[i].no_of_optional);
for (var j = 0; j < qdata[i].no_of_optional; j++) {
}
})
}
}
})
I am getting error at this console.log('first question',qdata[i].no_of_optional); .Actually qdata is containing the two set of data(qdata[0],qdata[1]) but inside the second ajax call i is becoming 2.
Here I am expecting qdata[1].no_of_optiona inside second ajax call.
use a closure, by the time the done callback is called the for loop has finished and incremented i:-
var data = $.param({
'op': 'setPollField',
'sid': id
});
$.ajax({
method: 'POST',
url: "dbcon/DBConnection.php",
data: data
}).done(function(msg) {
var qdata = JSON.parse(msg);
var get = $("#ques").val();
var cntr = 0;
for (var i = 1; i < get; i++) {
if (i == 1) {
(function(i) {
$('#questions' + i).val(qdata[i].questions);
$('#noofoption' + i).val(qdata[i].no_of_optional);
var data = $.param({
'op': 'getOptional',
'id': qdata[i]['_id']['$id']
});
$.ajax({
method: 'POST',
url: "dbcon/DBConnection.php",
data: data
}).done(function(msg) {
var optdata = JSON.parse(msg);
var cnt = 0;
console.log('first question', qdata[i].no_of_optional);
for (var j = 0; j < qdata[i].no_of_optional; j++) {
}
})
})(i);
}
}
})

How to abort ajax request

In my below code if input search vale is empty and as well as search keyword is same means if entered 'abc' got the result again clicked need to abort the ajax request, I had written in beforesend method but browser throwing error "Cannot read property 'abort' of undefined"
Ajax code:
function makeRequest()
{
var searchText='';
var popupRequest = $.ajax({
url:"cnc/cncstorelocator",
type:'GET',
cache:false,
data: {searchCriteria : $('#cnc-searchcriteria').val()},
dataType: 'json',
beforeSend: function(){
if(searchText == '' && searchText == searchData) {
popupRequest.abort();
}
},
success : function(cncStoreLocatorData)
{
var store=null;
for (var i = 0; i < cncStoreLocatorData.length; i++) {
var loc = cncStoreLocatorData[i];
store = $('<div/>').addClass('pane');
var store_hours = loc.hrsOfOperation;
var str1 = $('<p/>').addClass('stores-timing');
var store_timings=null;
for (var j = 0; j < store_hours.length; j++) {
var storetime = store_hours[j];
store_timings = str1.append($('<span/>').html('<strong>' + storetime.days_short));
store_timings.appendTo(store);
}
$("#cncstorepane").append(store);
searchText=searchData;
}
},
error: function(cncStoreLocatorData) {
alert("can't make req");
}
});
}
var xhr = $.ajax({
type: "POST",
url: "XXX.php",
data: "name=marry&location=London",
success: function(msg){
alert( "The Data Saved: " + msg );
}
});
//kill the request
xhr.abort()
var xhr = null;
function makeRequest()
{
if( xhr != null ) {
xhr.abort();
xhr = null;
}
var searchText='';
xhr = $.ajax({
url:"cnc/cncstorelocator",
type:'GET',
cache:false,
data: {searchCriteria : $('#cnc-searchcriteria').val()},
dataType: 'json',
beforeSend: function(){
if(searchText == '' && searchText == searchData) {
xhr.abort();
}
},
success : function(cncStoreLocatorData)
{
var store=null;
for (var i = 0; i < cncStoreLocatorData.length; i++) {
var loc = cncStoreLocatorData[i];
store = $('<div/>').addClass('pane');
var store_hours = loc.hrsOfOperation;
var str1 = $('<p/>').addClass('stores-timing');
var store_timings=null;
for (var j = 0; j < store_hours.length; j++) {
var storetime = store_hours[j];
store_timings = str1.append($('<span/>').html('<strong>' + storetime.days_short));
store_timings.appendTo(store);
}
$("#cncstorepane").append(store);
searchText=searchData;
}
},
error: function(cncStoreLocatorData) {
alert("can't make req");
}
});
Define a variable and give your ajax the same alias. Then, everytime the function is being made, you check if (in this example XHR) is null or not. If it is not, you abort() it and give it null value again.

Url.Action error dont exist object

I have Script
$(function() {
$.support.cors = true;
jQuery.support.cors = true;
$.ajax({
crossDomain: true,
type: 'GET',
url: 'http://example.com/WCFRESTService.svc/GetCategories',
success: function(result) {
var s = '';
for (var i = 0; i < result.length; i++) {
s += '<br>' + result[i]["Name_Category"] + '';
$('#content').html(s);
}
}
});
});
The Url.Action Gives an error on result[i]["Categories_id"].
The name "result" does not exist int the current context
How do I transfer to my object result?
You can't pass JavaScript(Client Side) variable to Url.Action as it is processed at the Server-Side.
As a workaround, you can use placeholder to generate the url. Then use .replace() method to generate the actual url.
var s = '';
//Generate a variable with URL
var url = '#Url.Action("GetAnn", "Home", new { categories_id = -1})';
for (var i = 0; i < result.length; i++) {
s += '<br>' + result[i]["Name_Category"] + '';
$('#content').html(s);
}

Send back returned response to ajax call

I have a ajax function in index.php which calls on the page thread.php which returns a JSON response(array). I basically want to parse through that array, display it in a particular html format, take the last value of the last row of that array and send it back in the same ajax call previously mentioned. So that ajax is basically a loop.
function returnValue()
{
$.ajax({
async: true,
type: "GET",
url: "thread.php",
data: {lastposted : dateposted},
dataType: "json",
success: function (json) {
if(json) {
{
for (var i = 0, len = json.length; i < len; i++) {
var results = json[i];
var newDiv = $("<div><img src='" + results[0] +"'/>" + results[2] + results[3] + results[4] + results[5] + "</div><br>");
$('#chatContents').append(newDiv);
var dateposted = results[5];
}
}
}
}
});
}
The stored value dateposted needs to be sent as an input when making the ajax call. The default value of dateposted will be 0.
I am not sure if this can be done. I am open to suggestions.
You can make this a lot simpler, you don't need to use the extended GET syntax:
var returnValue = (function() {
var dateposted = 0;
return function() {
$.get("thread.php", { "lastposted": dateposted }, function(result) {
// display your chats
dateposted = result[result.length-1][5];
}, "json");
}
})();
One simple way to your problem is declaring dateposted with a default value outside the function call and use it in the loop to store to store the last value. And have a new Ajax function call. I hope this is want you want.
function returnValue()
{
var dateposted=0;
$.ajax({
async: true,
type: "GET",
url: "thread.php",
data: {lastposted : dateposted},
dataType: "json",
success: function (json) {
if(json) {
{
for (var i = 0, len = json.length; i < len; i++) {
var results = json[i];
var newDiv = $("<div><img src='" + results[0] +"'/>" + results[2] + results[3] + results[4] + results[5] + "</div><br>");
$('#chatContents').append(newDiv);
dateposted = results[5];
}
}
}
}
});
}

Categories

Resources