Synchronous POSTing to SQL handle using AJAX [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I wish to make a synchronous call to a page that handles SQL insert of the words I'm posting. However since I have many chunks and SQL is not asynchronous I wish to process each ajax call/chunk after another
for (chunk = 1; chunk <= totalchunks; chunk++) {
$.ajax({
type: "POST",
dataType: "json",
url: "updateHandle.php",
data: {words:arr.slice(1000*(chunk-1),1000*chunk),push:getpush},
success: function(){
console.log('Items added');
},
error: function(){
console.log('Errors happened');
}
});
}
the
async: false,
does not work for some reason. Each ajax call always goes to the error case and not the success case. So is there another solution to this issue that I've overlooked?
I thought about using a busy-waiting while-loop and use locks, but the setTimeout() function does not work as expected (probably some error on my part)
EDIT: The chunks are too big for one AJAX call hence serialization is needed. Also the amount of chunks may change from call to call, so flexibility is needed.

How about something like:
function insertWords(words){
if(words.length) {
$.ajax({
type: "POST",
dataType: "json",
url: "updateHandle.php",
data: {
words: words.splice(0, 1000),
push: getpush
},
success: function(){
console.log('1000 items added');
insertWords(words);
},
error: function(){
console.log('Errors happened');
return;
}
});
} else {
console.log("Done inserting all words.")
}
}
You can use a callback as a param of insertWords or return a promise to make it even more resilient.

Related

How to get Variable to equal results from function with AJAX [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I'm trying to set a variable from a ajax call that runs a function. The code below returns imgurlthumbvar in the console log put the alert(test) says it's undefined. I did some research and found out that the it has something to do with AJAX being asynchronous. Could anyone please help. Thanks in advance!
function displayimg(id2){
$.ajax({
url:'getphotos.php',
type:'POST',
dataType: "JSON",
data:{id2:id2},
success: function(result){
$.each(result, function(){
imgurlvar = this.imgurl;
imgurlthumbvar = this.imgurlthumb;
console.log(imgurlthumbvar)
//console.log('test')
return imgurlthumbvar
})
}
});
}
$('#test123').click(function(){
var test = displayimg(7)
alert(test)
})
Try
function displayimg(id2) {
return $.ajax({
url: 'getphotos.php',
type: 'POST',
dataType: "JSON",
data: {
id2: id2
}
});
}
// AJAX returns a promise
$('#test123').click(async function(){
var result = await displayimg(7); // result is AJAX response
var test;
$.each(result, function(){
imgurlvar = this.imgurl;
imgurlthumbvar = this.imgurlthumb;
console.log(imgurlthumbvar)
//console.log('test')
test = imgurlthumbvar
})
alert(test)
});
await makes an asynchronus call look and behave like synchronous but without actually making it synchronous (sync. calls are discouraged due to UI freezing issue

Javascript global variables not updating properly [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I need lines to be a global array but when I use console.log to compare values inside the function and outside the function, the inside one works fine but the outside one remains empty. Am I missing something here?
var lines = new Array();
$.ajax({
type: "GET",
url: "posts_replied_to.txt",
success: function(content) {
console.log("success");
lines = content.split('\n');
console.log(lines);
},
error: function() {
console.log("error");
}
});
console.log(lines);
The problem here is not regarding global variables. Its the asynchronicity problem.By the time the console.log() outside your ajax request is called, the ajax success callback is not called.Thats why you won't get the right value.
async function doAjax() {
return await $.ajax({
type: "GET",
url: "posts_replied_to.txt"
});
}
let lines = await doAjax()
lines = content.split('\n')
console.log(lines)
Try this code using
Async to get the expected result.
Yes,AJAX is asynchronous function.So, in outside 'console.log(lines)' command run before AJAX.
You can AJAX asyn:false
What does "async: false" do in jQuery.ajax()?
Before your GET response come your second console.log code also execute due to ajax is not async. Change as below,
var lines = new Array();
$.ajax({
type: "GET",
url: "posts_replied_to.txt",
async: false,
success: function(content) {
console.log("success");
lines = content.split('\n');
console.log(lines);
},
error: function() {
console.log("error");
}
});
console.log(lines);
Try using promise object returned by ajax call.
var lines = new Array();
var promise_obj = $.ajax({
type: "GET",
url: "posts_replied_to.txt"
}).promise();
promise_obj.done(function(response)
{
lines = response.split('\n');
console.log(lines);
// Rest of your logic goes here where you want to use lines.
});

JS Array values become undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have a function that pull information from an XML file located on the system. IT will then pull the values located in that file and put them into an array. Once the function is called the values enter the array, but then onnce the function ends the values go away.
function getXML(location,day){
$(document).ready(function () {
$.ajax({
type:'post', //just for ECHO
dataType: "xml", // type of file you are trying to read
crossDomain:true,
url: './../CurrentFiles/'+ location +'.xml', // name of file you want to parse
success: function (xmldata){
if(array[0] == null){
$(xmldata).find('dgauges').children().each(function(){
array.push($(this).text());
});
}
}, // name of the function to call upon success
error: function(xhr, status, error) {
console.log(error);
console.log(status);
}
});
});
return array[day];
}
From what I researched it could be a problem with async, but I do not understand entirely what that is.
Also I am very new to jquery so if there is any thing that seems out of place that's why.
THis is what my plan is for this function
I have an XML file formatted like
<dgages><d>26.850</d><d-1>7.70</d-1><d-2>2.00</d-2><d-3>27.90</d-3></dgages>
I am trying to pull all of those values in an array so I can do some calculations on them.
Get the XML Document
find all the children of dgage
put each of the children into the array
4 once the array is filled return the associated day.
Try making a synchronous call instead. AJAX calls are async by default, which means that code will jump to the next line before waiting for the result of the previous line. You can enforce the result by telling the AJAX call to do it synchoronously:
function getXML(location, day) {
var array = [];
$.ajax({
type: 'post', //just for ECHO
dataType: "xml", // type of file you are trying to read
crossDomain: true,
async: false, // Wait until AJAX call is completed
url: './../CurrentFiles/' + location + '.xml', // name of file you want to parse
success: function(xmldata) {
if (array[0] == null) {
$(xmldata).find('dgauges').children().each(function() {
array.push($(this).text());
});
}
}, // name of the function to call upon success
error: function(xhr, status, error) {
console.log(error);
console.log(status);
}
});
return array[day];
}

Ajax global variables or synchronous AJAX [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I want to get data from another page using AJAX. I also want to wrap this AJAX call into my "user defined function".
But I can not write like this:
function func(){
var tmp;
$.ajax({
url: 'url',
type: "POST",
dataType: "json",
success: function (data) {
tmp=data;
}
});
return tmp;
}
because AJAX is asynchronous and this code returns - "undefined".
When AJAX async param set to false
var tmp=$.ajax({...});
possible do the trick.
I also can create some global variables and write like this:
function setMyVariable(){
$.ajax({
...
success: function (data) {
myGlobalVariable=data;
}
});
}
The question is - Is it good practice to use global variables in this case?
Or it is completely wrong and I need search something else
The best practice would be to return the promise from $.ajax:
function func(){
var tmp;
return $.ajax({
url: 'url',
type: "POST",
dataType: "json",
});
}
Then you can do function().done(function(result) { ... } );

javascript function that return a value from ajax [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
Can you help with my problem. I want to make a function that will return list of doctors in different spicialization.. this is my code the problem is this code the function doctorlist returns emtpy value. what is the wrong with my code.
can you help me to fixed my problem please.
$(document).ready(function () {
$("#loaders").append("<center><img src='images/ajax-loader.gif'></center>");
doctorSpecialty();
});
function doctorSpecialty(){
$.ajax({
url: "http://localhost:8080/m-help/apps/json_special.php",
dataType: 'json',
async: true,
success: function(data) {
$("#list").empty();
$.each(data.result, function(){
var specialty = doctorList(this['specialization']);
$("#list").append("<li><a href='doctor-special.html?special=" +this['specialization']+ "' style='padding-left:10px'>" +this['specialization']+ ""+specialty+"</a></li>");
$("#loaders").fadeOut("fast");
});
}
});
}
function doctorList(e){
var specials = e;
var retSpecial = "";
$.ajax({
url: "http://localhost:8080/m-help/apps/json_special-doctor.php?s="+specials,
dataType: 'json',
async: true,
success: function(data) {
$.each(data.result, function(){
retSpecial = this['docFname'];
});
}
});
return retSpecial;
}
Anyone can help me to fixed this code for please.
The second call can not be async = true, since the loop continues and uses the answer (which has not arrived yet).
You should make the second async:false
OR
Use promises in the second call which will fill in the specialization and you need to cancel the DOM manipulation in the first ajax call.

Categories

Resources