I have two Jquery function. How do I set the execution order so that function B would only be called after function A, (reason behind is that Function A set a value to a variable IdstoExclude that is getting passed as a parameter to function B.
Below is what i tried but no luck:
var IDstoExclude = "123";
callListService('getArticleTypelistById', 'Atid', 87, 5, '#MainStory', '#tmplFeaturePanel', IDstoExclude);
callListService('getArticleTypelistById', 'Atid', 87, 10, '#LeftSideContent1', '#tmplLeftSideContent1', IDstoExclude);
function callListService(webServiceName, parameterName, parameterValue, noOfItems, domElement, templName, exclIDs) {
//set a default value for the template name * exclIDs
templName = templName || "#FeaturedSubStories";
//exclIDs = exclIDs || "123,12";
var inputParameters = webServiceName.toLowerCase() + ':' + parameterName.toLowerCase() + ':' + parameterValue + ':noofitems:' + noOfItems + ':excludeids:' + exclIDs;
var clientcode = getCryptoToken(inputParameters);
//Build JSONp query
eval("data={" + parameterName.toLowerCase() + ":" + parameterValue + ", noofitems: " + noOfItems + ", excludeids:" + exclIDs + ", clientcode:'" + clientcode + "' }");
$.getJSON('https://abc.com/Service.svc/' + webServiceName + '?callback=?', data, function (data2) {
var template = $.templates(templName);
var htmlOutput = template.render(data2);
$(domElement).append(htmlOutput);
IDstoExclude = data2.IdsInThisList;
});
Tried below but no luck: var IDstoExclude = "123";
function callService1() {
return $.ajax()
.then(function(response) {
callListService('getArticleTypelistById', 'Atid', 87, 10, '#LeftSideContent1', '#tmplLeftSideContent1', IDstoExclude);
});
}
function callService2() {
callListService('getArticleTypelistById', 'Atid', 87, 10, '#LeftSideContent1', '#tmplLeftSideContent1', IDstoExclude)
}
$.when(callService1()).then(callService2);
For this solution to work as you expect your code should look like something below:
function callService1(p1, p2, ...) {
return $.ajax(...)
.then(function(response) {
return something;
});
}
function callService2(something_from_s1) {
// work with something_from_s1 var
}
$.when(callService1(...)).then(callService2);
References:
http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/
http://api.jquery.com/category/deferred-object/
http://api.jquery.com/deferred.then/
Related
Assign value to global tracking variable on submit of form.
var tracking;
$('.form-inline').submit(function (e) {
e.preventDefault();
tracking = jQuery('input[name="tracking"]').val();
init()
})
execute function init()
function init() {
Tabletop.init({
key: public_spreadsheet_url,
callback: showInfo,
simpleSheet: true
})
}
Which initiates the showInfo callback
var zipMatches = "";
function showInfo(data, tabletop) {
alert('Callback initiated..');
for (var i = 0; i < data.length; i++) {
var myRegex = '/' + tracking + '/';
console.log(myRegex)
if (myRegex.test(data[i].tracking)) {
zipMatches = zipMatches + data[i].location_1 + ", " + data[i].location_2 + ", " + data[i].location_3;
}
}
//write it into the DOM
var myElement = document.querySelector(".myJSON");
myElement.innerHTML = "<h3>List of Zipcodes that match tracking ID: </h3><p>" + zipMatches + "</p>";
}
myRegex.test is not a function
However regex function works with hardcoded value
if (/ABCD123/.test(data[i].tracking)) {...
How do I pass the regex value as a global variable?
..
Edit (working callback function):
function showInfo(data, tabletop) {
var regexp = new RegExp(tracking);
for (var i = 0; i < data.length; i++) {
if (regexp.test(data[i].tracking)) {
zipMatches = zipMatches + data[i].location_1 + ", " + data[i].location_2 + ", " + data[i].location_3;
}
}..
Plese try with following sol:
var regexp = new RegExp(tracking);
and please put it outside of forloop. So it is optimized.
Since you have tried
var regexp = "/" + tracking + "/"; will convert it into string. Not regex object. So you won't get test method in it.
Hope it helps :)
if have javascript:
function calculateValues(callback)
{
window.external.getHistoryRange(0,1,"",function(res){
var hist = eval(res);
histCount = hist.historyCount;
hist = hist.historyContent;
if (histCount == 0)
{
return;
}
$("#history_table").show();
var $row = addAlertHistoryRow(hist[0]);
var rowHeight = $row.height();
pageItemsCount = Math.floor(contentHeight / rowHeight);
curPageNum = 0;
$row.remove();
if (callback) callback();
});
}
in function calculateValues(callback) callback parameter is:
function(){statItempos = 0; gethistoryandshow(pageNum,startItemsPos,callback);}
and c# code, that works with that script (ObjectForScripting):
public string getHistoryRange(string strVar0 = "", string strVar1 = "", string strVar2 = "", string strVar3 = "")
{
string res = "";
using (DeskAlertsDbContext db = new DeskAlertsDbContext())
{
var alerts = db.HistoryAlerts.OrderBy(a => a.ReciveTime)
.Include(b => b.alert.WINDOW)
.ToList();
foreach (var alert in alerts)
{
res += ("{\"id\":" + System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Alert_id) +
",\"date\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(
alert.ReciveTime.ToString(CultureInfo.InvariantCulture)) + "\",\"alert\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alerttext) + "\",\"title\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Title) + "\",\"acknow\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Acknown) + "\",\"create\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Create_date) + "\",\"class\":\"" +
"1" + "\",\"urgent\":\"" + System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Urgent) +
"\",\"unread\":\"" + Convert.ToInt32(alert.isclosed).ToString() + "\",\"position\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Position) + "\",\"ticker\":\"" +
alert.alert.Ticker + "\",\"to_date\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.To_date) + "\"},");
}
res = res.TrimEnd(','); //trim right ","
res = "({\"historyCount\":" + alerts.Count.ToString() + ",\"historyContent\":[" + res + "]});";
Browserwindow.Wb.InvokeScript("eval", new object[] { strVar3 });
Browserwindow.Wb.InvokeScript("CallbackFunction", new object[] { res });
return res;
}
}
On string: "Browserwindow.Wb.InvokeScript("eval", new object[] { strVar3 });"
I try to call anonymous function from javascript and have an error.
Question is: how to make this logic. How to perform the JS function of the parameters a different function. And then continue JS. If i tryed to give name to function, and invoke it, function works, but global context(if (callback) callback();) becomes unavailible
Your callback function name is not correct.
Replace
Browserwindow.Wb.InvokeScript("CallbackFunction", new object[] { res });
With
Browserwindow.Wb.InvokeScript("calculateValues", new object[] { res });
Hmmm... Just maked my variable dynamic (not string), and all worked
public string getHistoryRange(string strVar0 = "", string strVar1 = "", string strVar2 = "", dynamic strVar3 = null)
{
string res = "";
using (DeskAlertsDbContext db = new DeskAlertsDbContext())
{
var alerts = db.HistoryAlerts.OrderBy(a => a.ReciveTime)
.Include(b => b.alert.WINDOW)
.ToList();
foreach (var alert in alerts)
{
res += ("{\"id\":" + System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Alert_id) +
",\"date\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(
alert.ReciveTime.ToString(CultureInfo.InvariantCulture)) + "\",\"alert\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alerttext) + "\",\"title\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Title) + "\",\"acknow\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Acknown) + "\",\"create\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Create_date) + "\",\"class\":\"" +
"1" + "\",\"urgent\":\"" + System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Urgent) +
"\",\"unread\":\"" + Convert.ToInt32(alert.isclosed).ToString() + "\",\"position\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Position) + "\",\"ticker\":\"" +
alert.alert.Ticker + "\",\"to_date\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.To_date) + "\"},");
}
res = res.TrimEnd(','); //trim right ","
res = "({\"historyCount\":" + alerts.Count.ToString() + ",\"historyContent\":[" + res + "]});";
dynamic variable = Browserwindow.Wb.InvokeScript("eval", new object[] { strVar3 });
variable(res);
return res;
}
}
I created this function to replace value in a string and call functions whose name is the value.
$(function() {
var str = "Homer drank {{countBeers}} beers";
function countBeers() {
console.log(this);
return 10 + 10;
}
function convert(str) {
console.log(this);
str = "'" + str.replace(/{{(.*?)}}/g, "' + $1.call(this) + '") + "'";
OR
str = "'" + str.replace(/{{(.*?)}}/g, "' + $1(this) + '") + "'";
return eval(str);
}
var output = convert.call(this, str);
$('body').append(output); //Homer drank 20 beers
});
This seems to work fine, but I would not use eval.
You can do it any other way?
Thank you
You could use an object with the function.
function convert(str) {
return str.replace(/{{(.*?)}}/g, function (_, f) {
return op[f] ? op[f]() : f;
});
}
var str = "Homer drank {{countBeers}} beers",
op = { countBeers: function () { return 10 + 10; } };
console.log(convert(str));
Why the undefined gets outputted instead of the object properties.
Created a function, defined setters for the parameters and function to output the string consisting of the parameters.
Below is the snippet for the app.js file.
// app.js
function Fruit(theColor, sweetness, theName, theOrigin) {
//properties
this.theColor = theColor;
this.sweetness = sweetness;
this.theName = theName;
this.theOrigin = theOrigin;
//functions
this.showName = function () {
console.log("This is a " + this.theName);
};
this.showLand = function () {
this.theOrigin.forEach(function (arg) {
console.log("Grown in: " + arg);
});
};
}
var mango = new Fruit("Yellow", 9, "Mango", ["India", "Central America"]);
console.log(mango.showName() + " " + mango.showLand());
This line:
console.log(mango.showName() + " " + mango.showLand());
calls those functions, then outputs their return values with a space between them. Neither showNames nor showLand returns anything, and so calling them gives you the result undefined.
If you just want to call those, just call them, without using console.log to output their result. E.g., replace:
console.log(mango.showName() + " " + mango.showLand());
with
mango.showName();
mango.showLand();
If you want them to return, rather than display, their result, edit them to do so. You'll have to decide how you want showLand to separate lines (e.g., with a \n, or by returning an array, etc.).
For instance, this showName will return a string, and showLand will return an array:
//functions
this.showName = function () {
return "This is a " + this.theName;
};
this.showLand = function () {
return this.theOrigin.map(function (arg) {
return "Grown in: " + arg;
});
};
which you could then call like this:
console.log(mango.showName() + ". " + mango.showLand().join(", "));
Live Example:
function Fruit(theColor, sweetness, theName, theOrigin) {
//properties
this.theColor = theColor;
this.sweetness = sweetness;
this.theName = theName;
this.theOrigin = theOrigin;
//functions
this.showName = function () {
return "This is a " + this.theName;
};
this.showLand = function () {
return this.theOrigin.map(function (arg) {
return "Grown in: " + arg;
});
};
}
var mango = new Fruit("Yellow", 9, "Mango", ["India", "Central America"]);
console.log(mango.showName() + ". " + mango.showLand().join(", "));
I am trying get paged json responses from Topsy (http://code.google.com/p/otterapi/) and am having problems merging the objects. I want to do this in browser as the api rate limit is per ip/user and to low to do things server side.
Here is my code. Is there a better way? Of course there is because this doesn't work. I guess I want to get this working, but also to understand if there is a safer, and/or more efficient way.
The error message I get is ...
TypeError: Result of expression 'window.holdtweetslist.prototype' [undefined] is not an object.
Thanks in advance.
Cheers
Stephen
$("#gettweets").live('click', function(event){
event.preventDefault();
getTweets('stephenbaugh');
});
function getTweets(name) {
var MAX_TWEETS = 500;
var TWEETSPERPAGE = 50;
var BASE = 'http://otter.topsy.com/search.json?type=tweet&perpage=' + TWEETSPERPAGE + '&window=a&nohidden=0&q=#' + name + '&page=1';
var currentpage = 1;
alert(BASE);
$.ajax({
dataType: "json",
url: BASE,
success: function(data) {
window.responcesreceived = 1;
var response=data.response;
alert(response.total);
window.totalweets = response.total;
window.pagestoget = Math.ceil(window.totalweets/window.TWEETSPERPAGE);
window.holdtweetslist = response.list;
window.holdtweetslist.prototype.Merge = (function (ob) {var o = this;var i = 0;for (var z in ob) {if (ob.hasOwnProperty(z)) {o[z] = ob[z];}}return o;});
// alert(data);
;; gotTweets(data);
var loopcounter = 1;
do
{
currentpage = currentpage + 1;
pausecomp(1500);
var BASE = 'http://otter.topsy.com/search.json?type=tweet&perpage=' + TWEETSPERPAGE + '&window=a&nohidden=0&q=#' + name + '&page=' + currentpage;
alert(BASE);
$.ajax({dataType: "json", url: BASE, success: gotTweets(data)});
}
while (currentpage<pagestoget);
}
});
};
function gotTweets(data)
{
window.responcesreceived = window.responcesreceived + 1;
var response = data.response;
alert(response.total);
window.holdtweetslist.Merge(response.list);
window.tweetsfound = window.tweetsfound + response.total;
if (window.responcesreceived == window.pagestoget) {
// sendforprocessingsendtweetlist();
alert(window.tweetsfound);
}
}
You are calling Merge as an static method, but declared it as an "instance" method (for the prototype reserved word).
Remove prototype from Merge declaration, so you'll have:
window.holdtweetslist.Merge = (function(ob)...
This will fix the javascript error.
This is Vipul from Topsy. Would you share the literal JSON you are receiving? I want to ensure you are not receiving a broken response.
THanks to Edgar and Vipul for there help. Unfortunately they were able to answer my questions. I have managed to work out that the issue was a combination of jquery not parsing the json properly and needing to use jsonp with topsy.
Here is a little test I created that works.
Create a doc with this object on it ....
RUN TEST
You will need JQUERY
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
And put the following in a script too. The is cycle through the required number of tweets from Topsy.
Thanks again everyone.
$("#gettweets").live('click', function(event){
event.preventDefault();
getTweets('stephenbaugh');
});
var MAX_TWEETS = 500;
var TWEETSPERPAGE = 50;
var BASE = 'http://otter.topsy.com/search.json';
var currentpage;
var responcesreceived;
var totalweets;
var pagestoget;
var totalweets;
var TWEETSPERPAGE;
var holdtweetslist = [];
var requestssent;
var responcesreceived;
var tweetsfound;
var nametoget;
function getTweets(name) {
nametoget=name;
currentpage = 1;
responcesreceived = 0;
pagestoget = 0;
var BASE = 'http://otter.topsy.com/search.js?type=tweet&perpage=' + TWEETSPERPAGE + '&window=a&nohidden=0&q=#' + nametoget + '&page=1';
$('#gettweets').html(BASE);
$.ajax({url: BASE,
dataType: 'jsonp',
success : function(data) {
getalltweets(data);
}
});
};
function getalltweets(data) {
totalweets = data.response.total;
$('#gettweets').append('<p>'+"total tweets " + totalweets+'</p>');
$('#gettweets').append('<p>'+"max tweets " + MAX_TWEETS+'</p>');
if (MAX_TWEETS < totalweets) {
totalweets = 500
}
$('#gettweets').append('<p>'+"new total tweets " + totalweets+'</p>');
gotTweets(data);
pagestoget = Math.ceil(totalweets/TWEETSPERPAGE);
var getpagesint = self.setInterval(function() {
currentpage = ++currentpage;
var BASE = 'http://otter.topsy.com/search.js?type=tweet&perpage=' + TWEETSPERPAGE + '&window=a&nohidden=0&q=#' + nametoget + '&page=' + currentpage;
$.ajax({url: BASE,
dataType: 'jsonp',
success : function(data) {
gotTweets(data);
}
});
if (currentpage == pagestoget) {
$('#gettweets').append('<p>'+"finished sending " + currentpage+ ' of ' + pagestoget + '</p>');
clearInterval(getpagesint);
};
}, 2000);
};
function gotTweets(data)
{
responcesreceived = responcesreceived + 1;
holdlist = data.response.list;
for (x in holdlist)
{
holdtweetslist.push(holdlist[x]);
}
// var family = parents.concat(children);
$('#gettweets').append('<p>receipt # ' + responcesreceived+' - is page : ' +data.response.page+ ' array length = ' + holdtweetslist.length +'</p>');
// holdtweetslist.Merge(response.list);
tweetsfound = tweetsfound + data.response.total;
if (responcesreceived == pagestoget) {
// sendforprocessingsendtweetlist();
$('#gettweets').append('<p>'+"finished receiving " + responcesreceived + ' of ' + pagestoget + '</p>');
}
}