I am very new to Ajax and under major deadline.
I have an ajax function
$.ajax({
type: "POST",
url: 'CritAdd.php?',
data: { currfilterfields : currfilterfields },
async: false,
success: function(msg) {
var javminmaxarray = $.parseJSON(msg);
alert(msg);
alert(javminmaxarray);
}
});
This works perfectly fine and the data gets stored in global variable array "javminmaxarray". Alerts put for testing also show expected values.
However when I use this global array in my function where it needs to be accessed as below, the value shows as empty/undefined.
function closemodal() {
alert(javminmaxarray[0]);
}
I made asynch option of ajax as false but that didn't work either. Please suggest how to use the value from ajax function outside the success block.
change this..
var javminmaxarray = $.parseJSON(msg);
to
javminmaxarray = $.parseJSON(msg);
declare you javminmaxarray variable outside the $.ajax function .
var javminmaxarray = {};
// ....
$.ajax({
//...
success: function(msg) {
javminmaxarray = $.parseJSON(msg);
}
});
and then use your function how ever you want
function closemodal(){
alert(javminmaxarray[0]);}
Related
I am trying to create a database handler class in javascript. I would like to call the class by simply using:
var databaseHandler = new DatabaseHandler();
result = databaseHandler.getResult("SELECT * FROM login");
I have created the class and used a callback for the ajax function (so as to wait for the ajax result to be returned). But all I am still receiving "undefined" as my result. If I use console.log(a) inside of the onComplete function, I get an array of the intended results.
(function(window){
//Database class
function DatabaseHandler(){
//Query
this.query = function(query, whenDone){
request = $.ajax({
url: "../optiMizeDashboards/php/DatabaseQuery.php",
type: "POST",
data: {query : query},
dataType: "JSON"
});
request.done(function(output) {
whenDone(output);
});
request.fail(function(jqXHR, textStatus) {
console.log(textStatus);
});
};
//Get result
this.getResult = function(query){
this.query(query, this.onComplete);
};
//Ajax callback
this.onComplete = function(a){
return a;
};
}
//Make available to global scope
window.DatabaseHandler = DatabaseHandler;
}(window))
My question is: Is this something to do with the variable scope, or the way that ajax works? I have read all the answers explaining that ajax is ASYNC and I thought I had handled that by using a callback function "onComplete"
Any help on this topic would be greatly appreciated!
You will not be able to return result immediately from calling getResult because underlying jQuery POST request is Asynchronous, instead you need to be passing a callback function which eventually will receive a result from server.
something like that:
(function(window){
//Database class
function DatabaseHandler(){
//Query
this.query = function(query, whenDone){
request = $.ajax({
url: "../optiMizeDashboards/php/DatabaseQuery.php",
type: "POST",
data: {query : query},
dataType: "JSON"
});
request.done(function(output) {
whenDone(output);
});
request.fail(function(jqXHR, textStatus) {
console.log(textStatus);
});
};
//Get result
this.getResult = function(query, callback){
this.query(query, callback);
};
}
//Make available to global scope
window.DatabaseHandler = DatabaseHandler;
}(window))
// then use it like so
var databaseHandler = new DatabaseHandler();
result = databaseHandler.getResult("SELECT * FROM login", function(data) {
//do something with data
});
PS: exposing direct SQL access to the databse on the client is very dangerous though, and I would not recommend doing that
I created a function that makes a jquery AJAX call that returns a JSON string. On its own, it works fine -- and I can see the JSON string output when I output the string to the console (console.log).
function getJSONCustomers()
{
var response = $.ajax({
type: "GET",
url: "getCustomers.php",
dataType: "json",
async: false,
cache: false
}).responseText;
return response;
};
However, when I set a variable to contain the output of that function call:
var mydata = getJSONCustomers();
, then try to use it within my Twitter-Bootstrap TypeAhead function (autocomplete for forms):
data = mydata;
console.log(data);
I get an 'undefined' error in my console.
Below is a snippet of this code:
$(document).ready(function() {
var mydata = getJSONCustomers();
$('#Customer').typeahead({
source: function (query, process) {
customers = [];
map = {};
data = mydata;
console.log(data);
// multiple .typeahead functions follow......
});
Interesting here, is that if I set the data variable to be the hardcoded JSON string returned from the AJAX function, everything works fine:
data = [{"CustNameShort": "CUS1", "CustNameLong": "Customer One"}]
How can I use the JSON string within my typeahead function?
.responseText returns a string. You have to parse the string first to be able to work with the array:
var mydata = JSON.parse(getJSONCustomers());
That being said, you should avoid making synchronous calls. Have a look at How do I return the response from an asynchronous call? to get an idea about how to work with callbacks/promises.
The problem is that the Ajax request hasn't had the chance to complete before typeahead is initialised, so typeahead is initialised with an uninitialised mydata variable. Also, as of jQuery 1.8+ async: false has been deprecated and you need to use the complete/success/error callbacks.
Try this:
function getJSONCustomers(callback) {
$.ajax({
type: "GET",
url: "getCustomers.php",
dataType: "json",
cache: false,
success: callback
});
};
And then you could do something like:
getJSONCustomers(function(mydata) {
// mydata contains data retrieved by the getJSONCustomers code
$('#Customer').typeahead({
source: function (query, process) {
customers = [];
map = {};
console.log(mydata);
// multiple .typeahead functions follow......
});
});
So your code completes the Ajax call before initialising the typeahead plugin.
I have an issue with a method ive created for an object ive created. one of the methods requires a callback to another method. the problem is i cant add the data to the object that called the method. it keeps coming back as undefined. otherwise when i send the data to the console it is correct. how can i get the data back to the method?
var blogObject = new Object();
var following = [...];
//get posts from those blogs
blogObject.getPosts = function () {
var followersBlogArray = new Array();
for (var i = 0; i < this.following.length;i++){
var followersBlog = new Object();
// get construct blog url
var complete_blog_url = ...;
i call the getAvatar function here sending the current user on the following array with it.
followersBlog.avatar = blogObject.getAvatar(this.following[i]);
that part goes smoothly
followersBlogArray.push(followersBlog);
}
this.followersBlogArray = followersBlogArray;
}
here is the function that gets called with the current user in following array
this function calls an ajax function
blogObject.getAvatar = function (data) {
console.log("get avatar");
var url = "..."
this ajax function does its work and has a callback function of showAvatar
$(function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: url,
data: {
jsonp:"blogObject.showAvatar"
}
});
});
}
this function gets called no problem when getAvatar is called. i cant however get it to add the data to the followersBlog object.
blogObject.showAvatar = function (avatar) {
return avatar
}
everything in here works fine but i cant get the showAvatar function to add to my followersBlog object. ive tried
blogObject.showAvatar = function (avatar) {
this.followersBlog.avatar = avatar;
return avatar
}
that didnt work of course. it shows up as undefined. can anyone help?
so somethings like...
$(function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: url,
complete: function () {
this.avatar = data;
}
data: {
jsonp:"blogObject.showAvatar"
}
});
});
}
Welcome to the world of asynchronous programming.
You need to account for the fact that $.ajax() will not return a value immediately, and Javascript engines will not wait for it to complete before moving on to the next line of code.
To fix this, you'll need to refactor your code and provide a callback for your AJAX call, which will call the code that you want to execute upon receiving a response from $.ajax(). This callback should be passed in as the complete argument for $.ajax().
The correct option for setting the JSONP callback is jsonpCallback. The recommendation from the API for .ajax(...) is to set it as a function.
{
// ...
jsonpCallback: function (returnedData) {
blogObject.showAvatar(returnedData);
},
// ...
}
I'm trying to fire an Ajax request with some data being returned by a function call and, as far as I can tell, the Ajax call isn't waiting for my function call to return.
I'm calling getSelectedMessages to get the values of a variable number of checkboxes before firing an Ajax request with an array of the values returned by getSelectedMessages.
getSelectedMessages looks like this:
var getSelectedMessages = function() {
var selected = [];
$('input:checkbox[name=multipleops]:checked').each(function() {
selected.push($(this).attr('value'));
});
return selected;
}
And the Ajax request that's invoking it looks like this:
$.ajax({
type: "POST",
url: "/api/messages/",
data: { ids: getSelectedMessages(), folder: folder },
cache: false,
success: function(){ location.reload() }
});
I've done a little bit of searching around and all I'm turning up are answers on how to return a value from a call and to it.
use
beforeSend attribute with ajax
try
var getSelectedMessages = function() {
var selected = [];
$('input:checkbox[name=multipleops]:checked').each(function() {
selected.push($(this).attr('value'));
});
return selected;
}
$.ajax({
type: "POST",
url: "/api/messages/",
beforeSend : function () { return jQuery.isEmptyObject(getSelectedMessages); }
data: { ids: getSelectedMessages(), folder: folder },
cache: false,
success: function(){ location.reload() }
});
Reference
beforeSend
isEmptyObject
Call getSelectedMessages() outside the ajax function of jquery (?)
The function is executed before the request is sent.
The real problem is that the getSelectedMessaged() returns an array.
This results in undefined=undefined after serialization in jQuery's internals.
And that gets ignored by the $.ajax(), so it looks like it's not sending in your vars but it's ignoring them because they're undefined.
If you concatenate a string with the values and make it a query string parameter yourself it should work.
I assume you want to send something like ?var[]=something&var[]=somethingelse to the server, so it ends up in PHP as an array?
Than you'll have to build up the string yourself in the getSelectedMessages function.
Hope it helps,
PM5544
I want to create a separate function to get specific data from Facebook graph JSON.
For example, I have the load() and called getNextFeed() function.
The getNextFeed works correctly. Except that returning value of aString is not successful.
When I pop alert(thisUrl). It said undefined.
Note: I am new to Javascript and Jquery. Please give me more information where I did wrong. Thank you.
function load()
{
$(document).ready(function() {
var token = "AccessToken";
var url = "https://graph.facebook.com/me/home?access_token=" + token;
var thisUrl = getNextFeed(url);
alert(thisUrl); // return undefined
});
function getNextFeed(aUrl)
{
$.ajax({
type: "POST",
url: aUrl,
dataType: "jsonp",
success: function(msg) {
alert(msg.paging.next); // return correctly
var aString = msg.paging.next;
alert(aString); // return correctly
return aString;
}
});
}
The problem is that $.ajax() is an ansynchronous function, means, when called, it returns in the same instance, but an ajax call is done in a separate thread. So your return vaule of $.ajax() is always undefined.
You have to use the ajax callback function to do whatever you need to do: Basically you already did it correctly, just that return aString does not return to your original caller function. So what you can do is to call a function within the callback (success()), or implement the logic directly within the success() function.
Example:
function load()
{
$(document).ready(function() {
var token = "AccessToken";
var url = "https://graph.facebook.com/me/home?access_token=" + token;
getNextFeed(url);
alert('Please wait, loading...');
});
function getNextFeed(aUrl)
{
$.ajax({
type: "POST",
url: aUrl,
dataType: "jsonp",
success: function(msg) {
alert(msg.paging.next); // return correctly
var aString = msg.paging.next;
alert(aString); // return correctly
do_something_with(aString);
}
});
}