0

I want to keep a ajax result into a variable which I will use later. The problem is when I want to use the variable it returns null. I understand that it will for asynchronous programming. But I need to keep the result in a variable. Also I don't want to use async=false method. Below is my code I tried so far.

var column_values=[];
                    $.ajax({
                                url: "/get_value/",
                                type: "POST", // http method                                
                                dataType: "json",
                                async:"false",
                                data:{
                                    json:prev_value
                                },
                                success: function(data){
                                    column_values=data;
                                    
                                },
                                error: function(error){
                                    alert(error)
                                }
                            }); 

When I tried to access the value of column_values in another function it lengths returns 0.

function get_value(){
  let values=column_values.length;
  // Here it returns 0
}

What I am doing wrong?

Syed Islam
  • 73
  • 1
  • 11
  • 1
    Long answer short: when `get_value()` is invoked your async request has not returned the data yet. – Terry Jun 29 '21 at 10:12
  • 1
    The question is: *when* are you calling `get_value()`? –  Jun 29 '21 at 10:13
  • I understand. But how can I store the result in variable? Otherwise I need to call the ajax request every time. – Syed Islam Jun 29 '21 at 10:14
  • I am calling get_value() later time. It has no relation with the ajax call. I just want to use the result from variable. @ Chris G – Syed Islam Jun 29 '21 at 10:16
  • It works for me: https://jsfiddle.net/w0kjsfru/ Please provide a [mcve] and explain why this isn't a duplicate. Currently we can just guess what _"later time"_ means and what the actual problem is. –  Jun 29 '21 at 10:23
  • At first the example you have shown it use async : false method which is depreciated. Second,This is not duplicate because all the example I have seen they call the ajax multiple time to get the result. But I want to call the ajax one time and keep the result in a variable. For example: I call the ajax on form load and store the result in a variable. Then after a button click I want to access the variable to get the value.@jabaa – Syed Islam Jun 30 '21 at 14:20

0 Answers0