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

2
  • can you add your HTML into the question too Commented Jun 27, 2015 at 8:17
  • is better not to use a FunctionsCall there, use directly the ajax function, and in the success function add or remove the classes depending on the ret value Commented Jun 27, 2015 at 8:34

8 Answers 8

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);
});
Sign up to request clarification or add additional context in comments.

6 Comments

Thats what i am thinking, is there a way to execute ajax first before continuing
@MysticJay You could do a synchronous ajax 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.
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
@MysticJay I've updated my answer with an example of how you could make it work.
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!
|
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.

Comments

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;

}

Comments

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;
}

2 Comments

@MysticJay Are you sure that you request actually succeed? Try adding an error function.
It it does i logged it to the console
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'); });
    }});
 }

Comments

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

Comments

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

Comments

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');
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.