0

I'm trying to learn javascript and encountered a wall due to working with variables through multiple functions.

After browsing through the documentation and stackoverflow most voted answers, related to global variables and how to effectively work with them through multiple functions.

I found little to no simple solution.

Any kind soul able to correct how this complete piece of code can work properly ?

variable "ttl" and "msg" are needed to be passed from "ajax" function to "notify" function

<script src="js/jquery.js"></script>
<script src="js/bootstrap-notify.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        // Global variables ttl and msg needed ?
        var ttl = null;
        var msg = null;

        // Make an ajax call to json file.
        $.ajax({
            url: "lastorder.json",
            dataType: "json",
            // Parse title and message from json.
            success: function(data) {
                ttl = data.title;
                msg = data.message;
            }
        });
        // Notify function displays a title and message that was parsed from json file
        $.notify({
            icon: 'img/avatar.jpg',
            title: ttl,
            message: msg
        },{
            type: 'minimalist',
            delay: 3000,
            icon_type: 'image',
            template: '<div data-notify="container" class="col-xs-11 col-sm-3 alert alert-{0}" role="alert">' +
                '<img data-notify="icon" class="img-circle pull-left">' +
                '<span data-notify="title">{1}</span>' +
                '<span data-notify="message">{2}</span>' +
            '</div>'
        });

    });
</script>
Marie Anne
  • 301
  • 1
  • 2
  • 12
  • Can you move your `$.notify` code into the `success` callback? Or is there a reason it needs to be outside of it? – Mike Cluck Apr 22 '16 at 16:44
  • are you getting null values for both variable in notify function ? – Hiren patel Apr 22 '16 at 16:48
  • Mike, that does work but i can't nest function inside a function when I'll be adding more things to do. I checked this [Reference](http://stackoverflow.com/questions/9085839/surprised-that-global-variable-has-undefined-value-in-javascript) As I will need to use the ttl and msg on more than just `$.notify` function, so having a concrete solution to use the variables is important. – Marie Anne Apr 22 '16 at 16:52
  • @Hirenpatel yes both return Null – Marie Anne Apr 22 '16 at 16:52
  • if `$.ajax` is async you won't get the values you need. Set `async: false` and see if it works. [jQuery docs](http://api.jquery.com/jquery.ajax/) – Daniel Almeida Apr 22 '16 at 16:53
  • 1
    @DanielAlmeida -- Never recommend setting `async` to false.... – Jeremy J Starcher Apr 22 '16 at 16:54
  • Then I'd suggest doing kind of like what Daniel said in his answer. Create a separate function which does your `$.notify` work and passed the values as needed to that function. Basically, the moment you start working with asynchronous values, everything else has to respond to an event of some sort (even if it's just one function that calls into more functions). – Mike Cluck Apr 22 '16 at 16:59
  • @JeremyJStarcher sorry, but can you explain why? doesn't seem to load lots of data that could block the browser.. – Daniel Almeida Apr 22 '16 at 17:00
  • 2
    @DanielAlmeida I'm not Jeremy but I can tell you that 1) [It's deprecated](http://stackoverflow.com/questions/11448011/jquery-ajax-methods-async-option-deprecated-what-now) 2) It encourages bad patterns and 3) It essentially locks up the browser while you're waiting for a response. – Mike Cluck Apr 22 '16 at 17:03
  • 1
    @DanielAlmeida It's not just the data -- it's the whole connection process. If there is any kind of slowdown in making the connection, from a DNS timeout to a a cellphone losing signal for a few seconds, the entire browser freezes. – Jeremy J Starcher Apr 22 '16 at 17:05
  • thank you both @JeremyJStarcher and MikeC . I didn't know that.. I always use the success/complete/error callback. – Daniel Almeida Apr 22 '16 at 17:10

2 Answers2

1

If you want to try @MikeC solution:

$(document).ready(function () {
        // Global variables ttl and msg needed ?
        var ttl = null;
        var msg = null;

        // Notify function displays a title and message that was parsed from json file
        function notify(data) {

            ttl = data.title;
            msg = data.message;

            $.notify({
                icon: 'img/avatar.jpg',
                title: ttl,
                message: msg
            }, {
                type: 'minimalist',
                delay: 3000,
                icon_type: 'image',
                template: '<div data-notify="container" class="col-xs-11 col-sm-3 alert alert-{0}" role="alert">' +
                '<img data-notify="icon" class="img-circle pull-left">' +
                '<span data-notify="title">{1}</span>' +
                '<span data-notify="message">{2}</span>' +
            '</div>'
            });

        }

        // Make an ajax call to json file.
        $.ajax({
            url: "lastorder.json",
            dataType: "json",
            // Parse title and message from json.
            success: notify
        });

    });
Daniel Almeida
  • 400
  • 3
  • 8
0

If you want to response returned from ajax request then you can get this data after ajax request successfully executes. Since ajax is asynchronus call , the code waiting for the response will be already executed by the time the response is received. So you will not get exact value return by ajax response in notify function.

So , in order to use values return by ajax response , you must call notify function in side success() method of ajax.

refer this SO question

Community
  • 1
  • 1
Hiren patel
  • 971
  • 8
  • 25