Javascript AJAX scope inside of $.each Scope - javascript

So I am trying to loop through some elements and change some text based on the result of an ajax call. the problem is I cannot get the data out of the ajax callback and I am not sure how exactly to chain the events to do so. I am getting a stock quote value it would be nice if I could just return that object up into the previous scope, the loop of matches, and then do all the manipulation there.
$(function(){
var tweets = $('.tweet');
var symbol_pat = /(^|\s\$)([a-z]+\b)/gi;
$.each(tweets, function(){
var tweet_html = $(this).html();
tweet_html = tweet_html.replace(symbol_pat,function(){
var symbol = arguments[2];
var YAHOO_API_URL = 'http://query.yahooapis.com/v1/public/yql'
var format = 'json'
var query = 'select * from yahoo.finance.quotes where symbol in ("'+symbol+'")';
var env = "store://datatables.org/alltableswithkeys";
$.ajax({
'url':YAHOO_API_URL,
'async':false,
'method':'GET',
'data': {
'format':format,
'q':query,
'env':env
},
success: function(data){
var quote = data.query.results.quote;
var change = quote.Change;
var change_pct = quote.ChangeinPercent;
var quote_price = quote.LastTradePriceOnly;
var html_str = "";
if( change.indexOf("+") != -1 ){
html_str = '<span class="symWrap up">'+arguments[0]+'</span>';
}else{
html_str = '<span class="symWrap down">'+arguments[0]+'</span>';
}
tweet_html = arguments[0].replace(html_str);
$(this).html(tweet_html);
}
});
});
});
});

$.ajax() runs asynchronously, so you can't really "wait" for the success in the previous scope. You can use jQuery promise and Deferred to do this though. Check out http://www.erichynds.com/jquery/using-deferreds-in-jquery/ and http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/
EDIT:
showing an alternate solution that doesn't require promise or deferred:
$(function(){
var tweets = $('.tweet');
var symbol_pat = /(^|\s\$)([a-z]+\b)/gi;
$.each(tweets, function(){
var that = this;
var symbol = arguments[2];
var YAHOO_API_URL = 'http://query.yahooapis.com/v1/public/yql'
var format = 'json'
var query = 'select * from yahoo.finance.quotes where symbol in ("'+symbol+'")';
var env = "store://datatables.org/alltableswithkeys";
$.ajax({
'url':YAHOO_API_URL,
'async':false,
'method':'GET',
'data': {
'format':format,
'q':query,
'env':env
},
success: function(data){
var quote = data.query.results.quote;
var change = quote.Change;
var change_pct = quote.ChangeinPercent;
var quote_price = quote.LastTradePriceOnly;
var html_str = "";
if( change.indexOf("+") != -1 ){
html_str = '<span class="symWrap up">'+arguments[0]+'</span>';
}else{
html_str = '<span class="symWrap down">'+arguments[0]+'</span>';
}
var tweet_html = $(that).html();
var tweet_html = arguments[0].replace(html_str);
tweet_html = tweet_html.replace(symbol_pat,html_str);
$(that).html(tweet_html);
}
});
});
});
});

so long as your replace code is correct, I believe the following rework of your code should work (or at least get you darn close, as this is untested and depends on the rest of your code):
$(function(){
var YAHOO_API_URL = 'http://query.yahooapis.com/v1/public/yql'
var tweets = $('.tweet');
var symbol_pat = /(^|\s\$)([a-z]+\b)/gi;
$.each(tweets, function(){
var tweet_html = $(this).html();
tweet_html = tweet_html.replace(symbol_pat, function(){
var symbol = arguments[2];
var format = 'json'
var query = 'select * from yahoo.finance.quotes where symbol in ("'+symbol+'")';
var env = "store://datatables.org/alltableswithkeys";
var quoteHtml = getQuote(format, query, env, function(quote) {
var change = quote.Change;
var change_pct = quote.ChangeinPercent;
var quote_price = quote.LastTradePriceOnly;
var html_str = "";
if( change.indexOf("+") != -1 ){
html_str = '<span class="symWrap up">'+arguments[0]+'</span>';
}
else{
html_str = '<span class="symWrap down">'+arguments[0]+'</span>';
}
return arguments[0].replace(html_str);
});
return quoteHtml;
});
$(this).html(tweet_html);
});
var getQuote = function(format, query, env, successCallback) {
$.ajax({
'url':YAHOO_API_URL,
'async':false,
'method':'GET',
'data': {
'format': format,
'q': query,
'env': env
},
success: function(data){
var quote = data.query.results.quote;
if(successCallback !== undefined && typeof successCallback == 'function') {
successCallback(quote);
}
}
});
};
});

Related

How to pass a JavaScript variable to XML?

I want to pass JavaScript variable's value to an XML file. I have already seen this question and answer here but since my XML file is not that small but rather big, I would like to know how to do this without writing whole xml if possible.
I have this JavaScript code
render_receipt: function () {
// this._super();
var self = this;
if (self.pos.config.disable_fiscalization == false) {
var data = self.get_receipt_render_env();
self.$('.pos-receipt-container').html("")
var total_amount = data['receipt']['total_with_tax'];
var vat = self.pos['company']['vat'];
var header_time = data['order']['formatted_validation_date'];
var order_name = data['order']['name'];
var soft_code = self.pos['company']['software_code'];
var business_unit_code = self.pos['config']['business_unit_code'];
var business_unit_address = self.pos.business_unit_address
var tcr_code = self.pos['config']['tcr_code'];
var operator_code = self.pos.get_cashier().operator_code
// create message
message = vat + '|' + header_time + '|' + order_name + '|' + business_unit_code + '|' + tcr_code + '|' + soft_code + '|' + total_amount
var order = self.pos.get_order();
if (!this.pos.config.iface_print_via_proxy) {
var invoiced = new $.Deferred();
// if (self.pos.config.disable_fiscalization == false) {
// console.log("hasEnoughSpeed", hasEnoughSpeed, isAlive)
if (isAlive && hasEnoughSpeed) {
rpc.query({
model: 'pos.order',
method: 'search_read',
domain: [['pos_reference', '=', order['name']]],
fields: ['iic_code', 'header_send_datetime', 'amount_total', 'fic', 'business_unit_code', 'operator_code', 'fiscalization_url', 'partner_id']
})
.then(function (orders) {
var partner = null;
if (orders.length && orders[0]['partner_id'] == false) {
var data = self.get_receipt_render_env();
data['partner_name'] = orders[0]['partner_id'][1];
data['street'] = false;
data['country'] = false;
data['city'] = false;
data['zip'] = false;
data['vat'] = false;
data['nslf'] = orders[0]['iic_code'];
// alert(data['nslf'])
data['nivf'] = orders[0]['fic'];
data['business_unit_code'] = business_unit_code;
data['operator_code'] = operator_code;
data['business_unit_address'] = business_unit_address
self.$('.pos-receipt-container').html(qweb.render('PosTicket', data));
var qr = new QRious({
element: document.getElementById('qr-code'),
size: 200,
});
I'd like to pass data['nsfl'] to this XML div tag. I have already tried as you see and it is failing, I get why it is failing and from the other side I don't know how to make work either. Thanks in advance guys!!!
<div>
<div style="font-weight:bold;font-size:12px;">NSLF: <t t-esc="data['nslf']"/></div>
</div>

ajax call returning null

I have this small script (fiddle) in charged for reading some blog XML. The problem is that it simply stopped working a few days ago. It seems the Ajax function is always returning null, even though there is data in the specified URL.
<script>
var toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
var buildRSS = function (container_id){
$.ajax({
type: "GET",
url: "http://bloginstructions.blogspot.dk/rss.xml",
dataType: "xml",
success: function(result){
var values = getEntries(result)
console.log(result)
for (var i = 0; i < 10; i++) {
var entry = values[i],
info = entry.__text.split("\n"),
title = info[0],
link = info[1],
date = entry.pubdate.match(/(.*) \d/)[1],
snippet = entry.description.replace(/<\/?[^>]+(>|$)/g, "").substring(0,350)+'...';
var html = '<div><h4>' + title + '</h4><p>' + date + '</p><p>' + snippet + '</p></div>'
$('#' + container_id).append(html)
}
}
})
}
function getEntries(rawXML){
var x2js = new X2JS();
console.log(rawXML);
var xml = rawXML.responseText;
match = xml.match(/<item>(.*)<\/item>/);
xml = match[0] || '';
var json = x2js.xml_str2json(xml);
json = json.rss.channel.item;
return json
}
</script>
<div id="rssfeed">
</div>
<div id="rss">
</div>
<script>
$(document).ready(function() {
buildRSS('rssfeed')
});
</script>

why my array is undefined in my savetime function but running properly in other functions?

i m calling my save function and st_bookmark and ed_bookmark array donot show any data in my JSON stringfy function the array is undefined or uncaught type error occur
<script>
var check = true;
var st_bookmark = new Array();
var str_print = new Array();
var end_print = new Array();
var ed_bookmark = new Array();
</script>
<script>
function save() {
var link = "M7lc1UVf-VE";
var bk_name = $('#bookmark_name').val();
var bk_tags = $('#bookmark_tags').val();
var bk_email = $('#bookmark_email').val();
var user = '#Session["email"]';
var t = st_bookmark.pop();
var ss = ed_bookmark.pop();
var data =
({ name: bk_name, tags: bk_tags, email: bk_email, link: link, start_bookmark: st_bookmark, end_bookmark: ed_bookmark });
$.ajax({
url: '#Url.Action("save_bookmark", "chopaal")',
type: "POST",
contentType: "application/json",
data: { data: data },
success: function () {
window.alert('success!!');
}
});
var check = true;
var st_bookmark = [];
var str_print = [];
var end_print = [];
var ed_bookmark = [];
}
function starttime() {
if (check == true) {
temp = player.getCurrentTime();
st_bookmark.push(temp);
str_print.push((temp / 60).toFixed(2));
document.getElementById("str_book").innerHTML = str_print;
check = false;
} else {
window.alert("Please End The Previous Bookmark");
}
}
function endtime() {
if (check == false) {
temp = player.getCurrentTime();
ed_bookmark.push(temp);
end_print.push((temp / 60).toFixed(2));
document.getElementById("end_book").innerHTML = end_print;
check = true;
} else {
window.alert("Please Add the Starting Bookmark");
}
}
</script>
Variable declarations are hoisted in JavaScript:
var data = {start_bookmark: st_bookmark};
var st_bookmark = [];
is equivalent to
var data;
var st_bookmark;
data = {start_bookmark: st_bookmark};
st_bookmark = [];
As you can see, st_bookmark is accessed before it got a value assignment, at which point its value is still undefined.
I guess what you really want is to access the variables with the same name that are declared globally. In that case, you should completely remove the declarations of these similarly named variables from save.
If you want to "reset" those variables after the Ajax call was successful, you need to move the assignment inside the success callback and remove the var keyword (so that the identifiers refer to the global variables):
success: function() {
window.alert('success!!');
check = true;
st_bookmark = [];
str_print = [];
end_print = [];
ed_bookmark = [];
}

Javascript hoisting issue-first and second debug return different value

i tried to run a script for developing an add-on. Somehow, the first run will return undefined and only the second run will obtain the result i desire. I searched through and realised it might be something related with hoisting. Any ideas on this? Thanks.
var array1=[];
var array2=[];
var arrayPDS=[];
var arrayPD=[];
var suggPD;
function handleClick(state) {
var suggPD = Request({
url: "http://google.com/complete/search?output=toolbar&q=" + primarydomain,
overrideMimeType: "application/xml; charset=latin1",
onComplete: suggPDparse,
}).get();
function suggPDparse(response) {
var {Cc, Ci} = require("chrome");
var parser = Cc["#mozilla.org/xmlextras/domparser;1"].createInstance(Ci.nsIDOMParser);
var xml = parser.parseFromString(response.text, "application/xml");
var pds;
var pd = xml.getElementsByTagName("suggestion");
for (i=1;i<pd.length;i++){
pds = pd[i].getAttribute("data");
array1.push(pds);
arrayPDS = array1[0];
}
function loadXMLDoc(filename, callback){
var req = new XMLHttpRequest();
req.open("GET",filename,true);
req.onreadystatechange = function(){
if(req.readyState === 4){
callback(req.responseXML);
}
}
req.send();
}
loadXMLDoc(self.data.url("pd.xml"), function(xmlDoc){
if (xmlDoc.documentElement.nodeName=="parsererror"){
console.log(xmlDoc.documentElement.childNodes[0].nodeValue);
return(null);
}
var x = xmlDoc.getElementsByTagName("Row");
for (i=0; i<x.length; i++){
var a=x[i];
getV=(a.getElementsByTagName("Field_0")[0].childNodes[0].nodeValue);
array2.push(getV);
}
arrayPD = array2;
});
}
console.log("arrayPD: " + arrayPD);
console.log("arrayPDS: " + arrayPDS);
}
The result for first click will return:
arrayPD:
arrayPDS:
The result for second click will return:
arrayPD:abcd
arrayPDS:abcd

Javascript won't take $_GET value from PHP?

so I'd like to assign a url parameter value to jquery but it won't take it ..
var product_id = '<?php echo $_GET["pID"]; ?>';
my function is below , document ready is included... just posted the relevant stuff
function sendOrderToServer() {
var order = $(".sortable_table").sortable("serialize");
var array_order = order.split("&");
var product_id = '<?php echo $_GET["pID"]; ?>';
alert(product_id);
for (var i=0;i<array_order.length;i++){
var id = array_order[i].split("=");
id = id[1];
var text_field_video = $("#products_video_sm_dynamic_"+ id).val();
var text_field_video_caption = $("#products_video_sm_dynamic_"+ id +"_caption").val();
var text_field_image = $("#products_image_sm_dynamic_"+ id).val();
var text_field_image_caption = $("#products_image_sm_dynamic_"+ id +"_caption").val();
var text_field_video_xl = $("#products_video_xl_dynamic_"+ id).val();
var text_field_video_xl_caption = $("#products_video_xl_dynamic_"+ id +"_caption").val();
var text_field_image_xl = $("#products_image_xl_dynamic_"+ id).val();
if(text_field_video != undefined){
var element = "products_video_sm_dynamic_" + id;
var position = i + 1;
}
if(text_field_image != undefined){
var element = "products_image_sm_dynamic_" + id ;
var position = i + 1;
}
if(text_field_video_xl != undefined){
var element2 = "products_video_xl_dynamic_" + id ;
var position = i + 1;
}
if(text_field_image_xl != undefined){
var element2 = "products_image_xl_dynamic_" + id ;
var position = i + 1;
}
//alert(element);
//alert("position is" + position);
$.ajax({
type:'POST',
url :'includes/insert_database.php',
data:{ position : position, element1:element , element2:element2},
success: function(result){
alert(result);
}
});
}
}
http://example.com/yourpage.php?pID=%27%3B+alert%28%27OMG+I+just+totally+hacked+your+site%21%27%29%3B+%27
Try this instead:
var product_id = <?php echo json_encode($_GET['pID']); ?>

Categories