0

I have made a function which is the one below that i pass data to and returns the result as is. I made this way because i will be needing a lot of ajax call and i just made a function that i pass the data to and get the result as is and work with the result.

function FunctionsCall(data){
var ret;
$.ajax({
type:'GET',
url: 'includes/helpers/functions.php',
dataType:"json",
data: data,
success: function(result){
    ret = result;
}});
return ret;}

Now i am calling it where i need it:

$('#register-name, #register-surname').keyup(function(e) {
var x = FunctionsCall({query: $(this).val(), funcid: 1});
(x!==1) ? $(this).addClass('input-has-error') : $(this).removeClass('input-has-error'); });

But strange is that i always see x as undefined. Pointing out the ret is filled with either 1 or 0 i don't know why it is not being passed to x.

Can you please help me out? It might be simple but i just experiment when needed with javascript and jquery.

Regards

Combinu
  • 882
  • 2
  • 10
  • 31

8 Answers8

1

ret doesn't get set until the success function runs, which is when the ajax finishes. FunctionCall returns straight away however. You'll either need to return the ajax deferred object or put your addClass/removeClass functionality in your success function.

A way to add your addClass/removeClass functionality to your success function would be like this:

function FunctionsCall(data, successFn) {
    $.ajax({
        type: 'GET',
        url: 'includes/helpers/functions.php',
        dataType: "json",
        data: data,
        success: successFn
    });
}

$('#register-name, #register-surname').keyup(function(e) {
    var element = $(this);
    var data = { query: element.val(), funcid: 1 };
    var successFn = function(x) { 
        if (x !== 1) { 
            element.addClass('input-has-error')
        } else {
            element.removeClass('input-has-error');
        }
    }
    FunctionsCall(data, successFn);
});
Ian
  • 159
  • 4
  • Thats what i am thinking, is there a way to execute ajax first before continuing – Combinu Jun 27 '15 at 08:22
  • @MysticJay You could do a [synchronous ajax](https://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-re) request but it will stop your entire page from working while the ajax happens. You're better off letting it happen asynchronously and dealing with the result when it comes in. – Ian Jun 27 '15 at 08:25
  • So the conclusion is that i can't make a function for ajax and use it wherever i want, i have to call where i need it – Combinu Jun 27 '15 at 08:27
  • @MysticJay I've updated my answer with an example of how you could make it work. – Ian Jun 27 '15 at 08:33
  • @MysticJay How did you go? – Ian Jun 27 '15 at 09:11
  • 1
    It is sort of what i was looking for, all i have to do is also pass what i want to do to the function. It works like this THANKS! – Combinu Jun 27 '15 at 11:42
1

The problem is that the ajax call takes time to execute, whereas your processing of x is immediately after the call to FunctionsCall

Imagine that in order to go to the php file and get the result, the browser has to send a request over the wire, the server needs to process the request and return the value, again over the wire. This process takes an unpredictable amount of time as it relies on network connections and server specs / current load.

The code to call the function and process the result happens immediately after this step and as such won't have the required values when it is run (browsers are much quicker at executing the next step than networks are at processing requests).

The best thing to do is to wrap your processing code up in it's own function, so it isn't immediately called, then call that function with the result once you get it. Like this:

// function defined, won't be called until you say so
var processMe = function(result) {
    alert(result);
}

$.ajax({
    // ajax params
    success: function(result) {
        // function called within success - when we know the request is fully
        // processed, however long it takes
        processMe(result));
    }
});

You could also do the processing directly in the success block but the advantage of using a function is it's there to re-use in the future, plus, you also get to give it a nice understandable name, like outputValidatedMessage.

Toni Leigh
  • 4,830
  • 3
  • 22
  • 36
1

you must send ajax request syncronous

function FunctionsCall(data){
var ret;
$.ajax({
    type:'GET',
    async: false,
    url: 'includes/helpers/functions.php',
    dataType:"json",
    data: data,
    success: function(result){
        ret = result;
    }
});
return ret;

}

user3441466
  • 43
  • 1
  • 6
0

Ajax calls are asynchronous.

This means that while you call $.ajax(), the function continues to run and return x which is undefined, as the ajax response has not been send yet.

function FunctionsCall(data){
    var ret;
    $.ajax({
        type:'GET',
        async: false,
        url: 'includes/helpers/functions.php',
        dataType:"json",
        data: data,
        success: function(result){
            ret = result;
        }
    });
    return ret;
}
Delgan
  • 18,571
  • 11
  • 90
  • 141
0

check if the following works, may be your GET method is taking time to execute.

   var x;
   function FunctionsCall(data){
   var ret;
     $.ajax({
     type:'GET',
     url: 'includes/helpers/functions.php',
    dataType:"json",
    data: data,
   success: function(result){
    ret = result;
    x= result;
      alert(x)
    }});
  return ret;}

if the snippet works, you should make you synchronous async: false or make callback function

KDP
  • 1,481
  • 7
  • 13
0

maybe is because the ajax function is called asynchronously so the line var x= .... doesn't wait for the asignment and thats why is undefined. for that you should use a promise here is an example http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/ http://www.htmlgoodies.com/beyond/javascript/making-promises-with-jquery-deferred.html

Geomorillo
  • 985
  • 1
  • 9
  • 14
0

The below should work for you

function FunctionsCall(data){
   var ret;
     $.ajax({
     type:'GET',
     url: 'includes/helpers/functions.php',
    dataType:"json",
    data: data,
   success: function(result){
    (result !==1 ) ? $(this).addClass('input-has-error') : $(this).removeClass('input-has-error'); });
    }});
 }
Ramesh
  • 13
  • 4
0

try this code.

function FunctionsCall(data,callback) {
    try {
        ajax({
            type: 'GET',
            url: 'includes/helpers/functions.php',
            dataType: "json",
            data: data,
            success: function (result) {
                callback(result);
            }
        });
    } catch(e) {
        alert(e.description);
    } 
}
$('#register-name, #register-surname').keyup(function (e) {
    var data = {            
        uery: $(this).val(),
        funcid: 1
    };
    FunctionsCall(JSON.stringify(data), function (result) {
        (result !== 1) ? $(this).addClass('input-has-error') : $(this).removeClass('input-has-error');
    });
});
Vishal Kiri
  • 1,248
  • 1
  • 12
  • 24