Return value ajax jquery async

how can I get this code to return a value without freezing the browser .
You can rewrite this with the new method, of course.

function get_char_val(merk)
{  
    var returnValue = null;
    $.ajax({   
                type:       "POST",
                async:      false,   
                url:            "char_info2.php",   
                data:   { name: merk },   
                dataType: "html",  
                success:    function(data)
                                    {
                                        returnValue = data;
                                    } 
        }); 
    return returnValue;
}
var px= get_char_val('x');
var py= get_char_val('y');

EDIT: I need to get at least 20 variables from a php file at another time.

+5
source share
3 answers

It's impossible.
Javascript runs in the user interface thread; if your code is waiting for a server response, the browser should remain frozen.

Instead, you need to return the value with a callback:

function get_char_val(merk, callback)
{  
    var returnValue = null;
    $.ajax({   
                type:       "POST",
                url:            "char_info2.php",   
                data:   { name: merk },   
                dataType: "html",  
                success:    function(data) {
                    callback(data);
                } 
        }); 
}

get_char_val('x', function(px) { ... });
get_char_val('y', function(py) { ... });

, .


, AJAX.
, , , JSON, { x: "...", y: "..." }.

+14

(async). success.

variableArray = new Array(); 

get_char_val('x');
get_char_val('y');

function get_char_val(merk)
{  
    var returnValue = null;
    $.ajax({   
        type:       "POST",
        url:            "char_info2.php",   
        data:   { name: merk },   
        dataType: "html",  
        success:    function(data)
            {
                variableArray[merk] = data;
            } 
    }); 
}

, x y variableArray[x] variableArray[y]

+1

Perhaps this is not what you expect, but you can set async: true if you do not want to pause the browser and so what you want to do with px for success

0
source

All Articles