How to pass parameters with Object Values through URL - javascript

I created a project that allows converting HTML to PDF. I'm using phantom-render-stream
to convert the HTML to PDF. My problem now, I failed to pass an object value to HTML. Below is my code.
app.js
var username = "AAA";
var pets = [
{id: 1, name: "cat"},
{id: 2, name: "dog"},
{id: 3, name: "sugar glider"}
];
var address = {
line1: "Street A123",
town: "Edinburgh",
country: "Scotland"
};
render('http://localhost:8888/createForm.html?username='+username+'&pets='+pets+'&address='+address
.pipe(fs.createWriteStream('customer.pdf'));
In createForm.html, I used an AngularJS to get and view the value to PDF.
createForm.html
<script>
var app = angular.module('myApp', []);
app.config(function($locationProvider){
$locationProvider.html5Mode(true);
});
app.controller('getDataCtrl', function($scope, $location) {
var url = decodeURIComponent( $location.url() );
var value = $location.search();
$scope.username = value.username;
$scope.pets = value.pets;
$scope.address = value.address;
})
</script>
<body>
<div ng-app="onePayForm" ng-controller="getDataCtrl">
<p>{{username}}</p>
<p>{{pets[0].name}}</p>
<p>{{address.line1}}</p>
</div>
</body>
After successfully converting HTML to PDF, I opened the pdf file to see the result. Only username appears in pdf, the rest shows like this {{pets[0].name}} {{address.line1}}.

in
render('http://localhost:8888/createForm.htmlusername='+username+'&pets='+pets+'&address='+address)
.pipe(fs.createWriteStream('customer.pdf'));
your query params need to be prepared before appending them to the url. What you should do
var readyPets = encodeURIComponent(JSON.stringify(pets));
var readyAddress = encodeURIComponent(JSON.stringify(address));
then change the code above to :
render('http://localhost:8888/createForm.htmlusername='+username+'&pets='+readyPets+'&address='+readyAddress)
.pipe(fs.createWriteStream('customer.pdf'));
in createForm.html parse these param queries:
$scope.pets = JSON.parse(decodeURIComponent(value.pets));
$scope.address = JSON.parse(decodeURIComponent(value.address));

Related

SAPUI5: Routing with parameters - How get correct path of binding context

I am trying to implement routing with parameters as in this walkthrough: https://sapui5.hana.ondemand.com/1.58.7/#/topic/2366345a94f64ec1a80f9d9ce50a59ef
However, instead of getting data as a path
/Invoices(CustomerName='Alfreds%20Futterkiste',Discount=0f,OrderID=10835....
when they do:
oRouter.navTo("detail", {invoicePath:
oItem.getBindingContext("invoice").getPath().substr(1)});
when I use the function in my controller (see onFwdDetail below), I only get a string path:
nodes/0
And this cannot be used in routing (see manifest.json below):
Invalid value "nodes/0" for segment "{detailPath}".
I am assuming it is because my JSON file is structured differently than in the walkthrough. How do I get the correct path with data for routing?
The relevant section of my implementation are as follows:
Data.JSON
{
"nodes": [
{
"text": "Text1",
"status1": "Status10",
"status2". "Status11"
},
{
"text": "Text2",
"status1": "Status20",
"status2". "Status21"
},...]
}
Overview.view.xml
<Table
items="{path: 'mydata>/nodes'}">
...
<ColumnListItem type="Navigation" press="onFwdDetail">
Overview.controller.js
onInit : function() {
var oModel = new JSONModel("model/Data.JSON");
this.getView().setModel(oModel, "mydata");
},
onFwdDetail : function(oEvent) {
var oItem = oEvent.getSource();
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.navTo("detail", {detailPath:
oItem.getBindingContext("mydata").getPath().substr(1)});
console.log(oItem.getBindingContext("mydata").getPath().substr(1));
}
manifest.json
{
"pattern": "details/{detailPath}",
"name": "details",
"target": "details"
}
Their path is a path to an entity of an OData model. Your path is a path to an entity of a JSON model.
Those paths are built entirely different. Most importantly your path contains a slash, while theirs does not. This confuses the parser which tries to match details/{detailPath} and details/nodes/0.
The 0 itself is a valid path in your example. nodes is an array and it's possible to do nodes[0]. It's just that the routing class doesn't like the format.
So what you can do is simply passing the 0 to your detailPath. In your detail view you can then build the original key ("nodes/" + detailPath) and bind your view to that key.
I would also recommend this approach for OData btw:
extract actual keys from bound object
pass keys to your router
in your detail view build a key from the passed arguments
Pseudo code for an OData model:
Controller A:
// read relevant values from binding context
var oContext = oItem.getBindingContext("myModel");
var sKeyName = oContext.getObject("CustomerName");
var sKeyId = oContext.getObject("OrderID");
// trigger navigation
oRouter.navTo("orderDetail", { name: sKeyName, id: sKeyId });
Controller B:
_onRouteMatched: function (oEvent) {
var oModel = this.getModel("myModel");
var that = this;
// read params from routing
var sKeyName = oEvent.getParameter("arguments").name;
var sKeyId = oEvent.getParameter("arguments").id;
// as soon as the metadata of the model are available there is a great API to build keys
oModel.metadataLoaded().then(function () {
var sPath = oModel.createKey("/Invoices", {
CustomerName: sKeyName,
OrderID: sKeyId
});
// sPath should be something like "/Invoices(CustomerName='Troll',OrderID=12345)"
that.getView().bindElement({ path: sPath });
});
},
manifest.json
"pattern": "order/{name},{id}",
"name": "orderDetail"

AngularJS localstorage for a factory

I am a newbie to IonicFrameWork and was following their "starter tab" template and made a few modifications to "delete" and "bookmark" items from a factory.
My books.js which contains the factory looks as follow:
.factory('Books', function() {
// books data
var books = [{
id: 0,
title: 'Sample Title',
author: 'Sample Author',
category: 'Horor, Fiction',
cover: '/cover.jpeg',
details: 'some details about the book',
chapters: [
{
id : 1,
name: 'Chapter 1',
filename: 'chapter1.html',
},
{
id : 2,
name: 'Chapter 2',
filename: 'Chapter2.html',
}
]
}
.....
return {
all: function() {
return books;
},
// remove a book from the list
remove: function(book) {
books.splice(books.indexOf(book), 1);
},
and my controllers.js looks like this:
....
.controller('DashCtrl', function($scope, Books) {
$scope.books = Books.all();
$scope.remove = function(book) {
Books.remove(book);
};
})
.controller('singlebookCtrl', function($scope, $stateParams, Books){
$scope.book = Books.get($stateParams.bookId);
$scope.toggleIcon = function ($evemt, iconName, book){
var buttonClasses = $event.currentTarget.className;
// add the book to favorite
if (....){
book.isFavorite = true;
}
// remove the book from favorite
else {
book.isFavorite = false;
}
....
when I exit the app and open it again, the deleted item is back and favorite items are gone.
When searching for a solution , I came across this article which states I should use window.localstorage. But not sure how I should apply this method for a factory.
I personnaly prefer using ngStorage that makes it very simple and straight forward to use localStorage & sessionStorage.
For example, after injecting the dependency in your controller you can:
Set a variable :
$scope.favList = [1, 4, ...]
$scope.jsonList = { ... }
$localStorage.favLists = $scope.favList;
$localStorage.jsonList = $scope.jsonList;
Access a variable, Simply access to localStorage value :
var favList = $localStorage.favLists;
For all intents and purposes you can treat Local Storage just as if it were a key/value store, like a javascript object. So if you want to save a value in local storage, just do it like the following.
window.localStorage["bookOne"] = "STRING HERE"
Or if you want to save a javascript object:
window.localStorage["bookOne"] = JSON.stringify({a:b})
And it should persist between page reloads.
The real issue here is that in your code, you are setting books on each load with var books = .... Every time you reload the application it will re-apply books and favourites will be lost. So beyond just saving it to window.localStorage you will also have to read from local storage and assign it to your books and favourites variables when your app loads in order to see the changes that were previously made.
You can simply do it with angular-local-storage module, here's some example based on your problem.
angular.module('app', ['LocalStorageModule'])
.factory('Books', function(localStorageService) {
// favorites list(books id)
var favList = [1, 2, 3, ...];
// ....
return {
remove: function(id) {
favList.splice(favList.indexOf(id), 1);
// sync with localStorage
localStorageService.set(favorites, favList);
},
// ....
}
});
Note that you can simply use angular-local-storage#bind and bind specific scope-key to this service that automatically do this synchronisation for you. for example:
// Inside your controller
$scope.favList = [1, 4, ...]
// returns a deregistration function for this listener.
$scope.unbind = localStorageService.bind($scope, 'favList');

how do i parse json value and get id into variable

hello i am having this code of jquery:
var fbuid = zuck;
var fbjson = $.getJSON("https://graph.facebook.com/"+fbuid);
how to get the id from json directly into var :
{
id: "4",
first_name: "Mark",
gender: "male",
last_name: "Zuckerberg",
link: "https://www.facebook.com/zuck",
locale: "en_US",
name: "Mark Zuckerberg",
username: "zuck"
}
all i would like to get id from json to var as below:
var fbjson.id;
how i do it using jquery?
So you're close but you've got some things you need to adjust. Ajax is async which means that you're waiting on a server response. You need to fill your data once you have that piece of data. Note you will not be able to reference fbjson until AFTER the getJSON has fired and completed.
According to the jQuery documentation for getJSON
you need to have a callback similar to this -
var fbuid = 'zuck';
var fbjson;
$.getJSON( "https://graph.facebook.com/"+fbuid, function( data ) {
fbjson = data;
});
Notice I assign the fbjson in the callback to data which is the server response. now you can reference it as
fbjson.id

AngularJS $http.get php file - $injector:modulerr

I have this file api.php
require_once 'db.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$query=mysql_query("SELECT * FROM $tableName") or die(mysql_error());
$arr[];
while($obj = mysql_fetch_object($query)) {
array_push($arr, $obj);
}
echo $json_response = json_encode($arr);
It is grabbing all the data that i need.
Then i am trying to put that data into my $scope here...
// The controller
function InstantSearchController($scope, $http){
$http.get('api.php').success(function(data) {
$scope.items = data;
$scope.items = [
image : data['icon'],
english : data['english'],
british : data['british']
];
});
}
But this does work if I hard code the data like this.
function InstantSearchController($scope){
$scope.items = [
{
english: 'English A',
british: 'British A',
image: 'images/advil.jpg'
},
{
english: 'English B',
british: 'British B',
image: 'images/advil.jpg'
}
]
}
This is the error that i am seeing in the console
Uncaught SyntaxError: Unexpected token : js/angular.js:44
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.15/$injector/modulerr?p0=instantSearch&p1=E…larjs.org%2F1.2.15%2F%24injector%2Fnomod%3Fp0%3DinstantSearch%0A%20%20%20%......1)
This is the fiddle trying response #1
http://jsfiddle.net/XgsWU/
And this one is for response #2
http://jsfiddle.net/JGjyS/
To anyone that might be reading this later I figured out my issues was in my controller call and i have changed/updated to this and it is working great!
app.controller('InstantSearchController', ['$scope', '$http', function($scope, $http) {
$http.get('inc/api.php').success(function(itemData) {
$scope.items = itemData;
});
}]);
Unexpected token :. This is from:
$scope.items = [
image : data['icon'],
You should use $scope.items = {...} since you want a JavaScript object with key-value pairs, not an array.
It seems like you also want to loop over data and push items onto the array:
$scope.items = [];
data.forEach(function (datum) {
$scope.items.push({
image: datum.icon,
english: datum.english,
british: datbum.british,
});
});
You have a syntax error here:
$scope.items = [
image : data['icon'],
english : data['english'],
british : data['british']
];
It should be:
$scope.items = [
{image : data['icon'],
english : data['english'],
british : data['british']}
];

Can't post variables to Parse JS API

I'm trying to make a sample page where I can fill in some forms and then save the data to Parse API. I tried this using strings first, like this:
var Billing = Parse.Object.extend("Billing");
var billing = new Billing();
billing.set("First Name", "John");
billing.set("Last Name", "Doe");
billing.set("Email", "admin#parse.com");
That did work fine, but when I just wrote a variable, I get an error "POST 400 Bad Request" :
var Billing = Parse.Object.extend("Billing");
var billing = new Billing();
billing.set("First Name", frnm);
billing.set("Last Name", lsnm);
billing.set("Email", eml);
Why is that? I can't seem to find another way to make it work...
See my full coded gist here here
I used:
document.getElementById("card_cvNumber").value;
Instead of:
$('#card_cvNumber').val();
And the Parse JS:
var Billing = Parse.Object.extend("Billing");
var billing = new Billing();
billing.save({Firstname: frnm, Lastname: lsnm, Company: cpnm, Adress: str1, City: cty, State: stat, PostalCode: zpc, Country: ctry, Phone: phn, Fax: fx, Email: eml}, {
success: function(object) {
alert("Success");
}
});
It worked just great!

Categories

Resources