1

Good evening guys,

I have the following requisition AJAX:

function getJson(url) {
    var json;
    $.ajax({
        type: "POST",
        url: url,
        dataType: "json",
        async: false,
        success: function (data)
        {
            alert(data);
            json= data;
        }
    });
    return json;
}

When a execute, it shows a json on Chrome's network tab. But i can't manipulate using the variable data neither in an alert nor on return. There is something wrong with the code?

  • Do you get any error in console? Can you try with a different variable name instead of json? – Kavindra May 27 '18 at 02:18
  • Yes. "Failed to load: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.1.1' is therefore not allowed access." Is it something about permission? – Felipe Assunção May 27 '18 at 09:58
  • You need to enable CORS(Cross-Origin Resource Sharing) on your server. – Kavindra May 27 '18 at 10:04

1 Answers1

0

You are misunderstanding asynchronous functions. When JS runs that $.ajax, it doesn't wait for it to finish before continuing on with the code. So, when you return json; you are returning it before it is defined. You are going to have to refactor your code by using nested callbacks, promises, or async/await. This is a common problem that people new to asynchronous programming encounter and it can be very frustrating to learners.

Kevin
  • 359
  • 2
  • 7
  • 22