0

I have this in my HTML code

<script type="text/javascript">
    var URL = replace(); 
    alert(URL);
</script>

If I put this in header, alert shows “http://example.com/result"

function replace() { 
 url = 'http://example.com'; 
 $.get(url, function(data){ 
  var url_gen = data.responseText; 
 }); 
 return “http://example.com/result"; 
} 

But if I use return like this, it won't do anything. Why?

function replace() { 
 url = 'http://example.com'; 
 $.get(url, function(data){ 
  var url_gen = data.responseText; 
 }); 
 return url_gen; 
} 

Just to make sure, If I insert alert(url_gen) in front of return url_gen; in 2nd code, alert shows 'http://example.com' so url_gen has an actual value in it!

Note: Here, assuming that url_gen is the string which is web-scraped from a web page.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
HUSTEN
  • 5,117
  • 4
  • 24
  • 38

2 Answers2

1

Because 1) url_gen only defined in $.get(), can't be accessed outside; 2) $.get() is async.

Workaround: return directly from $.get():

function replace() { 
 url = 'http://example.com'; 
 $.get(url, function(data){ 
   var url_gen = data.responseText; 
    return url_gen;
 }); 
  
} 
Peter O.
  • 32,158
  • 14
  • 82
  • 96
nicael
  • 18,550
  • 13
  • 57
  • 90
  • Thanks now alert says "undefined" :( – HUSTEN Mar 29 '15 at 15:54
  • 1
    you receive undefined because you set alert on a response of ajax function. ajax has a delay to retrieve data but alert is triggered as soon as you call it. You have to make a sync ajax call (bad way because the window will freeze until your function is finished) or change your structure to set alert inside ajax response. – Ali Sheikhpour Mar 29 '15 at 16:25
1

Make url_gen global like below:

function replace() { 
url = 'http://example.com'; 
var url_gen ='';
$.get(url, function(data){ 
url_gen = data.responseText; 
}); 
return url_gen; 
} 
Peter O.
  • 32,158
  • 14
  • 82
  • 96
Samir Das
  • 1,878
  • 12
  • 20
  • Thanks for an answer. I tried your code, but now the alert says "undefined" instead of showing url – HUSTEN Mar 29 '15 at 16:00
  • It returns empty. as nicael said, $.get() is async so you should work or do necessary operation inside success callback. – Samir Das Mar 29 '15 at 16:20