This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
I want to read the (images) files name inside a specific folder and then to preview images in Krajee Bootstrap FileInput (FileInput demo link) .
I have a problem with this code in javascript:
var initialPreviewArray = [];
var j = [];
$.ajax({
type: "POST",
url: "my_gallery_ajax.php?",
async: "FALSE",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// alert('ok');
$.each(data, function(i,filename) {
j[i] = filename;
initialPreviewArray.push("<img id='"+i+"' src='user_1/'"+j[i]+"'>");
});
alert(j[2]); // test - is working - value: '11.jpg'
}
});
alert(j[2]); // test - not working - value: 'undefined'
My goal is to fill 'initialPreviewArray' with data from AJAX, inside or outside.
Inside 'AJAX call' initialPreviewArray.push is not working, even with specific value (outside AJAX is working):
initialPreviewArray.push("<img style='height: 50px' id='1' src='user_1/1.jpg'>");
Conclusion: I am not able to get data outside AJAX.
Related
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 months ago.
I have the below java script function, the global variable description1 is updated in the nested JQuery, But when i try to display the variable or set the result as text for a label, it is not displayed. Kindly advice. Thanks in advance.
<script type="text/javascript">
var description1 = "";
function onSelect(e) {
var item = e.item;
var partcode = item.text();
$.ajax({
url: '#Url.Action("GetDescription", "Orderlist")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'id': partcode },
success: function (results) {
description1 = results;
},
error: function () {
alert('Error occured');
}
});
alert("DESC: " + description1)
document.getElementById("TechDescription").innerHTML = description1;
}
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
Sorry for the simple question, I am new to Javascript and Ajax.
Here is my code:
var rootURL = "http://localhost:8080/WineCellar/rest/wines";
var findById= function(id){
var testWine;
console.log('findById: ' + id);
$.ajax({
type: 'GET',
url: rootURL + '/' + id,
dataType: 'json',
success: function(data){
console.log('findById success: '+ data.name);
testWine = data;
}
});
return testWine;
};
var myWine = findById(3);
console.log(myWine.name);
It gives the following console output:
https://i.stack.imgur.com/JqmHQ.png
Cannot read property 'name' of undefined
myWine is undefined. How do I fix this? Is it possible there are two ways of overcoming this problem? Perhaps I need to add a parameter to the ajax method?
Perhaps you could try using the fetch API ( https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API ) heres an example
let YOUR_API = "https://swapi.dev/api/people/1/";
let cache;
window.onload = function () {
fetch(YOUR_API)
.then((response) => response.json())
.then((myJsonResponse) => {
cache = myJsonResponse;
console.log(cache);
// the rest of the code that runs on this response
});
};
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have function that is used from few different places in the system. All I need now is to return true or false depends if function completed successfully or not. here is example of what I have so far:
function userUnlock(userID){
var fnResult;
$.ajax({
type: 'POST',
url: 'Application.cfc?method=removeLock',
data: {'userID':userID},
dataType: 'json'
}).done(function(obj){
if(obj.STATUS == 200){
fnResult = true;
}else{
fnResult = false;
}
}).fail(function(jqXHR, textStatus, errorThrown){
alert("Error: "+errorThrown);
});
return fnResult;
}
Here is my onClick fucntion:
$("#unlockBtn").on("click", function(){
var userID = $.trim($("#userID").val());
if(userID){
console.log(userUnlock(userID));
$("#unlockBtn").prop("disabled",true);
$('#searchMsg').addClass("success").show().text("User is unlocked.").delay(3000).fadeOut('slow').queue(function(){
$(this).removeClass("success").dequeue();
$("#unlockBtn").css("display","none");
});
}else{
$('#searchMsg').addClass("error").show().text("Error.").delay(3000).fadeOut('slow').queue(function(){
$(this).removeClass("error").dequeue();
});
}
});
In my onClick function console.log() returns undefined. I'm not sure why that's the case since I have return the variable that is Boolean. Also I was wondering if there is a way to prevent multiple requests onClick. For example if user by accident clicked few times. One way is to set button attribute disabled and I'm doing that but I want to make sure that my function prevents multiple requests. if anyone can provide some example that would be great. Thank you.
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have an ajax call when my page loads, the result is a integer number that I need to save in a variable to use later with other jquery functions.
This is my code right now
$(document).ready(function() {
var ajaxResult = new Array();
$.ajax({
url: '<?php echo base_url(); ?>index.php/Po_general/obtenerIdConsecutivo',
method: 'GET',
success: function (returned) {
var returned = JSON.parse(returned);
var idPog = returned.idPog;
ajaxResult.push(idPog);
}
});
//This shows me the array in the console
console.log(ajaxResult);
//This shows undefined
console.log(ajaxResult[0]);
/*
* Additional jquery functions
*/
});
console.log(ajaxResult) shows me the array in the console
[]
0: 2
length: 1
But when I want to access ajaxResult[0] it shows as undefined.
Can you try with this -
$(document).ready(function() {
var ajaxResult = [];
$.ajax({
url: '<?php echo base_url(); ?>index.php/Po_general/obtenerIdConsecutivo',
method: 'GET',
success: function (returned) {
var returned = JSON.parse(returned);
var idPog = returned.idPog;
ajaxResult.push(idPog);
}
});
//This shows me the array in the console
console.log(ajaxResult);
//This shows undefined
console.log(ajaxResult[0]);
/*
* Additional jquery functions
*/
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
Im retriving data from my php and its working fine , the problem is that
var myData is getting cached and only updates if i refesh my page 2 times...
on my firebug i can see the post updates but when i `console.log(myData);the data is the old one ..until i refresh..
$.ajax({
url: "http://www.example.com/mobile_read.php", // path to remote script
dataType: "JSON",
type: 'post',
data:{
id : id,
eventos : eventos,
}, // data set to retrieve JSON
success: function (data) { // on success, do something...
// grabbing my JSON data and saving it
// to localStorage for future use.
localStorage.clear();
localStorage.setItem('myData1', JSON.stringify(data));
}
});
var myData = JSON.parse(localStorage.getItem('myData1'));
console.log(myData);
var arrayObjects = myData;
You're probably trying to set and read mydata before the request/response is complete. Instead, move that into your success callback.
$.ajax({
url: "http://www.example.com/mobile_read.php", // path to remote script
dataType: "JSON",
type: 'post',
data:{
id : id,
eventos : eventos,
}, // data set to retrieve JSON
success: function (data) { // on success, do something...
// grabbing my JSON data and saving it
// to localStorage for future use.
localStorage.clear();
localStorage.setItem('myData1', JSON.stringify(data));
var myData = JSON.parse(localStorage.getItem('myData1'));
console.log(myData);
var arrayObjects = myData;
}
});