Affichage des articles dont le libellé est Active questions tagged javascript - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged javascript - Stack Overflow. Afficher tous les articles

jeudi 26 mars 2015

Error in query: Invalid JSON string when Creating a Chart from a Spreadsheet? GAS


Why am I getting the error Error in query: Invalid JSON string when attempting to create a chart from a spreadsheet using the Google example script from their documentation here?


I can't figure it out. The only thing that I changed is the spreadsheet URL. The rest is directly from the documentation example. I provided all of my code below. Any help you guys could give would be greatly appreciated. Thanks, Brandon





function doGet() {
return HtmlService.createTemplateFromFile('index')
.evaluate()
.setSandboxMode(HtmlService.SandboxMode.NATIVE);
};

function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
};






<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="http://ift.tt/JuZcy0"></script>
<script type="text/javascript">

// Load the Visualization API and the controls package.
google.load("visualization", '1', {packages:['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var query = new google.visualization.Query(
'http://ift.tt/1M0dNkF');
query.send(handleQueryResponse);
}

function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}

var data = response.getDataTable();
var chart = new google.visualization.ColumnChart(document.getElementById('columnchart'));
chart.draw(data, { legend: { position: 'none' } });
}
</script>

<title>Data from a Spreadsheet</title>
</head>

<body>
<span id='columnchart'></span>
</body>
</html>






<div id="EntireSite">

<div>
<?!= include('Chart'); ?>
</div>



enter image description here



ng-click to call a function in services for logging ratings onto firebase


I am creating a website which logs user ratings to firebase, but I cannot accomplish the calling of a services.js function which is meant to log the user's rating on click of one of stars 1-5. Is there something wrong with my code, or something I am missing? Here is a snippet of the services.js, controllers.js, as well as the ratings div from the html. Any help is much appreciated!


From the services.js



angular.module('dev.services', [])
.factory('ratingsService', function() {
return {
//removed return envelope
//var obj = {};
/**
* @todo Add a check to determine whether or not the specified user has already rated the specified item.
*
* @param {String} userId
* @param {String} itemType
* @param {String} itemId
* @param {Number} rating
*/
rate: function(userId, itemType, itemId, rating) {
// @todo Construct a new promise that resolves when both Firebase operations have been performed.
$firebase( new Firebase(dvUrl + '/users/' + userId + '/ratings/' + itemType + '/' + itemId) ).$set(rating);
$firebase( new Firebase(dvUrl + '/' + itemType + '/' + itemId + '/ratings/' + userId) ).$set(rating);
console.log("SUCCESS!");
},
/**
* @param {Object} ratings
* @returns {Number} avgRating
*/
getAvgRating: function(ratings) {
var ratingsTotal = 0;
var ratingsCount = this.getRatingsCount(ratings);

if(ratingsCount === 0) {
return 0;
} else {
for(var rating in ratings) {
if( ratings.hasOwnProperty(rating) ) {
ratingsTotal += parseFloat(ratings[rating]);
}
}

return (ratingsTotal / ratingsCount).toFixed(1);
}
},
/**
* @param {Object} ratings
* @returns {Number} ratingsCount
*/
getRatingsCount: function(ratings) {
return ratings == null
? 0
: Object.keys(ratings).length;
}
//removed return envelope
//return obj;
}
})


From the controllers.js



angular.module('DeViine.controllers', [])
.controller('rateCtrl', ['$scope', 'ratingsService', 'dvUrl', function($scope, ratingsService) {
$scope.rate = function (item, rating) {
ratingsService.rate(userId, item.type, item.id, rating);
}
}]);


From the HTML



<div class="ratings">
<div ng-click="rate(itemId, 1)" class="rate rate1" title="1"></div>
<div ng-click="rate(itemId, 2)" class="rate rate2" title="2"></div>
<div ng-click="rate(itemId, 3)" class="rate rate3" title="3"></div>
<div ng-click="rate(itemId, 4)" class="rate rate4" title="4"></div>
<div ng-click="rate(itemId, 5)" class="rate rate5" title="5"></div>
</div>




Knockoutjs - Template with dynamic variables


I'm learning javascript and ko by trying my hand at a character sheet for my favorite tabletop rpg. Since this is day 3, I'm not even sure I'm approaching this correctly, but below is my attempt at producing a form for skills. It produces no errors, but also has zero functionality.


The evals are my attempt to produce a reference to other observables/computed observables, but no luck. The $data part of the eval was a later addition of an interpretation of advice on how to correct the problem.



<script type="text/html" id="skills-template">
<div data-bind="template: { name: 'skills-template', foreach: skills }"></div>
<div class="row">
<div class="col-md-1" data-bind="text: skill"></div>
<div class="col-md-1"><strong data-bind="text: eval('$data.' + skill + 'Total')"></strong></div>
<div class="col-md-1"><input size="2" data-bind="textInput: eval('$data.' + skill + 'Ranks')" /></div>
<div class="col-md-1"><strong data-bind="text: eval('$data.' + skillMod)"></strong></div>
<div class="col-md-1"><input size="2" data-bind="textInput: eval('$data.' + skill + 'Mod')" /></div>
<div class="col-md-1"><strong data-bind="text: untrained"></strong></div>
<div class="col-md-1"><strong>&nbsp;</strong></div>
<div class="col-md-1"><strong>&nbsp;</strong></div>
<div class="col-md-4">&nbsp;</div>
</div>

</script>


For reference, here is the skills obj I created.



self.skills = [
{ skill: 'Acrobatics', skillMod: 'dexMod', untrained: 'Yes', acPenalty: 'Yes' },
{ skill: 'Appraise', skillMod: 'Dex', untrained: 'Yes', acPenalty: 'No' },
{ skill: 'Bluff', skillMod: 'Dex', untrained: 'Yes', acPenalty: 'No' },
{ skill: 'Climb', skillMod: 'Dex', untrained: 'Yes', acPenalty: 'Yes' },
{ skill: 'Craft', skillMod: 'Dex', untrained: 'Yes', acPenalty: 'No' },
{ skill: 'Diplomacy', skillMod: 'Dex', untrained: 'Yes', acPenalty: 'No' }
]


And this is an example of a computed observable I tried.



self.AcrobaticsTotal = ko.computed(function() {
return Number(self.AcrobaticsRanks()) + Number(self.dexMod()) + Number(self.AcrobaticsMod()) + Number(self.AcrobaticsTrained());
}, this);


I can get this all working if I hand code it, but I thought I would do it smartly and avoid typing all 40 skills and all of the associated observables. Thanks for any advice.


edit: I should have been more clear, I'm trying to get the data-bind to be the equivalent of other observables that I've declared. I want eval($data.' + skill + 'Total') to be acrobaticsTotal and have ko act on the acrobaticsTotal observable.





Will this code ever return false?


I'm reviewing some code where the logic looks flawed. I'm not sure if the following code will ever return false because of the if else return flow. My question is, will the following code ever return false, or even throw an error?



function performSearch(e) {
if(e.keyCode === RETURN_KEY_KEYCODE) {
var select = document.getElementById("selectmenusearch");
var selected = select.options[select.selectedIndex].value;
if(selected === 'organisation') {
submitSearchForm('<%= doOrganisationSearchURL %>');
} else {
submitSearchForm('<%= doIndividualSearchURL %>');
}
} else {
return false;
}
return true;
}


So the flow to me looks like



if (this condition is true) {
//execute some code
} else {
return false
}
else return true


NB: I know it would be better to refactor to have only one return statement but it looks to me like there are two else statements.





Backbone save() respond with success


I have a properly configured Backbone Model, but when I run the save method like so:



backbone_model.save(null, {

success: function () { console.log('ok'); },

error : function () { console.log('not ok'); }

});


I have a successful POST request sent (and Backbone request is triggered) to my Node instance which responds with nothing except 200 OK like so:



app.post('/backbone', function (req, res) {
res.send(); // Automatically sends 200 OK
}


But Backbone does not trigger the sync event, and the error callback is executed. I've also tried returning 201 Created, with no success.





Angular: When does app.config get called?


I am creating a chrome extension UI using angular. I want to make it so when the user clicks the icon in the upper right the correct screen appears. If the user is not logged in they should go to the login page. If the user is logged in and in drawing mode then they should go to the drawing screen, if they are logged in and not drawing then they should go to the main menu.


My main problem is checking whether or not they are already in drawing mode. I am sending a message to my content scripts to check whether or not I am in drawing mode, but for some reason this callback is never getting called! Very disappointing. I'm not sure when code in app.config gets called; when does it?


app.js



app.config(function($stateProvider, $urlRouterProvider) {
var rootRef = new Firebase(mysterious_url);
var user = rootRef.getAuth();
chrome.tabs.sendMessage('isInDrawingMode', {action: 'isInDrawingMode'}, function(response) {
if (!user) {
$urlRouterProvider.otherwise('/login');
} else if (response.inDrawingMode) {
$urlRouterProvider.otherwise('/draw');
} else {
$urlRouterProvider.otherwise('/main');
}
});


contentscripts.js



chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse){
// Toggle User Canvas Messages
if ( request.toggle === 'off' ){
// toggleUserCanvasOff();
disableDrawingMode();
sendResponse({confirm:'canvas turned off'});
} else if ( request.toggle === 'on' ){
enableDrawingMode();
// toggleUserCanvasOn();
sendResponse({confirm:'canvas turned on'});

// Initialize toggle status for popup button
} else if ( request.getStatus === true ){
sendResponse({status:toggle});
} else if (request.canvasData) { // new Canvas data
onCanvasData(request.site, request.user, request.data);
} else if (request.erase){
eraseUserCanvas();
} else if (request.changeColor){
lineColor = request.changeColor;
} else if (request.image){
getCurrentUser(function(user){
var userCanvas = $('.'+ user);
addOneTimeClickEvent(userCanvas, addImage, request.image);
});
} else if (request.action) {
sendResponse({inDrawingMode: "true"});
}
}
);




How to change css styling for different lines within a paragraph in javascript


So I have this code that defined a variable called circle, and appended it a title. The title has four lines, first is the country, second is the price, 3rd is the value, and 4th is the gdppc. Now I want to make the gdppc a larger font size than the previous 3 variables. This would require me to style gdppc separately from the others (currently they are all styled by this css called tipsy). However, I don't know how exactly would I do that.



circles.append("title")
.text(function(d) { return d.country + "<br/> " + "Price=" + d.trust
+ ", Value=" + d.business + "<br/> " + d.gdppc; });

$(".circles").tipsy({ gravity:'nw', html: true,});


The idea is probably to make gdppc a separate variable, and style it separately.





Javascript Alert box popup


I have a very simple question. I'm a beginner at Javascript. I was wondering what is the correct method to write a Javascript alert box? Is it along the lines of {alert}?





Are there any triggers for file imports done using browser?


I was under the assumption that the afterSave() or beforeSave() triggers will fire for every new row (object) created when I import a CSV file using the browser. Unfortunately, this doesn't seem to be the case.



So, are there any triggers available for processing newly created objects (rows) when importing files via browser?





Text Duplicating in Meteor?


I'm attempting to make a Meteor app which allows multiple people to edit a body of text concurrently (think Google Docs/Drive).


I figure in order to do this, I need to have a template which just shows the text that's currently in the database, and then whenever the text is modified, it needs to update the text in the database.


I was able to reproduce the same problems from my full app in this minimal reproduction below (designed to be used by a single user instead of multiple, thus swapped from using a Mongo Collection to a Session.)



<body>
{{> hello}}
</body>

<template name="hello">
<pre contentEditable="true">{{text}}</pre>
</template>


(The exact same problem happens if I use a div instead of a pre.)



if (Meteor.isClient) {
Session.setDefault('text', "Edit me!");

Template.hello.helpers({
text: function () {
return Session.get('text');
}
});

Template.hello.events({
"input pre": function (event) {
Session.set('text', $(event.target).text());
}
});
}


Try typing a bit in the application and the bug should pretty quickly be apparent to you: with each keystroke it takes all of the existing text and appends it to what you've typed (so with each keystroke, it duplicates all the text). Here's the really weird part: this behavior doesn't always start immediately... in fact, I haven't found any particularly reliable ways of reproducing it. Once it has duplicated the text a single time, it'll reliably do it again and again with each keystroke, up until you refresh the page. After you refresh the page, sometimes the bug appears again with your next keystroke, other times it can take ~20 keystrokes before it appears.


I've tested this on Safari 8 (both OS X and iOS), Chrome (both OS X and Windows), and Firefox (just OS X) and the issue appears in every browser.


If you haven't been able to reproduce it yet, try highlighting all the text, deleting it, and typing. Also try starting a new line. I find those actions seem to have a higher probability of starting the text duplication, but even those don't consistently start the issue.


My questions are:



  1. Why is this bug occurring?

  2. How can I stop it from occurring?


If you'd like to see the problem first hand without having to run a meteor server (although I gave you everything you all the code already...) I threw it up here.





How to force client reload after deployment?


I'm using the MEAN stack (mongo, express, angular and node). I'm deploying relatively frequently to production...every couple of days. My concern is that I'm changing the client side code and the API at times and I would rather not have to ensure backwards compatibility of the API with previous versions of the client code.


In such a scenario, what is the most effective way of ensuring that all clients reload when I push to production? I have seen that Evernote for example has a pop-up that says something along the lines of please reload your browser for the latest version of Evernote. I would like to do something similiar...do I need to go down the path of socket.io or sock.js or am I missing something simple and there is a simpler way to achieve this?





Anonymous define() module in library's dependencies causes breakage for library's dependents


I'm working on a library that is used in a number of web applications. The library itself does not use RequireJS - it's written in node, and then bundled with browserify - however, some of its dependents are using a RequireJS shim to include the library.


What we've found is that the RequireJS shim used by our dependents breaks with an "mismatched anonymous define()" error, if our library depends on a library that includes an anonymous define module, such as this one from the lodash source:



// Define as an anonymous module so, through path mapping, it can be
// referenced as the "underscore" module.
define(function() {
return _;
});


I've found the RequireJS documentation on this problem; but all of its solutions seem to be with the assumption that the library importing the library with the anonymous module is using RequireJS, which isn't the case here.


How can I deal with this so that the downstream libraries don't need to do any special handling in order to require our library? Ideally, it'd be nice if we don't have to add custom logic for every library that we use with an anonymous module definition in it, too.





update on change by ajax in yii gridview


I've got a simple table tbl_task in my database with the followings attributes:



  • id int auto_increment

  • description varchar

  • complete boolean


Now I created a gridview. the value of the complete attribute is shown by a checkbox. There should be the possibility to change the value of the complete attribute. If you do that, it should save the changes in the database. Meanwhile the gridview gets every 3 seconds the newest records from the database.


I've tried to adapt the gridview js file but it doesn't work.


Does anyone has an idea how to solve my problem?


Many thanks in advance.





Increase hit area of mouseover in google maps polyline


I have a javascript code using google maps api with many polylines with stroke width 1. I want to add a tooltip, so I am using info window on mouse over. But the problem is, it is really hard to mouseover event for 1 width of polyline. Is it possible to increase the hit area without increasing the polyline width?


It might be a duplicate of How to increase mouseover “hit area” in polyline geomap but the accepted answer there doesn't seem to be good since it suggests to increase the stroke width which I don't want to do.


(I also needed similar thing for mouse click also, I currently find out the nearest marker for this by iterating and finding distance. If a easier solution exists for click also, I'd appreciate that also)





How can I add a class to the selected element on click event with select2?


We are using Select2 version 4.0.0-rc2


To improve mobile usage we would like to implement adding a class to the clicked item in the drop down.


I tried reacting to the select2 events like this:



element.select2({}).on('select2:open', function(){
this.addClass('my-class');
}


However, the problem with this is that 'this' is the option and not the rendered select li. I believe 'this' is because Select2 delegates/passes the event down to the select option.


I also tried directly targeting the result item like this:



$('.select2-results li ["aria-selected=true"]').on('click', function(){
this.addClass('my-class');
}


But I get the same problem as above. 'This' and even Event.target are option.


I found some suggestions from older versions of select2 and tried this:



element.select2({}).on('select2:open', function(e){
$('.search-results li [aria-selected=true]').on('mouseup', function(e){
e.stopPropagation();
this.addClass('my-class');
}


This one only seemed to work on the second click. So, I clicked to open the list, I select an item, nothing happens, I select another item, it then gets the class.



  • Note: Some of the selectors above may not be accurate but its just to give an example. All of my code worked except that I couldnt get my event to fire on the right element.


Could anyone suggest a fix?


Alternatively, on the Select2 page (http://ift.tt/1yf24TR) , they suggest that in version 4 you can write plugins using an adapter. Im not familiar with adapters and can only assume they mean the adapter pattern? I dont understand how I would even start with this. I understand the concept, I write a wrapper so that my functions are called and I can modify them and also pass through to the library methods? If anyone could provide any further info on how I could do that, it would be greatly appreciated.





Switching between flash and iframe version of live streaming Ustream with javascript in wordpress


I'm tryng to make a button for switching between flash version and iframe version of a ustream live channel that i have embed in my personal site


flash code:



<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="640" height="392" id="utv786564"><param name="flashvars" value="autoplay=false&amp;brand=embed&amp;cid=3064708"/><param name="allowfullscreen" value="true"/><param name="allowscriptaccess" value="always"/><param name="movie" value="http://www.ustream.tv/flash/viewer.swf"/><embed flashvars="autoplay=false&amp;brand=embed&amp;cid=3064708" width="640" height="392" allowfullscreen="true" allowscriptaccess="always" id="utv786564" name="utv_n_665786" src="http://www.ustream.tv/flash/viewer.swf" type="application/x-shockwave-flash" /></object>


iframe code:



<iframe width="640" height="392" src="http://ift.tt/1Hy5IR6" scrolling="no" frameborder="0" style="border: 0px none transparent;"> </iframe>
<br /><a href="http://www.ustream.tv" style="font-size: 12px; line-height: 20px; font-weight: normal; text-align: left;" target="_blank">Broadcast live streaming video on Ustream</a>


For this scope i'm using following code:


javascript:



var newHTML = 'html2';
var oldHTML = document.getElementById('divtabone').innerHTML;

function changeText3(){
var currentHTML = document.getElementById('divtabone').innerHTML;
if (currentHTML!=newHTML)
{
document.getElementById('divtabone').innerHTML = newHTML;
}
else
{
document.getElementById('divtabone').innerHTML = oldHTML;
}
}


html:



<div id='divtabone'>html1</div>
<input type='button' onclick='changeText3()' value='change Html'/>


replacing html1 and html2 with flash and iframe code reported above


working demo:


http://ift.tt/1BgU3Pq


I have inserted this code in my test site wordpress:


http://ift.tt/1xv86VC


but how can see when i click change html button i can change video from flash version to iframe version one time only because if i reclick and i want return to flash version it remain in iframe version i have made a demo with codes here:


http://ift.tt/1BgU6dW


the code that i have inserted in functions.php file of wordpress is following:



function mia_on_load_script()
{
// Not our page, do nothing
if( !is_page( 'test' ) )
return;
?>

<script type="text/javascript">
var newHTML = '<div id="1" style="margin-left: 0px; padding: 0px; float: left; width: 640px; height: 392px; border: 0px;"><iframe width="640" height="392" src="http://ift.tt/1Hy5IR6" scrolling="no" frameborder="0" style="border: 0px none transparent;"></iframe></div><div id="2" style="margin-left: 0px; padding: 0px; float: left; width: 320px; height: 392px; border: 0px;"><iframe style="border: 0 none transparent;" src="//www.ustream.tv/socialstream/3064708" width="320" height="392" frameborder="no"></iframe></div>';
var oldHTML = document.getElementById('divtabone').innerHTML;

function changeText3(){
var currentHTML = document.getElementById('divtabone').innerHTML;
if (currentHTML!=newHTML)
{
document.getElementById('divtabone').innerHTML = newHTML;
}
else
{
document.getElementById('divtabone').innerHTML = oldHTML;
}
}
</script>


<?php
};
add_action( 'wp_head', 'mia_on_load_script' );

?>


html in page http://ift.tt/1xv86VC :



<div id="divtabone"><div id="1" style="margin-left: 0px; padding: 0px; float: left; width: 640px; height: 392px; border: 0px;"><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="640" height="360" id="utv786564"><param name="flashvars" value="autoplay=false&amp;brand=embed&amp;cid=3064708"/><param name="allowfullscreen" value="true"/><param name="allowscriptaccess" value="always"/><param name="movie" value="http://www.ustream.tv/flash/viewer.swf"/><embed flashvars="autoplay=false&amp;brand=embed&amp;cid=3064708" width="640" height="360" allowfullscreen="true" allowscriptaccess="always" id="utv786564" name="utv_n_665786" src="http://www.ustream.tv/flash/viewer.swf" type="application/x-shockwave-flash" /></object></div> <div id="2" style="margin-left: 0px; padding: 0px; float: left; width: 320px; height: 392px; border: 0px;"><iframe style="border: 0 none transparent;" src="//www.ustream.tv/socialstream/3064708" width="320" height="392" frameborder="no"></iframe></div></div>
<input type='button' onclick='changeText3()' value='click to change'/>


Why in wordpress don't work ? Cold be a problem of caching? Any other solution to resolve problem? thanks





uncaught exception: out of memory in Ajax Process


I got a problem I am submitting a simple form that has a small data and when I checked in the console tab the URL of ajax seems to be working but after the ajax is success it is redirected to my homepage and from the console tab I have this weird error:



uncaught exception: out of memory


In my ajax I have this simple code only:



$("#add-comment").on('click', function() {

var id = $('input[name=\'review_id\']').val();
var customer_id = $('input[name=\'customer_id\']').val();
var $comment = $('textarea[name=\'user_comment\']').val();

var sample = "test";

$.ajax({
url: 'index.php?route=product/product/writeSubComment',
type: 'post',
dataType: 'json',
data: { text: sample },
beforeSend: function() {

},
success: function(data) {
console.log(data.test);
},
error: function() {
alert('ERROR!!!');
}
});

});


In my PHP controller I have this function



public function writeSubComment() {

$json = array();

$json['test'] = $this->request->post['sample'];

$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));

}




How can I send a response that is a block of code in a node request response function?


I am trying to have a server side function return a block of code. For example, I want to send the following back after a request:



$('body').css('background-color', 'blue')


What I did was wrap this in quotes and have the following response:



res.end("$('body').css('background-color', 'blue')");


However, as I write many lines code, I want to be able to write it without quotation marks. How can I store many lines of code in one variable perhaps so that I can write res.end(codesnippet)?





$cookies service equivalent to chrome.cookies?


I'm new to angular and am working on trying to rebuild a chrome extension into a generic webapp using angular just to learn it.


One of the very first things the extension does is grab a specific cookie (created by logging into a website in a browser tab) using the command chrome.cookies.getAll(). Is the angular equivalent to this just using the $cookies service with $cookies.getAll()? It doesn't seem to be having the same effect when I test it, which is why I ask, so I apologize if this is a stupid question. Anyway, any guidance is appreciated!





Updating template when route model changes (?)



import Ember from 'ember';

export default Ember.Route.extend({
logMore: 20,
dateEncode: "",
model: function(){
var url = "https://xxxx/api/xxxx";
var localData = JSON.parse(localStorage.getItem("user"));
var data = { auth_token: localData.user_token };

( this.get('dateEncode') !== "" )? url += "?from="+ this.get('dateEncode') : url;
return Ember.$.ajax({
url: url,
headers: { "X-Api-Token": data.auth_token }
}).then(function(data) {
console.log(data);
return data;
});
}.observes('dateEncode'),
actions: {
loadMore: function(){
var today = new Date();
today.setDate(today.getDate() - this.get('logMore'));
var initial = this.get('logMore') + 10;
this.set('logMore', initial);
this.set('dateEncode', today.toISOString());
}
}
});


I am using ajax to call an API and made an action than change the url with a param 'from' it's a date return some days ago, the modal can call and return the new data but the template no change, i don't know how to do it, if there somebody who can help thanks for your time.


Maybe another way to do that (?)