Passing a Variable into PayPal initPayButton Function (Paypal Payments) - var

Can anybody help with this short question.
I am trying to pass a JS variable into the PayPal create order function,
but I am not sure how to pass it into the function correctly.
Function Below:
createOrder: function(data, actions) {
var ppcaught=document.getElementById('ppinput').value
return actions.order.create({
purchase_units: [{"description":'ppcaught' <?php echo json_encode($orderdetails); ?>,"amount":{"currency_code":"GBP","value":19.99}}]
});
},

Related

How to use session entity in dialogflow's inline editor?

My problem is passing parameters between intents' hooks.
As example: at one hook I made a request for my own backend and receive a sessionId. I need pass the sessionId to an another intent for second request in it's hook.
How I can do it? I can't find any examples, documentations or best practices.
Thanks for your attention!
You can do this with contexts.
In your first intent you do something like this:
function firstIntentHandler(agent){
return axios.get(`https://yourserver.com`)
.then(function (response) {
agent.add(response.data.sessionId);
const context = {'name': 'yourcontextname', 'lifespan': 3, 'parameters':
{'sessionid': response.data.sessionId }};
agent.setContext(context);
}).catch(function (error) {
agent.add("An error occured.");
});
}
sessionId is the variable name in your json data sent by your server.
In your other intent you can access this data like this:
function otherIntentHandler(agent) {
const context = agent.getContext("yourcontextname");
const sessionid = context.parameters.sessionid;
// do something with this session id
});
}
Be careful with camelcase for your context name. I have the feeling that uppercase letters are stored as lowercase...

Get result in from YouTube channel in nodejs

I am using youtube-node npm to find out all the video list. The documentation is on the link https://www.npmjs.com/package/youtube-node.
But I want that my search only show result of a specific channel i.e if I search hello, then it only give result of AdeleVEVO YouTube channel.
I cant find suitable documentation for that. I don't want to use oauth credentials, I only want to use youtube-node npm.
In package doc you have a sample search, make sure you include in the params parameter an object with the values you want, in your case see in youtube api doc that you need to specify the channelId. Try this way:
var YouTube = require('youtube-node');
var youTube = new YouTube();
youTube.setKey('AIzaSyB1OOSpTREs85WUMvIgJvLTZKye4BVsoFU');
youTube.search('World War z Trailer', 2, {channelId: <string value of the channelId>}, function(error, result) {
if (error) {
console.log(error);
}
else {
console.log(JSON.stringify(result, null, 2));
}
})
;
If you are the owner of the channel, you can use the forMine parameter of the YouTube API for this. Setting this parameter will limit the search to the authorized user's videos. Below is a sample from the official documentation.
IMPORTANT NOTE: Do not use the youtube-node module for this, specifically because--in my experience at least--the addParam() function does not reliably add parameters to the request (e.g., in my code I called youtube_node.addParam('safeSearch', 'strict');, but restricted videos would still be returned in the results.)
Instead, use the YouTube Data API directly as shown in this quickstart example.
// Sample nodejs code for search.list
function searchListMine(auth, requestData) {
var service = google.youtube('v3');
var parameters = removeEmptyParameters(requestData['params']);
parameters['auth'] = auth;
service.search.list(parameters, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
console.log(response);
});
}
//See full code sample for authorize() function code.
authorize(JSON.parse(content), {'params': {'maxResults': '25',
'forMine': 'true',
'part': 'snippet',
'q': 'fun',
'type': 'video'}}, searchListMine);

Node.js Web Scraping with Jsdom

I would like to scrape the http://www.euromillones.com.es/ website to get the last winning 5 numbers and two stars. It can be seen on the left column of the website. I've been reading tutorials, but I am not capable of achieving this.
This is the code I wrote so far:
app.get('/winnernumbers', function(req, res){
//Tell the request that we want to fetch youtube.com, send the results to a callback function
request({uri: 'http://www.euromillones.com.es/ '}, function(err, response, body){
var self = this;
self.items = new Array();//I feel like I want to save my results in an array
//Just a basic error check
if(err && response.statusCode !== 200){console.log('Request error.');}
//Send the body param as the HTML code we will parse in jsdom
//also tell jsdom to attach jQuery in the scripts and loaded from jQuery.com
jsdom.env({
html: body,
scripts: ['http://code.jquery.com/jquery-1.6.min.js ']
}, function(err, window){
//Use jQuery just as in a regular HTML page
var $ = window.jQuery;
res.send($('title').text());
});
});
});
I am getting the following error:
Must pass a "created", "loaded", "done" option or a callback to jsdom.env.
It looks to me that you've just used a combination of arguments that jsdom does not know how to handle. The documentation shows this signature:
jsdom.env(string, [scripts], [config], callback);
The two middle arguments are optional but you'll note that all possible combinations here start with a string and end with a callback. The documentation mentions one more way to call jsdom.env, and that's by passing a single config argument. What you are doing amounts to:
jsdom.env(config, callback);
which does not correspond to any of the documented methods. I would suggest changing your code to pass a single config argument. You can move your current callback to the done field of that config object. Something like this:
jsdom.env({
html: body,
scripts: ['http://code.jquery.com/jquery-1.6.min.js'],
done: function (err, window) {
//Use jQuery just as in a regular HTML page
var $ = window.jQuery;
res.send($('title').text());
}
});

AJAX Image upload with backbone.js node.js and express

So I have been trawling the net for a day now trying to find a complete example of how to upload an image along with a normal POST (create) request from a backbone model. So after some initial digging around I discovered the FileReader api in HTML5 - After some testing I had this working great outside backbone by creating a XMLHttpRequest()
The problem im now trying to solve is how can I make bacbone send the FILES data along with the POST request like you would experience in a normal multipart form work flow. Im pretty new to backbone so please forgive any obvious errors. Heres what I have so far.
model
define(
[
'backbone'
],
function (Backbone) {
var Mock = Backbone.Model.extend({
url: '/api/v1/mocks',
idAttribute: '_id',
readFile: function(file){
var reader = new FileReader();
self = this;
reader.onload = (function(mockFile){
return function(e){
self.set({filename: mockFile.name, data: e.target.result});
};
})(file);
reader.readAsDataURL(file);
}
});
return Mock;
}
);
view
define(
[
'jquery',
'backbone',
'underscore',
'text!../templates/create_mock-template.html',
'models/mock',
'collections/mocks'
],
function ($, Backbone, _, createMockTemplate, Mock, mocksCollection) {
var CreateMockView = Backbone.View.extend({
template: _.template(createMockTemplate),
events: {
'submit form': 'onFormSubmit',
'click #upload-link': 'process',
'change #upload': 'displayUploads'
},
initialize: function () {
this.render();
return this;
},
render: function () {
this.$el.html(this.template);
},
process: function(e){
var input = $('#upload');
if(input){
input.click();
}
e.preventDefault();
},
displayUploads: function(e){
// Once a user selects some files the 'change' event is triggered (and this listener function is executed)
// We can access selected files via 'this.files' property object.
var formdata = new FormData();
var img, reader, file;
var self = this;
for (var i = 0, len = e.target.files.length; i < len; i++) {
file = e.target.files[i];
if (!!file.type.match(/image.*/)) {
if (window.FileReader) {
reader = new FileReader();
reader.onloadend = function (e) {
self.createImage(e.target.result, e);
};
self.file = file;
reader.readAsDataURL(file);
}
}
}
},
createImage: function(source, fileobj) {
var image = '<img src="'+source+'" class="thumbnail" width="200" height="200" />'
this.$el.append(image);
},
onFormSubmit: function (e) {
e.preventDefault();
// loop through form elements
var fields = $(e.target).find('input[type=text], textarea');
var data = {};
// add names and vlaues to data object
$(fields).each(function(i, f) {
data[$(f).attr('name')] = $(f).attr('value');
});
// create new model from data
var mock = new Mock(data);
// this should set the filename and data attributes on the model???
mock.readFile(this.file);
// save to the server
mock.save(null, {
wait: true,
error: function(model, response) {
console.log(model)
},
success: function(model, response) {
mocksCollection.add(model);
console.log(model, response);
}
});
},
});
return CreateMockView;
}
);
I totally appreciate this may all be a bit hand wavey, its more a proof of concept than anything else and a good chance to learn backbone too. So the crux of my question is this
When the request is sent by backbone to the api why arent I seeing the data and filename attrs in the request to the node/express server
Is what im trying to do even possible, I basically thought i'd be able to read the data attr and create and image on the server?
Is there a way to perhaps overide the sync method on the Mock model and create a properly formed request where POST and FILES are correctly set.
Im sure this is possible but I just cant seem to find the bit of info I need to plough on and get this working.!
Hope someone can help!
CHEERS
edit
Just wanted to provide a bit more info as by my understanding and some brief chats on the document cloud irc channel this should work. So when I call
mock.readFile(this.file)
the fileName and data attributes dont seem to get set. In fact a console log here dosent even seem to fire so im guessing this could be the problem. I would be happy with this approach to basically build up the Image on the node end based on the value of data and fileName. So why arent these properties being set and passed along in the post request to the api?
I have resolved this situation splitting the Model creation in two steps:
Basic information
Assets
For example if my Model is a Film, I show a create-form that only include title and synopsis. This information is sent to the server and create the Model. In the next step I can show the update-form and now is very easier to use File Uploads plugins like:
jQuery File Upload Very profesional and stable
BBAssetsUpload Very beta, but based on Backbone, and you can say you know the programmer ;P
You can also check their source code for references to try to achieve a one-step Backbone Model with File creation solution.
jquery-file-upload-middleware for express is probably worth mentioning.

Dynamic sidebars with Node.js, Express.js and Jade

I'm trying to write a dynamicHelper for Jade to check if a user is allowed to access a resource before actually accessing it. I have the module to perform the checks which returns true or false when called with the url and username of the resource to be accessed, but I can't get the helper working with parameters?
dummy view:
if(hasAccess.check("/url", "username") == true)
li access
else
li no-access
Helper:
app.dynamicHelpers({
hasAccess: function() {
return access;
}
});
Access-function:
var access = function() {
return {
check: function(url, user) {
return mymodule.hasAccess(url, user);
}
};
};
I tried to get it done with this answer, but no luck so far.
There are a couple of things wrong there (if I understand it correctly)
Your hasAccess function isn't accepting any parameters
hasAccess is also just returning a reference to the access function, not calling it
the access function doesn't accept any parameters either
It's possible that what you're trying to do would work using
app.dynamicHelpers({
hasAccess: access().check
});
But i haven't run the code, so I may be completely wrong.
Good luck :)

Resources