Note that there are some explanatory texts on larger screens.

plurals
  1. POjQuery: a function containing an ajax() function won't return ajax() response
    text
    copied!<p>In an attempt to make my jQuery code modular, i.e. reusable, I've placed an ajax() function inside of another function <code>fetch_ajax()</code>. I'm trying to call <code>fetch_ajax()</code> with parameters from other places, which <em>should</em> simply run the contained <code>ajax()</code> and return the response.</p> <p>But that's not happening - instead, <code>fetch_ajax()</code> apparently returns false too quickly to the caller and doesn't wait until <code>ajax()</code> has completed the request and gotten a response.</p> <p>Here's the code:</p> <p>The <code>fetch_ajax()</code> function</p> <pre><code>function fetch_ajax(url) { $.ajax({ type: 'GET', url: url, success: function(response) { return response; } }); } </code></pre> <p>The calling function:</p> <pre><code>function caller() { response = fetch_ajax('script.php'); alert(response); //this is always 'undefined' } </code></pre> <p>In <code>fetch_ajax()</code>, I've tried not directly returning <code>response</code> from within <code>ajax()</code>, but writing it to a variable, and returning that variable after <code>ajax()</code> - that didn't work either (same result).</p> <p>When I place a 2nd alert right before <code>return response;</code> inside of the <code>ajax()</code> function, I'm seeing that one fire AFTER the one inside <code>caller()</code>. So I'm thinking that somehow, <code>fetch_ajax()</code> doesn't wait for the contained function to execute before it returns false.</p> <p>What am I doing wrong?</p> <p>Thank you.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload