-2

I try to get some info from external php with ajax and use the data but my global var return undefined.I try with async false but is deprecated.If i console in success function it has value outside is undefined.

  var pkz;
  $(function(){

    $.ajax({
        type:'GET',
        url: '/user/cred',
        success: function (data){
         pkz=data;
        }
    });
console.log(pkz);
John Dow
  • 1
  • 1
  • loool possible that's why you unvote – John Dow Apr 27 '18 at 11:03
  • man that is a entire page i just need to use that variable – John Dow Apr 27 '18 at 11:04
  • And you can't because the AJAX callback is ran after your console.log. That post explains it very fine. – Ivar Apr 27 '18 at 11:06
  • i deleted my answer , dont no some people like to downvote , but if you want to use variable outside , then you must need to wait for ajax call to finish it , else you will get undefined – Pranay Rana Apr 27 '18 at 11:06
  • @JohnDow, I believe you are doing the wrong question. You want to use the return of a request on a PHP page? Why are you calling another service? Why you do not call the request directly on PHP? – Victor Apr 27 '18 at 11:30

1 Answers1

-1

The problem with your code is that the execution is asyncronous. When you run console.log, the ajax did not finished. Put it inside the ajax callback. The ajax do not block the execution. It continue without finished. You SHOULD use callbacks.

If you want to use ajax syncronous:

$.ajax({
    type: "GET",
    url: remote_url,
    async: false
})

This is a horrible solution.

Victor
  • 8,309
  • 14
  • 80
  • 129