3

I'm very new with Ajax and I need help to store the data from an Ajax request into an array. I looked at answers here at the forum, but I'm not able to solve my problem.The Ajax response is going into $('#responseField').val(format(output.response)) and I'm want store "output.response" into an array that can be used outside of the Ajax. I tried to declare a variable outside of the Ajax and call it later, but without success. I'm using $json_arr that should get the data. How do I do to get the data from the Ajax and store it in a variable to be used outside of the Ajax? This variable will an array that I can access the indexes.

function sendRequest(postData, hasFile) {

  function format(resp) {
    try {
      var json = JSON.parse(resp);
      return JSON.stringify(json, null, '\t');
    } catch(e) {
      return resp;
    }
  }

  var value; // grade item
  $.ajax({
          type: 'post',
          url: "doRequest.php",
          data: postData,
          success: function(data) { //data= retArr

            var output = {};

            if(data == '') {
              output.response = 'Success!';
            } else {
              try {
                output = jQuery.parseJSON(data);


              } catch(e) {
                output = "Unexpected non-JSON response from the server: " + data;
              }
            }
            $('#statusField').val(output.statusCode);
            $('#responseField').val(format(output.response));

            $("#responseField").removeClass('hidden');
            data = $.parseJSON(output.response)
            $json_arr=$('#responseField').val(format(output.response));
          },
          error: function(jqXHR, textStatus, errorThrown) {
            $('#errorField1').removeClass('hidden');
            $("#errorField2").innerHTML = jqXHR.responseText;
          }

  });

}

window.alert($json_arr);
Maple
  • 183
  • 8
  • Possible duplicate of [Wait until all jQuery Ajax requests are done?](https://stackoverflow.com/questions/3709597/wait-until-all-jquery-ajax-requests-are-done) – Nick Feb 12 '19 at 00:14
  • @Nick Why are you flagging this as duplicate when it isn't? User is asking how to return data from ajax to global scope inside javascript and not how to await for multiple ajax calls. – Admir Feb 12 '19 at 00:20
  • 1
    @Admir OPs problem is that `window.alert($json_arr);` is executed before the ajax call completes, hence `$json_arr` has no data in it. – Nick Feb 12 '19 at 00:22
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Louys Patrice Bessette Feb 12 '19 at 00:57
  • @Nick How do I solve that? – Maple Feb 12 '19 at 00:59
  • Read the answers to the possible duplicates, I'm sure at least one will be adaptable to your situation. The diplicate posted by @LouysPatriceBessette is probably a better place to start. – Nick Feb 12 '19 at 01:03
  • @Nick I went to "How do I return the response from an asynchronous call?", and I did no find the answer. Should I put 30 secs to get the result? – Maple Feb 12 '19 at 01:25
  • I'm trying everything and it is not working. Any helping , I really appreciate. – Maple Feb 12 '19 at 03:43
  • **$json_arr** is defined inside the AJAX call, and you are trying to use it outside this. The scopes do not match. Try defining **$json_arr** outside the function (in the same scope you intend to use it). I think that should work. – muka.gergely Feb 12 '19 at 04:12
  • @muka.gergely it still get blank if I try to use outside of ajax. – Maple Feb 12 '19 at 04:45
  • Then maybe it IS empty... are you sure you get data in the **data** variable? Are you sure there’s an **output** object with a **response** attribute? Did you check that it really should contain data, and there isn’t an error in the function somewhere before that? I’d try to **console.log** the response **data** on success - just to be sure the server sends the correct data to my function. And then **console.log** every step. If the data arrives, then you should be able to output it somehow. – muka.gergely Feb 12 '19 at 04:59
  • @muka.gergely if I use window.alert( $json_arr); inside of $AJAX it print the json, but if I try console.log, it does not print. – Maple Feb 12 '19 at 05:08
  • Actually your **window.alert** is outside the **AJAX** success method. **AJAX** is asynchronous, so you open the alert BEFORE the data arrives (synchronously). Most of the cases the alert will be empty if you put it there. It should be called in/from the success callback of the **AJAX**. – muka.gergely Feb 12 '19 at 05:29
  • You can see two answers below - I tried to make my snippet be closer to your example, and use $.ajax(), so you can see the problem easier. – muka.gergely Feb 12 '19 at 05:52

2 Answers2

0
let promise = new Promise(function(resolve, reject) {
  $.ajax({
          type: 'post',
          url: "doRequest.php",
          data: postData,
          success: function(data) { //data= retArr

            var output = {};

            if(data == '') {
              output.response = 'Success!';
            } else {
              try {
                output = jQuery.parseJSON(data);


              } catch(e) {
                output = "Unexpected non-JSON response from the server: " + data;
              }
            }
            $('#statusField').val(output.statusCode);
            $('#responseField').val(format(output.response));

            $("#responseField").removeClass('hidden');
            data = $.parseJSON(output.response)
            resolve(format(output.response));
          },
          error: function(jqXHR, textStatus, errorThrown) {
            $('#errorField1').removeClass('hidden');
            $("#errorField2").innerHTML = jqXHR.responseText;
          }

  });
});
promise.then(
  function(result) { /* you can alert a successful result here */ },
  function(error) { /* handle an error */ }
);

The issue is you are calling asynchronously.

0

You call the alert synchronously, but it should be called asynchronously.

A little snippet to help you see the difference:

// $json_arr initialized with a string, to make it easier to see the difference
var $json_arr = 'Hello World!';

function sendRequest() {

  $.ajax({
    // dummy REST API endpoint
    url: "https://reqres.in/api/users",
    type: "POST",
    data: {
        name: "Alert from AJAX success",
        movies: ["I Love You Man", "Role Models"]
    },
    success: function(response){
        console.log(response);
        $json_arr = response.name;
        // this window.alert will appear second
        window.alert($json_arr);
    }
  });

}
sendRequest();
// this window.alert will appear first
window.alert($json_arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
muka.gergely
  • 8,063
  • 2
  • 17
  • 34