undefined object from php json-Collection of common programming errors

I try to send json array to ajax (from PHP to jQuery)

in my PHP script:

$value = 'test';
echo json_encode(
    array(
        'key' => $value
    )
);
exit;

Javascript side:

function sweety_ajax(url, datas)
{
    $.ajax({
        url: url,
        type: 'POST',
        cache: false,
        dataType: 'json',
        data: datas,
        success: function(r){
            return r;
        }
    });
}

I get the correct value with r.key inside the function, but I would like to get my “r” object like this:

var response = sweety_ajax(url, datas);

alert(response.key);

But the problem is that response object is undefined and cannot get the value of key…

Any idea?

  1. AJAX request in asynchronous. You need to pass a callback if you want to do this.

    function sweety_ajax(url, datas, callback)
    {
        $.ajax({
            url: url,
            type: 'POST',
            cache: false,
            dataType: 'json',
            data: datas,
            success: callback
        });
    }
    
    sweety_ajax(url, datas, function(response) {
      alert(response.key);
    });
    

Originally posted 2013-11-09 23:09:06.