Link to my codepen:https://codepen.io/Kibitz/pen/PKdLma?editors=1111.
I'm running an ajax call that gets information from Wikipedia for results. Upon succeeding I have a for loop that adds the results to an array.
Currently, I just have one innerHTML statement to try and modify a p tag that starts as the word placeholder.
Eventually, I want to show ten results. Currently, the innerHTML call isn't modifying the placeholder word.
This is a snippet of the ajax call:
$.ajax({
type: "GET",
dataType: 'jsonp',
data: {
format: 'json'
},
cache: false,
url: url,
async: false,
success: function (data) {
for (i = 0; i < 10; i++) {
res[i] = data[1][i];
}
console.log(res);
document.getElementById("results1").innerHTML = res[0];
},
error: function (errorMessage) {
console.log('here');
alert("error");
},
complete: function () {
console.log("complete");
}
});
Could you replace line
document.getElementById("results1").innerHTML =res[0];
with
document.getElementById("result1").innerHTML =res[0];
Related
So I have a function that executes an ajax call in a for loop. I need to callback another function when the entire for loop is done. Since the ajax calls are running asynchronously, I'm not able to call the next function once the for loop is done.
Here's my code:
for(let i=0; i< industryArray.length; i++){
$.ajax({
url: myurl + "_api/web/lists/GetByTitle('library')/items",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
RejectedSalesCount += data.d.results.length;
},
error: function (data) {
}
})
}
// Need to call myfunction() here
myfunction() is being called even before the ajax calls are executed. Thanks!
Set ajax asyc state false then it will work
this is a sample example to set ajax asyc false
$.ajax({
url : "/submit/checkuser/",
type : "get",
async: false,
success : function(userStatus) {
if (userStatus == 'Disabled') { // check if user if disabled
} else if (userStatus == 'Deleted') { // check if user if deleted
} else {
};
},
error: function() {
connectionError();
}
});
Right now it wait for the function to get executed and moved to the next line
var pendingRequests=0;
for(let i=0; i< industryArray.length; i++){
if (condition) {
pendingRequests++;
$.ajax({
url: myurl + "_api/web/lists/GetByTitle('library')/items",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
RejectedSalesCount += data.d.results.length;
pendingRequests--;
if(pendingRequests===0) {
otherFunction()
}
},
error: function (data) {
doSomethingWithError(data)
}
})
}
}
The alert at the start shows "undefined", why?
The alerts come in this order:
"success!"
"Data" (what it should be)
"undefined"
I read through multiple threads, the problem was always that ajax was asynchronous, so the data was not defined when it was accessed, but in my case the data is there, the alert in my function shows the data BEFORE the other alert where it is undefined!
Very grateful for any help!
I got this code
var data = getData("");
alert(data); <<<<<<< UNDEFINED
function getData(fileName) {
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
var arrData = processData(data);
alert("success!");
alert(arrData); <<<<< WORKS GREAT
return arrData;
},
});
}
function processData(data) {
var arrData = CSVToArray(data);
dimensions = arrData[0];
var objects = [];
objects[0] = dimensions;
for (var i = 1; i < arrData.length; i++){
objects[i] = new Object();
for (var j = 0; j < dimensions.length; j++){
objects[i][dimensions[j]] = arrData[i][j];
}
}
return objects;
}
To clarify, I know asynchronous is the way to go for user experience, but this page just has to show data from this call, so its okay for me to wait for it.
Your getData function doesn't return anything.
You need to return it from the function itself.
function getData(fileName) {
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
var arrData = processData(data);
alert("success!");
alert(arrData); <<<<< WORKS GREAT
return arrData;
},
});
}
^ This returns the data within getData. But getData doesn't do anything with it: such as returning it.
function getData(fileName) {
var ourData = "";
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
var arrData = processData(data);
ourData = arrData;
},
});
return ourData;
}
This returns the data from getData to whatever calls that function.
edit: also, don't use async:false. Your browser won't capture any events happening until that AJAX completes. The benefit of asynchronous JS is that...we can! And in this case should.
Preface: Don't use async: false. But answering the question:
getData doesn't return anything. You're doing a return from the success callback, but that returns something from the success callback, not getData.
To change it so getData returns something, you'd do this:
function getData(fileName) {
var arrData;
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
arrData = processData(data);
},
});
return arrData; // <=== Now `getData` returns something
}
But don't do that. Instead, embrace asynchronous programming and remove async: false. For instance, a callback:
function getData(fileName) {
$.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
callback(processData(data));
},
});
}
...called like this:
getData(function(data) {
alert(data);
});
...or a promise ($.ajax returns one, of sorts):
function getData(fileName) {
return $.ajax({
async:false,
type: "GET",
url: "breastCancer.csv",
dataType: "text",
success: function (data) {
callback(processData(data));
},
}).then(data) {
return processData(data); // <== Becomes the resolution value of `getData`'s promise
});
}
and then
getData().then(function(data) {
alert(data);
});
data is undefined because the function getData doesn't return anything. You should have a look at promises.
I've been searching my brains out but I can't seem to wrap my head around the little help I find.
I'm running a database that is being fed by data from another DB. The csv transport is handled by a third party server providing executable "flows" which compile and deliver the data.
I have a php script to handle the request (can't be done directly via Javascript because of the missing 'Access-Control-Allow-Origin' header). But this runs nicely. I can trigger the flow.
This is not the problem though.
What I want to do: trigger the flow #onClick of a button with something like this:
function trigger_func(flowID) {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID,
dataType: 'json',
success: function(result) {
var jsonResult = jQuery.parseJSON(result);
console.log(jsonResult.runID);
}
});
}
With the flowID and the resulting runID I want to check back like every second or so.
function check_status(flowID, runID) {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID+"&action=status&runId="+runID,
dataType: 'json',
success: function(result){...}
});
}
This will return the status / progress of the flow.
It will start for a few seconds with status==null, then go on to status=='running' and finally status=='success'.
I have gotten check_status() to run for i.e. 15 times with a setTimeout in a for loop within the success-function of trigger_func() and it works fine too.
But I cannot for the life of me figure out how I would link this stuff together to have it checking until status is 'success' and then stop checking, update page content and so on...
I have also fiddled with something like
trigger_func(id).done(function(result){
console.log(result);
});
This works too but still I can't think my way further to the checking every second until 'success'. I guess it comes down to getting the variable 'status' back into my loop so I can break it.
Maybe someone knows of a comprehensible example somewhere online...
You could do this:
function periodically_check_status_until_success(flowID, runID) {
setTimeout(function() {
$.ajax({
url: './ajaxPHP_handler.php',
data: { flowid: flowID, action: status, runId: runID },
dataType: 'json',
success: function(result){
if (result != 'success') {
periodically_check_status_until_success(flowID, runID);
}
}
});
}, 5000); // Five seconds
}
Note: You can use an object for the data option, rather than concatenate the string yourself.
So just keep calling it
var flowID, runID;
function trigger_func(flowID) {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID,
dataType: 'json',
success: function(result) {
var jsonResult = jQuery.parseJSON(result);
runID= jsonResult.runID;
check_status();
}
});
}
function check_status() {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID+"&action=status&runId="+runID,
dataType: 'json',
success: function(result){
if (result is not what you want) {
setTimeout(check_status,1000);
}
}
});
}
ajax are async so you have to manage by this via some 3rd party variable
Like Init with value 0
var _status = 0
than change it on your first call set it 1
function trigger_func(flowID) {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID,
dataType: 'json',
success: function(result) {
var jsonResult = jQuery.parseJSON(result);
console.log(jsonResult.runID);
check_status(flowID, runID);
}
});
}
function check_status(flowID, runID) {
$.ajax({
url: './ajaxPHP_handler.php',
data: "flowid="+flowID+"&action=status&runId="+runID,
dataType: 'json',
success: function(result){
//at end status=='success'.
if(status=='success'){
// end part
}else{// running
check_status(flowID, runID);
}
// clear timeout will stop that time interval after success
}
});
}
i have a problem with ajax post function. Ajax function doesn't working without alert message. If add alert message, div content will be refresh and working my code.
I have a mv3 application. And post form data to this javascript function. Like that:
function Add_Definition() {
var data = $.extend({ call: "Add_Definition", url: "/Definition/Definition", type: "post", dataType: "html", data: $("#definition_form").serialize() }, data);
Load(ajaxrequest(data));
}
function Load(val) {
if (val == true) {
var data = $.extend({ call: "Load", render: $("#render"), url: '#Url.Action("Definition", "Definition")', type: "get", dataType: "html", data: { "groupid": '#Request.QueryString["groupid"].ToString()'} }, data);
ajaxrequest(data);
}
}
My ajax javascript function is below.
function ajaxrequest(param) {
var result = true;
//alert("hi there");
$.ajax({
type: param.type,
url: param.url,
data: param.data,
dataType: param.dataType,
success: function (result) {
$(param.render).empty();
$(param.render).html(result);
result = true;
},
error: function (request, status, error) {
result= false;
}
});
return result; }
If remove // char from javascript code, it will not work, (need refresh page), if have a alert message, content will be refresh with load function.
How is error?
you can also direct call like
var divElem = $('#yourdivid').load('#Url.Action("Definition", "Definition")');
I have a global javascript array and i am able to call values from it at the beginning of the function but after that, when i alert leaders[i], it shows as undefined:
It appears the problem occurs when there are two ajax calls nested in each other, JS cannot seem to find the values in the array.
JS
function getLeaders(bool) {
var leaders = new Array();
leaders.push('444');
leaders.push('111');
$.ajax({
url: 'url',
crossDomain: true,
type: 'post',
data: {
'clubID': curClub
},
success: function (data) {
for (var i = 0; i < leaders.length; i++)
{
alert(leaders[i]); <===== working fine here
$.ajax({
url: 'someurl',
crossDomain: true,
type: 'post',
data: {
'id': leaders[i] <====== works here
},
success: function(data3) {
alert(leaders[i]); <======= undefined here
var json3 = jQuery.parseJSON(data3);
}
});
}
}
});
};
Since the call is asynchronous the value of i is more than likely leader.length by the time the call returns. So you are probably accessing an index that is out-of bounds.