0

I have what I believe to be a valid json test but I cannot get it to function correctly.

Here is a fiddle: http://jsfiddle.net/pwwj4zf5/

Any ideas why the onReady wouldn't be displaying the response in the Ajax call?

var a; 
function fetch_data(){
       $.ajax({
              url: "http://echo.jsontest.com/key/value/one/two",
              cache: false,
              dataType: "json",
              type: "GET",
              data: {
                     //datapoint: '(' + response1.d.PointOfContactId + ')'
              },
              success:function(data){

                  return data;

              }
       });
}

$(document).ready(function(){

       a = fetch_data(); 
       console.log(typeof(a));
       console.log(a);
});
SBB
  • 8,560
  • 30
  • 108
  • 223

2 Answers2

2

You may try something like this:

function fetch_data(fn){
   $.ajax({
          url: "http://echo.jsontest.com/key/value/one/two",
          cache: false,
          dataType: "json",
          type: "GET",
          data: {
                 //datapoint: '(' + response1.d.PointOfContactId + ')'
          },
          success:function(data){
              fn(data);
          }
   });
}

$(document).ready(function(){
    fetch_data(function(data){
        console.log(data);
    }); 
});

Updated Fiddle.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
0

By default $.ajax() performs an asynchronous request. (This is for good reason) take a look at the API documentation to learn in detail hwo to use callbacks to work with the ajax response.

Daniel
  • 3,541
  • 3
  • 33
  • 46