0

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

frosty
  • 2,559
  • 8
  • 37
  • 73
  • 1
    [how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-re](https://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-re) might be helpful to you – flyingfox Nov 14 '22 at 02:09
  • You don't want to do this synchronously, what you actually want to do is to understand how to do async properly: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Adam Jenkins Nov 14 '22 at 02:19

1 Answers1

0

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);
sjb
  • 1
  • 2