Jquery Ajax Call Return - javascript

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

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

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.

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

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

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

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

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

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

Related

Javascript JQuery On Select Change Get Result and pass to outside

I have the following code which works on the event that a select box is changed.
When it changes, the ajax call will pass the results to the variable result.
My problem is that I cannot get that data outside this function.
The code:
$('#myselect').on('change', function() {
$.ajax({
url: 'myurl'+this.value,
method: 'GET',
success: function(result) {
console.log(result); //Just checking it's there
external = result;
}
});
});
console.log(external); //Returning Undefined
I need external to be available here outside the function above.
How do I do this?
You can create the variable outside of the event and than access it outside. But as ajax is ascychron, the variable would still be undefined:
var external;
$('#myselect').on('change', function() {
$.ajax({
url: 'myurl' + this.value,
method: 'GET',
success: function(result) {
external = result;
}
});
});
// this would be still undefined
console.log(external);
You can write the console.log inside your success, or create your own callback function. Then you can log or handle the data otherwise after the ajax request.
$('#myselect').on('change', function() {
$.ajax({
url: 'myurl' + this.value,
method: 'GET',
success: function(result) {
myCallback(result);
}
});
});
function myCallback(external) {
console.log(external);
}
Even shorter would it be possible in this example, if you directly use your callback function as success callback without wrapper. And because GET is the default request type, we could remove it too:
$('#myselect').on('change', function() {
$.ajax({
url: 'myurl' + this.value,
success: myCallback
});
});
function myCallback(external) {
console.log(external);
}
I'm sorry if I'm misunderstanding the question:
What it sounds like is that you are trying to get the data from external but the ajax call hasn't called the callback yet, so the data hasn't been set.
If I can recommend how to fix it, call the code that references external from the callback itself so you can guarantee that you have the data when you need it.
You are not able to access variable because it comes in picture after ajax completion and you are trying to access it directly, since you don't have any idea how exact time this ajax takes each time so you need to define a function like this
$('#myselect').on('change', function() {
$.ajax({
url: 'myurl'+this.value,
method: 'GET',
success: function(result) {
console.log(result); //Just checking it's there
saySomething(result); //result will be injected in this function after ajax completion
});
});
function saySomething(msg) {
console.log(msg); //use variable like this
}
I hope my code is help to you.
$('#myselect').on('change', function() {
$.ajax({
url: 'myurl'+this.value,
method: 'GET',
async: false, // stop execution until response not come.
success: function(result) {
console.log(result); //Just checking it's there
external = result;
}
});
});
console.log(external); //now it should return value
Define the variable external above your first function like so:
var external;
$('#myselect').on('change', function() {
$.ajax({
url: 'myurl'+this.value,
method: 'GET',
success: function(result) {
console.log(result); //Just checking it's there
external = result;
}
});
});
console.log(external);

AJAX: Store PHP data in a Javascript variable

As stated in the title, I have an ajax call. On the success function I want to store the returned data into a variable for use in my javascript. randNum.php simply returns a random number every 2 seconds, and I would like to use that number for other functions in my scripts. How can I use the data sent back from the php file in my javascript?
I know there are more logical ways to go about this, but want to know how to accomplish the task this way.
var result;
var interval = 2000;
function myCall() {
var request = $.ajax({
url: "randNum.php",
type: "GET",
dataType: "html",
success:function (msg) {
result = msg; //Not working as I intend
setTimeout(myCall, interval);
}
});
}
function(){
do something with result;
}
Declare a Global variable outside of the function and assign response variable to it after the ajax response.
var results;
function TestJSONP(){
$.ajax({
url: "randNum.php",
jsonp: "callback",
dataType: "jsonp",
success: function (response) {
console.log(response);
results = response;
}
});
}
You might not need to specify dataType, but use jqXHR.responseText to get the raw response. Something like
function myCall() {
var request = $.ajax({
url: "randNum.php",
type: "GET",
success:function (data, textStatus, jqXHR) {
result = jqXHR.responseText;
setTimeout(myCall, interval);
}
});
}
When you set dataType, and the response is not that type, then the ajax did not succeed and error call back will be invoked.

how to use properties and methods withing a JavaScript class to exchange data?

i have small issue with exchanging data in between methods in a JavaScript object (class):
var TEST = (function () {
var TEST = function() {
};
TEST.prototype.get = function() {
$.ajax({
type: "GET",
url: "http://test.com/getall",
dataType: "json",
success: function (data) {
return data; // if i console log this i will get a json obj
}
});
};
TEST.prototype.parse = function(data) {
$.each(this.get(), function(k, v){
console.log(v);
});
};
return TEST;
})();
so i am trying to call one method in the each statement in another method. the issue is that
the response is undefined.
i also tried it like this, but with he same result
var testing = new TEST();
var get = testing.get();
testing.parse(get);
What am i missing? how can i return the data from this.get to be used in this.parse.
thanks
$.ajax() per default is asynchronous. That means, that the execution of your function get() wont wait until the request is finished. Hence you return no value from it, which results in undefined being returned.
In order to have your get() function be able to return a value, you would have to do the request in a synchronous way and set a variable in the outer function (as success itself is just another function, whose return value is not caught):
TEST.prototype.get = function() {
var result;
$.ajax({
type: "GET",
url: "http://test.com/getall",
async: false, // this is the important part!
dataType: "json",
success: function (data) {
result = data;
}
});
return result;
};
EDIT
As mentioned by #pebbl, this will halt the execution of all your scripts, until the request is done. Hence your whole page will be blocked for the time being.
The general approach is to use callbacks in such cases, which will be executed once the requests finished. So in your case something like this:
TEST.prototype.get = function( cb ) {
$.ajax({
type: "GET",
url: "http://test.com/getall",
dataType: "json",
success: function (data) {
cb( data );
}
});
};
with later on calling like this:
var testing = new TEST();
testing.get( function( data ) {
testing.parse( data );
});
You can't construct your function this way as you are relying on an asyncronous call, which will return it's result outside of the normal execution flow. The only way you can actually receive the result of your .get function is to use a callback.
Put simply your value isn't being returned from the .get function, it's being returned from the callback you are passing into jQuery's .ajax method.
You'd be far better off redesigning your code so as to still support the asyncronous call -- rather than disabling async.
A rough idea is to change your parse function like so:
TEST.prototype.parse = function(data) {
this.get(function(result){
$.each(result, function(k, v){
console.log(v);
});
});
};
And to change your get function accordingly:
TEST.prototype.get = function(callback) {
$.ajax({
type: "GET",
url: "http://test.com/getall",
dataType: "json",
success: callback
});
};
The above is just a quick example, you'd be wise reading up on the following jQuery topics:
http://api.jquery.com/promise/
http://api.jquery.com/category/deferred-object/
If you design your code around the promise pattern you'll find it complicated at first, but it gives you a lot of power in your code -- and gets around the whole callback stacking madness you can end up with when dealing in ajax calls.
Whilst it's not entirely clear from the jQuery.ajax documentation, this function returns a jqXHR object which implements the promise interface. So this means you can use the promise methods done, always and fail.
http://api.jquery.com/jQuery.ajax/

How do I return something in JQuery?

function vote_helper(content_id, thevote){
var result = "";
$.ajax({
type:"POST",
url:"/vote",
data:{'thevote':thevote, 'content_id':content_id},
beforeSend:function() {
},
success:function(html){
result = html;
}
});
return result;
};
I want to return the result. But it's returning blank string.
Short answer, you can't.
Long answer, .ajax uses a callback to return the value. This means that the value may or may not have been returned already by the time the return fires. But either way, it's being done so in another context.
If you're looking to make this simulate returning a value, add a new argument to your function that will replace the ajax callback. Something such as:
function vote_helper(content_id, thevote, callback){
var result = "";
$.ajax({
type:"POST",
url:"/vote",
data:{'thevote':thevote, 'content_id':content_id},
beforeSend:function() {
},
success:callback
});
return result;
};
vote_helper(x,y,function(html){
result = html;
});
But work-around or not, the reply will never be in the same working path as the code that calls the function. You need to await the response and pick up processing from there.
Since you're making an AJAX call, you need to process the result of the AJAX call in the success callback:
function vote_helper(content_id, thevote){
$.ajax({
type:"POST",
url:"/vote",
data:{'thevote':thevote, 'content_id':content_id},
beforeSend:function() {
},
success:function(html){
/* Do something like call a function with html */
}
});
};
The ajax won't complete by the time your function ends, so you can't return a result. Instead you have to modify your function to accept a callback, and call that callback with the result:
function vote_helper(content_id, thevote, callback) { // extra callback argument
$.ajax({
type: "POST",
url: "/vote",
data: {'thevote':thevote, 'content_id':content_id},
beforeSend: function() {},
// Point directly to the callback here
success: callback
});
};
If you want the UI to be completely unresponsive while waiting for the server's response, you could do the following:
function vote_helper(content_id, thevote){
var result = "";
$.ajax({
type:"POST",
async: false, //This line will make your code work
url:"/vote",
data:{'thevote':thevote, 'content_id':content_id},
beforeSend:function() {
},
success:function(html){
result = html;
}
});
return result;
};
But nobody wants the UI to hang, so the real answer is what other suggested, instead of returning a value, your method should take a callback that will be passed the 'return value' when your asynchronous method returns.

jquery trouble with getJSON call

Got some basic problem again.
I need to modify a function that previously returned a in code written object.
Im now trying to get the object from json through $.getJSON
function getEventData() {
var result = '';
$.getJSON("ajax.php?cmd=getbydate&fromdate=&todate=", function(data) {
result = data;
});
return result;
}
Problem is that result isn't set in the callback function for obvious reasons.
Do you guys have a solution for this?
Edit:
Ok i got an answer that was removed.
I just had to change it abit..
This is the answer that works:
function getEventData() {
var result = '';
url = "ajax.php?cmd=getbydate&fromdate=&todate=";
$.ajax({
url: url,
async: false,
dataType: 'json',
success: function(data) {
result = data;
}
});
return result;
}
You should program your application in an asynchronous way, which means, that you should use callback functions for you application flow, too, or continue in the getJson callback function. You can also make the request synchronously which should then be able to return the value (or at least assign it and block the function till the callback is completed), but this is not recommended at all:
function getEventData() {
var result = '';
result = $.ajax({
url: "ajax.php?cmd=getbydate&fromdate=&todate=",
async: false,
dataType: "json",
data: data,
success: function(data) {
return data;
}
});
return result;
}
Are you sure that the server returns valid json? It will be better to validate it using a tool like jsonlint. Also make sure that application/json is used as content type for the response.

Categories

Resources