0

I researched on this question in forums but could not succeed with applying code in answers given by techies. I am trying to access a variable which is inside jquery success function. It throws null as it was assigned null on initialisation. How can I access data value out side ajax call? Also my Stringified result shows "/" slashes in json string. How can I remove slashes in code. I tried applying regex, replacing / with quotes but no use. Please suggest.

var details=null;

        $.ajax({
            type: "GET",
            url: "/Default/GetDetails",
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (data) {
                details = JSON.stringify(data);            
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.statusText);
            }
        });
    alert(details)
Kurkula
  • 6,386
  • 27
  • 127
  • 202
  • This is not duplicate of Getting response from ajax call. I am able to get response successfully.I get data in success function and I want to use that response outside ajax function.. – Kurkula Jan 06 '14 at 09:17
  • 2
    It is a duplicate. If you read that question, you'll learn why you can't do what you're trying, and how to do it properly. – Barmar Jan 06 '14 at 09:19
  • You're alerting before the AJAX call has completed, because AJAX is asynchronous. – Barmar Jan 06 '14 at 09:19
  • There is no need to parse the `data` within the ajax since you have mentioned `dataType` as `json`. – Praveen Jan 06 '14 at 09:21

2 Answers2

2

The normal execution will not wait for the ajax block to complete execution. so the value of details will be alerted even before the result is assigned by ajax. That is why the alert shows null as result.

if you want to alert the result of details u can call it inside the ajax call.

Myth
  • 446
  • 7
  • 18
-4

try to add on more option in your ajax call

async:false
Manish Jangir
  • 5,329
  • 4
  • 42
  • 75
  • 1
    As this will lock the UI thread it's a generally bad idea and - first and foremost - a bad user experience! – KeyNone Jan 06 '14 at 09:19