0

I'm trying to set the returned object from a jQuery Ajax call to the scope of the parent function (jQuery Ready).
I'm probably missing something obvious, but I'm pretty tired today and I can't find it.
In comment, I gave some feedback on the console.logs.

Here is my current code:

$(function () {
    var json_contracts; 
    var parent_id = $('#dropdown_parents').select2('data').id;         
    $.ajax({
        type: 'GET', 
        url: 'http://www.ingemployeebenefits.com/develop_kgy/entities/parents/db_parents_getcontracts.php',
        dataType: 'json', 
        data: {
            'parent_id': parent_id
        },
        success: function(data) {
            json_contracts = data;
            //This line returns the object properly 
            console.log(json_contracts); 
        }, 
        error: function (xhr,status,error) {
                   $('#msg_parent_view').html("Error: " + error);
                   return false;
                }
    });
    //This line returns undefined. 
    console.log(json_contracts); 
});

I also checked out this post: Set javascript global variable to JSONresult?

I can't see what I'm doing diffferently.

Thanks

Community
  • 1
  • 1
html_programmer
  • 18,126
  • 18
  • 85
  • 158

2 Answers2

1

It is happening because console.log() is called before ajax call is completed.

Add callback and it should work.

Try:

$(function () {
    var json_contracts; 
    var parent_id = $('#dropdown_parents').select2('data').id;    
    function get_value(function(){
        console.log(json_contracts);
    });
    function get_value(callback){
        $.ajax({
            type: 'GET', 
            url: 'http://www.ingemployeebenefits.com/develop_kgy/entities/parents/db_parents_getcontracts.php',
            dataType: 'json', 
            data: {
            'parent_id': parent_id
            },
            success: function(data) {
                json_contracts = data;
                console.log(json_contracts); 
        }, 
           error: function (xhr,status,error) {
                   $('#msg_parent_view').html("Error: " + error);
                   return false;
                }
        });
    }        
});
codingrose
  • 15,563
  • 11
  • 39
  • 58
0

Basic AJAX, your global variable is being assigned but your console.log statement returns undefined because it is hit before your AJAX is complete. Either do your logic inside the success function or pass in a callback function which takes your data as a parameter.

tymeJV
  • 103,943
  • 14
  • 161
  • 157