0

I am trying to get the value returned from a JavaScript function.

Here is the function:

function db_check(field_id, data_type, value) {
    $.ajax({
        url: 'ajax-php.php',
        type: 'post',
        dataType : 'json',
        data: { 'db_check': 'true', 'field_id': field_id, 'value': value, 'data_type': data_type },
        success: function (data, status) {
            alert(data);
            return data; 

        },
        error: function (xhr, desc, err) {
            console.log(xhr);
            console.log("Details: " + desc + "\nError:" + err);
        }
    }
}

While the function is running the alert(data); return the good data. However if I use it somewhere within another function like Ex;

var result = db_check(field_id,data_type,value);
alert(result);

Then the alert is not showing the data but instead returning undefined.

I think this has to do with the call back. If I understand correctly, its because the alert(result); is getting executed before I get the data from db_check() function.

Could anyone show me how to get this working please.

EDIT

I know this is a duplicate but I have hard time understanding what seams to be a very good explanation because they use the different terms like foo,result,callback over and over so I am having hard time to figure what they stand for! Anyways i will keep trying i will eventually get it.

MadeInDreams
  • 1,991
  • 5
  • 33
  • 64
  • 1
    yes, It's because you'r function is async. I'll try to help you, so, you can solve this by passing the function to db_check, and when ajax call is finished you can call your function, so: `db_check(field_id, data_type, value, callbackFn)` inside success function you say: `callbackFn(passTheValueHere)` and when you call db_check, call it with: `db_check(field_id,data_type,value, function callbackFn(passedValue) { alert(passedValue) });` When you understand this method, I suggest you to take a look at: https://api.jquery.com/deferred.promise/ because that is beter solution. Hope that I help – Darkves Jan 19 '16 at 00:03
  • Inside the success function? do you mean that where i have success: function (data, status) { should become success:callbackFn(field_id, data_type, value) – MadeInDreams Jan 19 '16 at 00:22
  • 1
    no. You need to do it like this: `success: function (data, status) { callbackFn(data); }, ` – Darkves Jan 19 '16 at 08:01
  • http://stackoverflow.com/questions/34871371/javascript-array-debuging i am almost there made a new question since its more about array. Got promise working – MadeInDreams Jan 19 '16 at 08:03

0 Answers0