0

I am trying to call the ajax returned outside its function, below is the code I tried but didn't work.

var names;
$.ajax({
    type: 'POST',
    url: 'ajax/get_upcoming.php'
}).success(function (data) {
    names = data[1];
});

alert(names);
PSL
  • 123,204
  • 21
  • 253
  • 243
user2310422
  • 555
  • 3
  • 9
  • 22

2 Answers2

0

Because success function is callback function and called when ajax request get the response , so instead try this

var names;
$.ajax({
    type: 'POST',
    url: 'ajax/get_upcoming.php',
    success: performOperation
});



function performOperation(data)
{
    // write your code here 
    names = data[1];
}
Vijay
  • 1,024
  • 6
  • 18
  • I know how to do it, but i want to use names on other function. That's the whole idea – user2310422 Oct 05 '13 at 05:32
  • If you want to perform some opertation or activty after ajax request you need to put it in success function only . Because when request is going to complete,nobody knows , so its better practice to create a function and you write what you want to do and call it in success function – Vijay Oct 05 '13 at 05:35
  • Nope, you are not helping. – user2310422 Oct 05 '13 at 05:46
  • Now you are helping instead of suggesting. – user2310422 Oct 05 '13 at 05:58
0

I think alert() executes before the response comes back from the server. put console.log() and remove the alert and see the order of executions.

Evren Bingøl
  • 1,306
  • 1
  • 20
  • 32