With this function I'm trying to get the licence name from a json url by name/key
my json looks like this:
[{"Gallery":true,"Responsive":true,"Main":true,"Seasonal":true}]
js:
function getLicenseName(name, callback){
var license = 'default'
$.getJSON(adl+'DesignTemplateBuilder.aspx?GetLicense=1', function(data){
/*
licence = data[0].Gallery;
respValue = data[0].Responsive;
seasonalValue = data[0].Seasonal;
*/
licence = data[0].name;
callback(licence)
});
}
getLicenseName(name, function(Responsive) {
console.log(name);
//this returns empty right now
});
What I need is to get the true or false value using something like this
getLicenceName(Gallery);
I need to use it in my functions eg: if(getLicenceName(Gallery)=false)...
function getLicenseName(callback){
$.getJSON(adl+'DesignTemplateBuilder.aspx?GetLicense=1', function(data){
callback(data)
});
}
getLicenseName(function(data) {
console.log(data[0].Gallery);
//this returns empty right now
});
Will do the trick.
You can't really do if(getLicenceName(Gallery) == false) because the AJAX request is asynchronous, but you can do it this way:
function getLicenseName(name, callback) {
$.getJSON(adl+'DesignTemplateBuilder.aspx?GetLicense=1', function(data){
// pass back the name parameter
callback(data[0][name])
});
}
// use quotes around the name
getLicenseName('Gallery', function (name) {
if (name) {
...
}
});
Related
I have three files: user.js, influencer.js, & validate.js
In user.js, I import ./influencer (as var = influencer) & ./validate (as var = validate).
My function in user.js:
addAccount: function(){
return functions.database.ref('/acct/{accountID}/name/').onCreate(event => {
var accountID = event.params.accountID;
var name = JSON.stringify(event.data.val()).replace(/['"]+/g, '');
console.log("New Account Added ("+accountID+")");
console.log("Nickname: " +name);
influencer.getIG(name);
var data = influencer.data;
validate.validateThis(data);
});
}
With influencer.getIG(name), I am passing the name we defined above to the function getIG (inside of influencer.js). This works like a charm. The result is JSON body.
What I want to do now is take this JSON body result and pass it to the validate function (in validate.js). In influencer.js, I also added "exports.data = data;".
With that being said, I can't seem to figure out how to pass "data" to validate.js. I log it, and it returns undefined. I added a timeout before running validateThis(data) and still undefined. The validate function on its own works great; I've tested it. But clearly, I am not doing this the correct way.
This is my influencer.getIG function:
module.exports = {
getIG: function (name) {
var url = "https://www.instagram.com/"+name+"/?__a=1"
console.log(url);
request({
url: url
}, function (error, response, body) {
var data = JSON.parse(body);
console.log(data);
exports.data = data;
})
}
}
How can I pass the result of the second module to the third module in my function? What am I doing wrong?
You can try passing callback function as another parameter to getIG
Your influencer file will look like this.
module.exports = {
getIG: function (name, callback) {
var url = "https://www.instagram.com/"+name+"/?__a=1"
request({
url: url
}, callback)
}
}
And your user file will look like this
addAccount: function(){
return functions.database.ref('/acct/{accountID}/name/').onCreate(event => {
var accountID = event.params.accountID;
var name = JSON.stringify(event.data.val()).replace(/['"]+/g, '');
influencer.getIG(name, function (error, response, body) {
var data = JSON.parse(body);
validate.validateThis(data);
});
});
}
Using callback will ensure that data is retrieved before you call it.
As the two other commentors noted - you have an asynchronous function with a callback. One way around this is to define the callback inside the user.js file, and pass it to the getIG function. So you would have
user.js
<pre><code>
addAccount: function(){
return functions.database.ref('/acct/{accountID}/name/').onCreate(event => {
var accountID = event.params.accountID;
var name = JSON.stringify(event.data.val()).replace(/['"]+/g, '');
console.log("New Account Added ("+accountID+")");
console.log("Nickname: " +name);
function callback(err, res, data) {
var data = JSON.parse(body);
console.log(data);
validate.validateThis(data)
}
influencer.getIG(name, callback);
});
}
</pre></code>
then in the other file
influencer.js
module.exports = {
getIG: function (name, callback) {
var url = "https://www.instagram.com/"+name+"/?__a=1"
request({
url: url
}, callback)
}
}
This way the asynchronous function runs inside of influencer, and then calls back to the user when the result is done. Data is now in scope for the user file to utilize.
The alternative (and better) way is to use promises. In that case the user code would be along the lines of
influencer.getIg(name).then(data => //use data here in user.js//)
I have written a Javascript Function
jQuery(document).ready( function newbie($) {
//var email = 'emailaddress'
var data = {
action: 'test_response',
post_var: email
};
// the_ajax_script.ajaxurl is a variable that will contain the url to the ajax processing file
$.post(the_ajax_script.ajaxurl, data, function(response) {
alert(response);
});
return false;
});
Which I will call using
newbie();
But I want to pass in a variable (the email address) when I call the function but I am not sure how to do this. That $ sign seems to get in my way! Any thoughts much appreciated.
jQuery(document).ready(function(){
var email = 'emailaddress';
newbie(email);
});
function newbie(email) {
var data = {
action: 'test_response',
post_var: email
};
// the_ajax_script.ajaxurl is a variable that will contain the url to the ajax processing file
$.post(the_ajax_script.ajaxurl, data, function(response) {
alert(response);
});
return false;
}
OR
jQuery(document).ready(function(){
var newbie = function(email) {
var data = {
action: 'test_response',
post_var: email
};
// the_ajax_script.ajaxurl is a variable that will contain the url to the ajax processing file
$.post(the_ajax_script.ajaxurl, data, function(response) {
alert(response);
});
return false;
}
var email = 'emailaddress';
newbie(email);
});
Functions in javascript take 'arguments'. You can pass in as many arguments you want and define their name space in the function declaration. ie
function foo(bar,baz,etc){
console.log(bar,baz,etc);
}
foo(1,2,3)
//logs out 1 2 3
Sometimes you don't always know what's going to be passed in or how many arguments there are going to be, in this case inside of the function declaration we can use the 'arguments' object to pick out certain arguments passed into the function.
function foo(){
console.log(arguments);
}
foo(1,2,3)
//logs out an array object that looks like this [1,2,3]
jQuery(document).ready( function newbie($, email) {
//var email = 'emailaddress'
var data = {
action: 'test_response',
post_var: email
};
// the_ajax_script.ajaxurl is a variable that will contain the url to the ajax processing file
$.post(the_ajax_script.ajaxurl, data, function(response) {
alert(response);
});
return false;
});
you simply call the function by passing the values
I have a function which does a fetch, it returns successful and sets the data.
But I can't work out how to get the data out of the model again.
fetchAcceptedTerms: function () {
var self = this;
this.appAcceptedTerms = new T1AppAcceptedTerms();
this.acceptedTerms = new AppAcceptedTerms();
this.acceptedTerms.fetch({
success: function (data) {
console.log(data);
if (data.meta.status === 'success') {
self.appAcceptedTerms.set(data.data);
}
}
});
console.log(self.appAcceptedTerms);
console.log(self.appAcceptedTerms.attributes);
},
See output in console:
http://s32.postimg.org/ssi3w7wed/Screen_Shot_2016_05_20_at_14_17_21.png
As you can see:
console.log(data); returns the data as expected
console.log(self.appAcceptedTerms); the data is set correctly as we can see it in the log
console.log(self.appAcceptedTerms.attributes); isn't working properly and returns Object {}
Can someone help on how to get all of the attributes out?
Thanks
The fetch operation is asynchronous, so you need to check for your attributes after the fetch operation has completed. Does the below output your attributes as expected?
fetchAcceptedTerms: function () {
var self = this;
this.appAcceptedTerms = new T1AppAcceptedTerms();
this.acceptedTerms = new AppAcceptedTerms();
this.acceptedTerms.fetch({
success: function (data) {
console.log(data);
if (data.meta.status === 'success') {
self.appAcceptedTerms.set(data.data);
console.log(self.appAcceptedTerms);
console.log(self.appAcceptedTerms.attributes);
}
}
});
}
I have a function like this:
jQuery.fn.stickyNotes.createNote = function(root) {
var record_no;
$.get(root+"/blocks/stickynotes/max_records.php", function(resp) {
alert(resp);
record_no=resp;
})
var note_stickyid = record_no;
...
}
The max_record.php looks like this:
<?php
require_once('../../config.php');
global $DB;
$max_id = $DB->get_record_sql('
SELECT max(stickyid) as max_id
FROM mdl_block_stickynotes
');
$stickyid= $max_id->max_id+1;
echo $stickyid;
?>
I wondering why records_no has no value in it, while resp is showing right value in alert.
This line is your problem:
var note_stickyid = record_no;
The $.get() function above it is asynchronous, so it's trying to assign this value before the function has completed. Assign the variable inside the callback:
var note_stickyid;
$.get(root+"/blocks/stickynotes/max_records.php", function(resp) {
alert(resp);
record_no=resp;
note_stickyid = record_no;
}).done(function() {
alert(note_stickyid); //Works because it waits until the request is done
});
alert(note_stickyid); //This will alert null, because it triggers before the function has assigned!
In your case, you'll probably want to pass in a callback function so you can actually use this variable, here's a sample callback function:
function callback(param) {
alert(param);
}
Now setup another parameter for your createNote:
jQuery.fn.stickyNotes.createNote = function(root, callback) {
Now use that callback inside the $.get:
var note_stickyid;
$.get(root+"/blocks/stickynotes/max_records.php", function(resp) {
alert(resp);
record_no=resp;
note_stickyid = record_no;
callback(note_stickyid);
});
Try this:
var record_no= '';
$.get(root+"/blocks/stickynotes/max_records.php", function(resp) {
alert(resp);
record_no+=resp;
})
I am trying to do 2 ajax function calls when a user clicks a button.
I have
$('.test').on('click', function(){
code.getCode();
code.getText();
})
code.prototype.getCode=function(){
var call=//call ajax
call.callback= function(data){
//parse return data
}
}
code.prototype.getText=function(){
var call=//call ajax
call.callback= function(data){
//parse return data
}
}
I can only do 1 ajax call and only 1 ajax call will return data.
I am not sure how to solve this. Any ideas? Thanks a lot!
I am not sure if I understood correctly, but I think you are looking for a single callback from both the ajax calls..
You should use $.when.done. See below,
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2){
/* a1 and a2 are arguments resolved for the
page1 and page2 ajax requests, respectively */
var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
if ( /Whip It/.test(jqXHR.responseText) ) {
alert("First page has 'Whip It' somewhere.");
}
});
Not sure if you looking for sequencing it or trying to have 1 callback.
You could also have the first ajax call, call the second on success:
$('.test').on('click', function(){
var datastr = "your data";
$.ajax({
type: "POST",
url: "url",
data: datastr,
success: function(successMsg) {
//ajax done
if (/* not yet complete */) {
setTimeout(secondAjaxCall(),500);
} else {
secondAjaxCall();
}
}
});
});
You could just save each return in the code object (since you are in a different context you have to work around "this"). Then you can use a third function that checks if the data objects are loaded... and start parsing once both are there.
$('.test').on('click', function(){
code.getCode();
code.getText();
})
code.prototype.getCode=function(){
var call=//call ajax
var that = this;
call.callback= function(data){
//parse return data
that.codeData = data;
parseData();
}
}
code.prototype.getText=function(){
var call=//call ajax
var that = this;
call.callback= function(data){
//parse return data
that.textData = data;
parseData();
}
}
function parseData() {
if(!code.textData || !code.codeData) return;
... work with both
}