0

I'm tring to create a variable from an ajax call (object). The call looks like this:

        // Get scheduled resource, id
        $('#loading').show();
        var resource_id = $.ajax({
            url: campaign_planning_base_url() + '/get_schedule_resource_id',
            data: {
                event_id: event_id
            },
            type: "POST",
            dataType: 'json',
            success: function(data) {
                var resource_id = data[order].resource_id;
                return resource_id;
            }
        }).done(function() {
            $('#loading').hide();
        });

The data I receive back looks like this:

[{"resource_id":"36"}]

I like to use the value (36) of resource_id outside this call. But when I alert the value

alert (resource_id);

I receive [object Object]. How do I get the value 36? Anyone an idea?

MikeTSF
  • 39
  • 4

2 Answers2

0

As AJAX is asynchronous, so you can't return resource_id to any outside. You might call a outer function within success() function.

     // Outer function
      function callOuterFunction(resource_id) {
         alert(resource_id);
      }

      $('#loading').show();
        var resource_id = $.ajax({
            url: campaign_planning_base_url() + '/get_schedule_resource_id',
            data: {
                event_id: event_id
            },
            type: "POST",
            dataType: 'json',
            success: function(data) {
                var resource_id = data[0].resource_id; // should be use 0 instead of `order`
                callOuterFunction(resource_id); 
            }
        }).done(function() {
            $('#loading').hide();
        });
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
0

data[0].resource_id will return 36 and writing a call back function in the success block to use this value is a better option

prodeveloper
  • 943
  • 14
  • 22