0

I currently have a query from php outputting json that is one simple value. The json looks like this {"value":53}. I am trying to set that value as a variable in jquery function. The json I have is this and have tried all suggestions and ways that I have found but it still does not set that as a variable.

My current code in jquery is this:

var test = 
$.ajax({
     url: "ajax/graphs.ajax.php",
     dataType: "json",
     data: { get_param: 'value' },
     success: function(data) {
         return data;
    }
}) 

Any help or guidance is appreciated.

indubitablee
  • 8,136
  • 2
  • 25
  • 49
Deon
  • 97
  • 1
  • 13
  • 4
    possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – rrk Sep 18 '15 at 13:40
  • AJAX is asynchronous, the return wont work. – rrk Sep 18 '15 at 13:59

2 Answers2

0
  • AJAX is asynchonous;
  • "success function" scope is not the "main" scope;

Alternatives:

var test;
$.ajax({
     url: "ajax/graphs.ajax.php",
     dataType: "json",
     async : false,
     data: { get_param: 'value' }
}).success(function(data) {
     test = data;
});


var test = $.ajax({
     url: "ajax/graphs.ajax.php",
     dataType: "json",
     async : false,
     data: { get_param: 'value' }
});

console.log(teste.responseText)
0
var test;
$.ajax({
 url: "ajax/graphs.ajax.php",
 dataType: "json",
 async : false,
 data: { get_param: 'value' }
}).success(function(data) {
 test = $.parseJSON(data);
});

now the test variable is an array.

Master Yoda
  • 531
  • 8
  • 22