Is there a synchronous version of the $.get() method? [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 months ago.
Since the $.get() method is asynchronous, the getText() function wasn't able to get a return value in the time that the $.get() method finished running. Is there a similar method that's like a synchronous version of the $.get() method?
var text = getText("https://www.google.com/search?q=search");
console.log(text);
function getText(url) {
$.get( url, function( data ) {
return data;
});
} //end of function getText(URL)
Returns: undefined

Please try this function:
function getText(url){
var output = '';
$.ajax({
url: url,
async: false
// ... other parameter
}).done(function(data) {
output = data;
});
return output;
}
you can change the parameter following this url
I have tested like below. it works fine.
function getText(url){
var output = '';
$.ajax({
url: url,
async: false
// ... other parameter
}).done(function(data) {
output = data;
});
return output;
}
var text = getText("https://jsonplaceholder.typicode.com/posts");
console.log(text);

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.
});

How to return data to variable after ajax call success [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 PHP file returning data in required array format to my FlotChart, it's working.
Now I'm trying to get this result in my script using ajax, however I cannot see result on global variable, as described below:
myJS.js
var EcomDashboard = function() {
return {
init: function() {
var dataEarnings = NULL;
$.ajax({
url:"operation.php",
dataType: "text",
success:function(data) {
alert(data); //show my array [ [1, 20],[2,30],[3,14] ]
dataEarnings = data;
}
});
alert(dataEarnings); //showing "NULL" but I need [ [1, 20],[2,30],[3,14] ]
...
What is the correct way to assign to my variable date Earnings the array [[1, 20], [2.30], [3.14]]?
Javascript is an async language, it means it won't wait the http request to finish to execute the next line. you will have to assign the variable inside the success block.
the alert shows null is becauseit got executed before the $.ajax http request line finishes.
may be you can do this using a callback:
dataAccess.js
var ecomDashboard = function() {
init: function(callback) {
var dataEarnings = NULL;
$.ajax({
url:"operation.php",
dataType: "text",
success:function(data) {
callback(data);
}
});
}
}
controller.js
ecomDashboard.init(function(data){
// data contains the array result
// do your stuff
})
event better:
since jquery 1.5 there is incorporated promise interface, and .success is going to be deprecated. edited: thanks to Kevin B
so with promise:
dataAccess.js
var ecomDashboard = function() {
init: function(callback) {
var dataEarnings = NULL;
return $.ajax({
url:"operation.php",
dataType: "text"
});
}
}
controller.js
ecomDashboard.init().done(function(data){
//do your stuff
alert(data);
}).fail(function(error){
//do stuff when error
});
$.ajax({
url:"operation.php",
dataType: "text",
success:function(data) {
doSomthingOnComplete(data);
}
});
function doSomthingOnComplete(data)
{
// do here your work
}
This is occurring because that alert(dataEarnings) is executing before your ajax request resolves. The first letter in the AJAX acronym is Asynchronous. So, ultimately your data is being set properly you are just trying to access it before the asynchronous call completes.

Returning value from javascript object [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have created a javascript object and im trying to fetch som data from it.
Im using jquery ajax to fetch send some values and then returing them from a php script.
this works, but when i try to use an instanse of my javascript object to dispaly the value i get 'undefined'.
Object:
var getDBresults = (function () {
function getResult(url,TableName ,callback){
$.ajax({
url: url,
type: 'POST',
data: {
'table':TableName,
},
success: function(data){
callback(data);
},
error: function(event){
alert(event.error);
}
});
}
return {
getAllVideoes: function(){
getResult("getAllResults.php", "videoer", function(data){
console.log(data); //Works
return data;
});
},
}
})();
in my other script:
var obj = getDBresults;
var data = obj.getAllVideoes(); //this runs, and produce the log showed above
console.log(data) //results in undefined
console.log(obj.getAllVideoes()) //results in undefined
Maybe you can use callbacks it will solve your async problems: http://recurial.com/programming/understanding-callback-functions-in-javascript/

javascript variable is not showing correct value [duplicate]

This question already has answers here:
How to add callback to AJAX variable assignment
(4 answers)
Closed 8 years ago.
i have this ajax call function.
function saveData(ip)
{
$JQ.ajax({
type: "POST",
url: "all_actions.php",
data:
{
page_url:document.URL,
ip_address:ip
},
success: function(responce)
{
if(responce)
{
var newtoken;
newtoken=responce;
return newtoken;
}
}
});
}
Then i have another function
function getToken()
{
var ip=myip
var mytoken;
mytoken=saveData(ip);
alert(mytoken);
}
My token giving undefined in alert.Although if i alert newtoken variable in savedata response it gives correct value in alert box.why if i return that avlue it does not assigned to mytoken.
is it something time delay issue.??
Need your help...
You cannot return from an asynchronous call.
You have to consume the return data inside the success function. Whatever you are going to do with token, write that code inside the success handler.
success: function(responce)
{
if(responce)
{
var newtoken;
newtoken=responce;
// Global variable
sourceid = newtoken;
return newtoken; // This won't work
}
}
Also
function getToken()
{
var ip=myip
var mytoken;
mytoken=saveData(ip); // This won't return any data
alert(mytoken); // This won't give you anything useful
}
Hi friends This is solution that for i was looking.
function saveData(ip)
{
return $JQ.ajax({
type: "POST",
url: "all_actions.php",
data:
{
page_url:document.URL,
ip_address:ip
},
async: false,
}).responseText;
}
function getToken()
{
var ip=myip
var mytoken;
mytoken=saveData(ip);
return mytoken;
}
The first 'A' in AJAX is 'Asynchronous'. Your alert is running before the AJAX request has had a chance to complete. You need to handle whatever you wish to do with the response inside of the success: function() or .done() functions of jQuery:
success: function(responce)
{
if(responce)
{
var newtoken = responce;
// Work here with newtoken...
}
}

Categories

Resources