Ajax in for loop without jquery [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have a for loop that call a ajax method
function viderTableauConteneur()
{
var caf = document.getElementById('CAF').value;
var tabConteneurAjouter = caf.split("#");
for (var i = 0; i < tabConteneurAjouter.length; i++) {
if(!verifierConteneurAppartienClient(tabConteneurAjouter[i]));
removeConteneur(tabConteneurAjouter[i]);
};
}
function verifierConteneurAppartienClient(serialNumber)
{
var e = document.getElementById("id_client");
var idClient = e.options[e.selectedIndex].value;
var xhr = getXhr();
var res = 12;
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
if(xhr.responseText == "0")
return false;
else if(xhr.responseText == "1")
return true;
}
}
xhr.open("GET","index.php?option=com_tkcontrack&controller=facture&task=verifierConteneurAppartienClient&refConteneur="+serialNumber+"&id_client="+idClient,true);
xhr.send();
}
Well if I alert the xhr.responseText I got "1", but when I alert the result in the viderTableauConteneur method I always got "Undifined"
Any help please

You could modify your code this way :
function viderTableauConteneur()
{
var caf = document.getElementById('CAF').value;
var tabConteneurAjouter = caf.split("#");
for (var i = 0; i < tabConteneurAjouter.length; i++) {
verifierConteneurAppartienClient(tabConteneurAjouter[i],
function()
{
alert('true');
},
function()
{
alert('false');
removeConteneur(tabConteneurAjouter[i])
}
);
}
}
/* callbcakIfTrue and callbackIfFalse have to be 2 functions
that will be called respectiveley if the return of the
ajax call is true or false.
*/
function verifierConteneurAppartienClient(serialNumber, callbackIfTrue, callbackIfFalse)
{
var e = document.getElementById("id_client");
var idClient = e.options[e.selectedIndex].value;
var xhr = getXhr();
var res = 12;
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
if(xhr.responseText == "1")
callbackIfTrue();
else
callbackIfFalse();
}
}
xhr.open("GET","index.php?option=com_tkcontrack&controller=facture&task=verifierConteneurAppartienClient&refConteneur="+serialNumber+"&id_client="+idClient,true);
xhr.send();
}

Related

Can't set <p> text to a returned var [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have this code :
function getJSONVideoInformation(videoUrl, informationPath) {
var jsonPath = 'https://www.googleapis.com/youtube/v3/videos?key=' + googleAPIKey + '&part=snippet&id=' + getVideoId(videoUrl);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
var object = JSON.parse(xhr.responseText);
paths = informationPath.split('.'),
for (var i = 0, informationToReturn = object; informationToReturn && i < paths.length; i++) {
informationToReturn = informationToReturn[paths[i]];
}
console.log(informationToReturn);
return informationToReturn;
}
}
};
xhr.open('GET', jsonPath, true);
xhr.send();
}
var newP = document.createElement('p');
newP.innerHTML = getJSONVideoInformation(videoUrl, 'items.0.snippet.title');
My goal is to display newP with 'informationToReturn' as text.
When I execute the code everything seems to work, the console.log in the function shows the good value in the console (which is text) but newP only displays 'undefined'.
I can't figure out what's wrong :c
Thanks!
You shouldn't return from function that runs asynchronously. Replace the return statement with the last two lines of code.

Function won't return a value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I'm making a password generator. Trying to implement pass-phrases.
The function loadFile(); won't return a value to my main function, generate();
I think I'm too close to the problem and can't logic it out. I could use some help. Thank you.
Test site: https://jf0.000webhostapp.com/passWordGenerator/
test.js source: https://jf0.000webhostapp.com/passWordGenerator/test.js
The source is getting kind of long, sorry.
//Main generate password function
function generatePassword(){
var x = document.getElementById("passOutput");
var p = document.getElementById("testP");
x.value = generate();
//Make sure they aren't using an insecure number of characters
checkMaxChars();
p.innerText = x.value;
}
//Generate a password. 3 passSets for customization, one for passphrase
function generate(){
var nL = document.getElementById("noLetters");
var nN = document.getElementById("noNumbers");
var nS = document.getElementById("noSymbols");
var pPK = document.getElementById("passWordPhrase");
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var numbers = "0123456789";
var symbols = "!##$%^&*()_+~`|}{[]:;?,.-='";
var maxChars = document.getElementById("maxCharControl").value;
var generatedPass = "";
var holdPass = "";
//Main loop
for(var i = 0;i < maxChars;i++){
//Pick random value for each passSet
var passSet1 = chars.charAt(Math.random() * chars.length);
var passSet2 = numbers.charAt(Math.random() * numbers.length);
var passSet3 = symbols.charAt(Math.random() * symbols.length);
//if a checkbox is selected, clear out that value
if(nL.checked == true){passSet1 = "";}
if(nN.checked == true){passSet2 = "";}
if(nS.checked == true){passSet3 = "";}
//Randomly select a set to be added to holdPass, or not if it is empty.
var r = Math.floor((Math.random() * 4) + 1);
if(r == 1){if (passSet1 == ""){i--}else{holdPass += passSet1;}}
if(r == 2){if (passSet2 == ""){i--}else{holdPass += passSet2;}}
if(r == 3){if (passSet3 == ""){i--}else{holdPass += passSet3;}}
if(r == 4){
if(pPK.checked == true){
//get the value from loadFile(); and apply it to passSet4, add that to holdPass.
}}
}
generatedPass = holdPass;
console.log("Max Characters:" + maxChars);
console.log("passSet1:" + passSet1);
console.log("passSet2:" + passSet2);
console.log("passSet3:" + passSet3);
console.log("Iteration:" + i);
console.log("Random Position:" + r);
console.log("Password:" + holdPass + "::::" + holdPass.length);
//return password
return generatedPass;
}
//Make sure they didn't select all the checkboxes
function checkBoxes(){
var nL = document.getElementById("noLetters");
var nN = document.getElementById("noNumbers");
var nS = document.getElementById("noSymbols");
var pP = document.getElementById("passWordPhrase");
var nA = document.getElementById("noticeArea");
var nT = document.getElementById("noticeAreaText");
if(nL.checked == true && nN.checked == true && nS.checked == true){
nL.checked = false;
nN.checked = false;
nS.checked = false;
nA.style.display = "block";
nT.innerHTML = "You cannot select all checkboxes at once.";
window.setTimeout(hideNotice,5000);
}
else{
nA.style.display = "none";
nT.innerHTML = "";
}
}
//make sure the max characters is greater than 8
function checkMaxChars(){
var maxChars = document.getElementById("maxCharControl").value;
var nA = document.getElementById("noticeArea");
var nT = document.getElementById("noticeAreaText");
var x = document.getElementById("passOutput");
console.log(maxChars);
if (maxChars < 8){
x.value = "";
nA.style.display = "block";
nT.innerHTML = "You cannot generate a password less than 8 characters in length for security reasons.";
window.setTimeout(hideNotice,7000);
}
}
//hides the notice area div once the message is completed
function hideNotice(){
var nA = document.getElementById("noticeArea");
var nT = document.getElementById("noticeAreaText");
nA.style.display = "none";
nT.innerHTML = "";
}
//Load file
function loadFile() {
var xhttp = new XMLHttpRequest();
var x;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
x = this.responseText;
parseResponse(x);
}
}
xhttp.open("GET", "wordList.csv", true);
xhttp.send();
return x;
}
//Format response
function parseResponse(x){
console.log("MADE IT HERE!");
var dS,sV1,rPos;
dS = x.split(",");
for(var i =0;i < dS.length;i++){
sV1 = dS[i];
}
x = sV1;
}
The results of an AJAX request will never be available until after the function that initiated it completes. You are attempting to return x before at the end of the function that initiates the request, which is before the AJAX request has finished.
You need to move that line into your AJAX success handler.
function loadFile() {
var xhttp = new XMLHttpRequest();
var x;
// The onreadystatechange callback function will execute
// at some future point after loadFile has completed, so
// you can only gain access to the AJAX result from within
// that function.
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
x = this.responseText;
parseResponse(x);
return x;
}
}
xhttp.open("GET", "wordList.csv", true);
xhttp.send();
}
Your xhttp request is opened asynchronously with the true in xhttp.open("GET", "wordList.csv", true); so x is returned before a value is assigned to it.
Edit: said synchronously instead of asynchronously because I am dumb

Js code does not run sequentially due to asynchronous [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
EDIT: My js code involve asynchronous, so that it actually finishes the second alert() in the ready method before the init() finish executing. Any idea on how to make sure that my second alert() executes after the init()? Thank you in advance.
var notes = [];
$(document).ready(function() {
//var notes = [];
alert("before " + notes.length);
init();
alert("after " + notes.length)
//execute(notes, 0);
});
function init() {
loadJSON(function(response) {
// Parse JSON string into object
var actual_JSON = JSON.parse(response);
var len = actual_JSON.notes.length;
//alert("length is " + len);
for(var i = 0; i < 6; i++) {
notes.push(actual_JSON.notes[i]);
}
//alert("after for loop " + notes.length);
});
}
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'test.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
Use promise
var notes = [];
$(document).ready(function() {
alert("before " + notes.length);
init()
.then(function(){
alert("after " + notes.length)
})
.catch(function(err){
console.log('error in init()', err)
});
});
function init() {
return new Promise(function(resolve, reject) {
loadJSON(function(response) {
var actual_JSON = JSON.parse(response);
var len = actual_JSON.notes.length;
for(var i = 0; i < 6; i++) {
notes.push(actual_JSON.notes[i]);
}
resolve()
});
});
}
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'test.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);

(beginner javascript) get multiple text files xml request

Very grateful if someone can help me out with the syntax here- I am hoping to make several XML requests, each time getting a different text file. Here is the general structure of my code. How can I get each file in turn (f0, f1 and f2)?
window.onload = function(){
var f = (function(){
var xhr = [];
for (i = 0; i < 3; i++){
(function (i){
xhr[i] = new XMLHttpRequest();
f0 = "0.txt"
f1 = "1.txt"
f2 = "2.txt"
//??? xhr[i].open("GET", file i, true);
xhr[i].onreadystatechange = function () {
if (xhr[i].readyState == 4 && xhr[i].status == 200) {
//do stuff
}
};
xhr[i].send();
})(i);
}
})();
};
Simply put your filenames in an array.
window.onload = function(){
var f = (function(){
var xhr = [];
var files = ["f0.txt", "f1.txt", "f2.txt"];
for (i = 0; i < 3; i++){
(function (i){
xhr[i] = new XMLHttpRequest();
xhr[i].open("GET", files[i], true);
xhr[i].onreadystatechange = function () {
if (xhr[i].readyState == 4 && xhr[i].status == 200) {
//do stuff
}
};
xhr[i].send();
})(i);
}
})();
};
Something like this should work
// ...
for (i = 0; i < 3; i++){
(function (i){
xhr[i] = new XMLHttpRequest();
xhr[i].open('GET', i.toString() + '.txt'); // <-- this line
xhr[i].onreadystatechange = function () {
if (xhr[i].readyState == 4 && xhr[i].status == 200) {
// ....

Ajax without jQuery [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to make an ajax call without jquery?
I have code in js(Ajax) but I want to make it without Ajax(XMLHttpRequest)
$.ajax({
type:'POST',
data:'slug='+prize,
url:'/wybrana-nagroda/',
success:function(msg)
{
$('#whaiting').hide();
if(msg==='winner')
$(window.location).attr('href','/formularz');
}
});
How it should look?
function send(post, url) {
var client = new XMLHttpRequest();
client.open("POST", url);
client.send(message);
}
?
Thanks.
If you want it to be compatible on all browsers, you'll need to do something like the following:
function sendRequest(url,callback,postData) {
var req = createXMLHTTPObject();
if (!req) return;
var method = (postData) ? "POST" : "GET";
req.open(method,url,true);
req.setRequestHeader('User-Agent','XMLHTTP/1.0');
if (postData)
req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
req.onreadystatechange = function () {
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304) {
// alert('HTTP error ' + req.status);
return;
}
callback(req);
}
if (req.readyState == 4) return;
req.send(postData);
}
var XMLHttpFactories = [
function () {return new XMLHttpRequest()},
function () {return new ActiveXObject("Msxml2.XMLHTTP")},
function () {return new ActiveXObject("Msxml3.XMLHTTP")},
function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];
function createXMLHTTPObject() {
var xmlhttp = false;
for (var i=0;i<XMLHttpFactories.length;i++) {
try {
xmlhttp = XMLHttpFactories[i]();
}
catch (e) {
continue;
}
break;
}
return xmlhttp;
}
Credit: quirksmode

Categories

Resources