0

I am using an Ajax command to query data from a local server and I need to return a JSON object via the success handler.

My Ajax command looks like this:

var json = $.ajax({
    url: 'http://localhost:9200/wcs/routes/_search',
    type: 'POST',
    data: JSON.stringify({
        "query": {
            "match_all": {}
        }
    }),
    dataType: 'json',
    async: false
});

I'd like to return the JSON document in the variable that I already have assigned: json

Could I do something like this in the command? (I know this isn't correct code):

success: return(json);
});
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Shawn Roller
  • 1,101
  • 2
  • 12
  • 14

3 Answers3

1

You were close,

var json;
$.ajax({
    url: 'http://localhost:9200/wcs/routes/_search',
    type: 'POST',
    data :
        JSON.stringify(
            {
                "query" : { "match_all" : {} }
        }),
    dataType : 'json',
    async: false,
    success: function(data){
        json = data;
    }
})
console.log(json);

but async: false is a bad idea, so i'd suggest using json inside the callback.

$.ajax({
    url: 'http://localhost:9200/wcs/routes/_search',
    type: 'POST',
    data :
        JSON.stringify(
            {
                "query" : { "match_all" : {} }
        }),
    dataType : 'json',
    //async: false,
    success: function(data){
        console.log(data);
    }
})
Kevin B
  • 94,570
  • 16
  • 163
  • 180
0

Success expect's A function to be called if the request succeeds.

You can do this :

var json:
....
....

success: function(data){
       json = data;
   }
});
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
0
 var arr = new Array();
 success: function (data) {
    $.map(data, function (item) {
          arr.push({
              prop_1: item.prop_1,
              prop_2: item.prop_2,
              prop_3: item.prop_3
             });
           });
      }

You can rename prop_1, prop_2 vs up to your codebehind

Mehmet Ince
  • 4,059
  • 12
  • 45
  • 65