Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variable outside ajax function [duplicate]

Please help - I have the following code which returns the variable 'results' in an alert. I want to use this variable outside of the function, and cannot get a callback, or outside declaration to work successfully. I'm sure I'm being a muppet, so I apologise for this basic question.....

<script src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script>

$(function () {
    $.ajax({
        type: 'POST',
        dataType: 'jsonp',
        url: 'https://creator.zoho.com/api/json/my-company-culture/view/PageFeed_Report?scope=creatorapi&authtoken=d670dc68ac0f6d7ca389e7b206a25045',
        success: function (results) {
            var raw_result=JSON.stringify(results);
            alert(results);
        }
    });
});

 </script>
like image 820
MarkE Avatar asked Aug 17 '26 08:08

MarkE


2 Answers

The jQuery 1.5+ way of resolving this is by using deferred objects:

var res;

var ajax = $.ajax({
    type: 'POST',
    dataType: 'jsonp',
    url: ...
}).done(function(results) {
    // you may safely use results here
    res = results;
    ...
});

// you cannot safely use 'res' here, only in code
// invoked via a 'done' callback on the `$.ajax` promise

console.log(res);    // undefined

It would be incorrect to attempt to copy results into some other variable in the outer scope unless you have ensured that no other code tries to access that variable until the AJAX call has completed.

like image 111
Alnitak Avatar answered Aug 18 '26 22:08

Alnitak


Well, why not:

    <script src='http://code.jquery.com/jquery-1.9.1.js'></script>
    <script>
    function do_the_stuff(smth) {
         console.log(smth);//or do whatever you want to do with this data
    }
    $(function () {
        $.ajax({
            type: 'POST',
            dataType: 'jsonp',
            url: 'https://creator.zoho.com/api/json/my-company-culture/view/PageFeed_Report?scope=creatorapi&authtoken=d670dc68ac0f6d7ca389e7b206a25045',
            success: function (results) {
                var raw_result=JSON.stringify(results);
                do_the_stuff(results);
            }
        });
    });

    </script>

That works fine for me. I don't see any problem.

like image 44
haldagan Avatar answered Aug 18 '26 21:08

haldagan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!