Can't append items to array with ajax [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'm trying to append the link value of Instagram images into an array. The link values are showing up fine in the console but my array length is 0 after the ajax function. Also '0' shows up in the console before all the links.
I have an idea this problem is caused by ajax running asynchronously and so the rest of the js code is actually run before anything can be appended to $images, but I have no idea how to circumvent this. This is my code:
$liked = 'https://api.instagram.com/v1/users/self/media/liked?access_token=' + $access_token + '&COUNT=20';
$images = []
$.ajax({
type:'get',
dataType:'jsonp',
cache: false,
url: $liked,
success: function(data) {
for (var i = 0; i < data.data.length; i++) {
console.log(data.data[i].images.standard_resolution.url);
$images.push(data.data[i].images.standard_resolution.url);
}
}
});
console.log($images.length);

The console.log will run before the ajax call is ended; write your code or you console.log in your success function right after the end of the data loop.
Like:
$liked = 'https://api.instagram.com/v1/users/self/media/liked?access_token=' + $access_token + '&COUNT=20';
$images = []
$.ajax({
type:'get',
dataType:'jsonp',
cache: false,
url: $liked,
success: function(data) {
for (var i = 0; i < data.data.length; i++) {
console.log(data.data[i].images.standard_resolution.url);
$images.push(data.data[i].images.standard_resolution.url);
}
console.log($images.length); // here the array is filled with response data
}
});

Related

Update front after ajax request in for function

I have a project where I sent an array to a foreach in PHP and it worked, the question is that it took a long time and it showed timeout, I try to do that for from js and ajax so that it sends the request to PHP and returns, update the value of the registry and return to PHP, this to avoid this timeout error, but when doing the synchronous for, the PHP function works ok and return data, but does not update the front with the information.
I have tried with success and with .done and it doesn't work as I want.
for(var i = 0 ;i < ids.length; i++){
console.log(i+' '+ids[i]);
var parametros = {'val1' : ids[i]}
$.ajax({
data: parametros,
url: "{{path('enviar_fac')}}",
type: 'post',
async: false,
success: function(data){
alert("success: "+i);
document.getElementById("loading").style.display = "block";
document.getElementById("resultados").innerHTML = "id: "+i+" data: "+data;
}
});
}
thanks

Can't pass array through ajax [duplicate]

This question already has answers here:
Javascript POST not working - Sending Javascript array to PHP
(4 answers)
Closed 4 years ago.
Trying to have data passed to a php script so the said data can be added to the session.
The debug console log returns are the following:
the quant array is correct and typeof is object, the JSON.stringified data's type is string , lastly success from the ajax success.
In the PHP script var_dump return is NULL
$('#bigsubmit').click(function() {
var quant = [];
$('.input-number').each(function() {
var tmp = {};
tmp.id = this.id;
tmp.qu = $(this).val();
quant.push(tmp);
});
console.log(quant);
var data = JSON.stringify(quant);
console.log(typeof(data));
$.ajax({
type: "POST",
url: url,
data: {
data: data
},
success: function() {
console.log("success");
}
});
the php script (url var)
<?php
session_start();
$_SESSION['test'] = $_POST['data'];
var_dump($_SESSION['test']);
?>
Your success callback function isn't taking in a parameter, try changing to this,
success:function(data) {
console.log(data);
}

ajax not setting value on declared variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I have a problem with this javascript function. What I'm trying to do is, finding a specific "Material Description" using ajax call. When I try to console.log the ajax function, the data is showed up. But when I'm setting to an array, it won't set the array value and skipped. Using "async: false" give me this warning:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience.
without async will give me undefined result.
$('#iBarcode').keypress(function (keyPressed) {
if (keyPressed.which == 13) {
var barcode = $('#iBarcode').val()
var splitted = new Array()
var arrayCnt = -1;
for (var i = 0; i < barcode.length; i++) {
var flagStart;
if (barcode.charAt(i) == ')') {
flagStart = true
i += 1
arrayCnt += 1
splitted[arrayCnt] = ''
}
if (barcode.charAt(i) == ('(')) {
flagStart = false
}
if (flagStart == true) {
splitted[arrayCnt] = splitted[arrayCnt] + barcode.charAt(i)
}
}
console.log(setMatDesc(splitted[0])) //value showed here
splitted[arrayCnt + 1] = setMatDesc(splitted[0]) //value not showed here and skipped?
splitted[arrayCnt + 1] = currentDate
$('#iBarcode').val('').focus
console.log(splitted)
}
})
function setMatDesc(MatID) {
var result
$.ajax({
url: '#Url.Action("Get_MatDesc")',
type: 'GET',
async: false,
data: { MatID: MatID },
success: function (data) {
result=data
},
error: function (xhr) {
alert('error');
}
})
return result
}
I would appreciate the help, thanks.
You need to provide a call back function which will get executed after ajax call completes like:
function setMatDesc(MatID, calback) {
var result
$.ajax({
url: '#Url.Action("Get_MatDesc")',
type: 'GET',
async: false,
data: { MatID: MatID },
success: function (data) {
callback(data); // note this
},
error: function (xhr) {
alert('error');
}
});
}
and at calling end do like:
setMatDesc(splitted[0],function(result) {
splitted = result;
splitted[arrayCnt + 1];
splitted[arrayCnt + 1] = currentDate;
});
The code might not work as i have not tested but this is the way to return the data from a function doing ajax call as the ajax call executes asynchronously and the function executes the body before the ajax call completes back from the server.

jquery async:false won't work [duplicate]

This question already has answers here:
async-ajax call not working as expected
(2 answers)
Ajax synchronous requests
(1 answer)
Closed 8 years ago.
So, I have a list of imdb ids stored in the database. What I want to do is, iterate over these and query a web service provider, for example TMDB and get the movie thumbnail associated with that imdb id.
I have fetched the data from the database, and stored it in response.
<script>
var results_area = $(".results-area");
function render(response) {
var img_thumbnail = $(".img-thumbnail");
var quote= $(".quote");
results_area.empty();
for (var i = 0; i < response.d.length; i++) {
img_thumbnail.attr('src', getImageThumbnail(response.d[i].imdbId));
quote.text("Reviews:" + response.d[i].quote);
results_area.append(img_thumbail.clone(),quote.clone());
}
}
function getImageThumbnail(imdbId) {
$.ajax({
async: false,
url: "https://api.themoviedb.org/3/movie/" + imdbId + "?",
data: param,
dataType: 'jsonp',
success: function () {
}
});
}
</script>
Since my dataType is 'jsonp', async:false won't work. What is happening is since in my html img src="#", it stays the same after the for loop finishes.
Is there a better way to do this?

Array doesn't keep content, maybe something with declaration [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have an array declared in an else structure
var days = new Array();
$.ajax({
url: 'someurl',
dataType: 'jsonp',
success: processJSON
});
I process the data from the ajax call in the processJSON function
function processJSON(jsonData) {
var weather = jsonData.data.weather;
for(var key in weather) {
var day = weather[key];
days.push(new Array(day.tempMaxC, day.type));
}
}
I add some other arrays to the days-array.
If I check it in the console (in the processJSON-function), the length is three/
Then when I want to use the variable in some code under the the ajax-call, nothing works and when I check the length it's 0. I guess it's something with declaration?
Is your code under the Ajax call happening after the processJson function? The call to the ProcessJson function is asynchronous and happens only after the Ajax call finishes. However the code following it might happen before. So it might be a timing thing. If you need the array for any other processing you should have it in the callback or after you know the callback has been finished.
Put the declaration outside of the condition/else
var days = new Array();
if(...){
}else{
$.ajax
}
You need to wait until the XHR call has finished. It looks like you're using JQuery so check out their deferred docs (http://api.jquery.com/deferred.then).
You would end with something like this:
$.ajax({
url: 'someurl',
dataType: 'jsonp'
}).then(function( jsonData ) {
var weather = jsonData.data.weather;
for(var key in weather) {
var day = weather[key];
days.push(new Array(day.tempMaxC, day.type));
}
console.log( 'done!', days );
});

Categories