Html cloud storage? - javascript

I'm trying to make an app using phonegap, but what I want to know is if it is possible to store information online. For example, say there is a number variable, and it is added to when a button is pushed. Could that value be saved somewhere and then a totally different device can retrieve the variable?
I looked at databases, but I couldn't really understand it. I want something that can be accessed by any device as long as It has a key or something.
Is this possible? If so, how would I do it?

PhoneGap uses JS so you cannot connect to the database directly. You should create a Web service using server side languages like PHP on external server and make ajax request on your web service. This approach is possible using PhoneGap.
Sample Code will look somewhere near:
function FetchData() {
$.ajax({
async: false,
type: "GET",
url: "Your_WebService_URL",
dataType: "json",
success: function(data) {
$.each(data, function(i, object) {
if(i==="title"){
document.getElementById("title").InnerHTML = object;
}
if(i==="home_image"){
document.getElementById("title").InnerHTML = '<img src="'+object+'"/>';
}
});
},
error: function() {
alert("There was an error loading the feed");
}
});
The web service, in this case json will throw the variables. May me somewhere like this :
[{"title":"my application"},{"home_image":"http://link.com/image.png"}]
I think this article is useful to you: Loading external data into a PhoneGap app using the jQuery JSONP plugin for cross-domain access. Also see this similar question here:

This is entirely possible.
You essentially need two components: the client interface, and the server.
The client displays the results to the users, and, using your example, waits for a button to be pushed. On the push of that button, the client would send a request to the server to increment the stored value (possibly through a jQuery.post, or get, function call).
The server page, written in php for example, receives this request, and accesses a file, or more realistically a database, to increment the value.
With some Googling, this should be very doable, but post specific questions if you get stuck.

Related

Restrict ajax calls from outside of node app

I want to restrict AJAX calls other than my application. I don't want my AJAX request to send response when called from outside my application, even when the url of AJAX call is copied and pasted in browser. I am using node, express and mongodb.
What I did was add some headers in my ajax calls:
// javascript
$.ajax({
type: 'POST',
dataType: 'json',
headers: {"Content-Type": "application/json", "app-ver": 1.5}
})
.
// php
$client_ver = floatval($_SERVER['HTTP_APP_VER']);
// I also check $_SERVER['CONTENT_TYPE'] to be: 'application/json'
// and post method. (ask me I'll add)
if ( $client_ver != 1.5 )
{
echo '{}';
exit();
}
Edit:
Another way would be creating a "session" with your app, meaning every request after a successful login has to carry a token (at least)
and have your app attach lots of unique header key-values that is only recognizable by your server, and not any two requests are a like (eg: include time in header, and hash it with REST command, and have server check it to make sure it's a unique command, and it's not just being manipulated.
* You have to know your session creation algorithm and it HAS to be unique, or if you don't know how to do it, I suggest research more about it.
If your application runs on a user's machine (like a JavaScript web app) then it is impossible to prevent someone from making the calls from outside of your app. You can make it harder by using a nonce with each request, but even then someone could build their own app that mimics your app and makes the calls in the correct order.
In short: you can't ever fully trust the client and you can't prevent someone from spoofing the client. You need to re-examine your requirements.

Custom tracking via API

I was looking to get some opinions on something I am trying to achieve. I have built an API which essentially comprises of GET requests that returns data. A third party have built a frontend that utilizes my API. I am hosting the frontend and backend but they sit on seperate servers. The frontend has no access to the server besides via the API.
Now on a third level, I need to implement some tracking. Essentially, if a button is clicked on the frontend I want to record this. So I thought that I could add a database table to my API database for this. I can then provide a route to record the information I need. With the API set up, I have created my own script which essentially looks something like this
$( ".button" ).click(function(e) {
e.preventDefault();
$.ajax({
url: "https://someurl.com/tracking",
type: "POST",
data: {
"Element" : "Button Click",
"id": someID
},
success: function (data) {
alert(data)
},
error: function(xhr, ajaxOptions, thrownError){
alert("ERROR")
}
});
});
So if any element with the class button is clicked, an AJAX request is made to my API and then the API can put the data into the table.
Now in thoery the above approach should work. I did have a couple of questions however.
I now essentially have a frontend on server A, a backend on server B, and a seperate tracking script which I will place on server A and simply load in the frontend. I am expecting a lot of visitors to this application, so would this tracking and all of the requests it will make cause any issues?
My main question however is this. Is there any way I can implement this tracking without interfering with the application itself, almost making it unobtrusive. Essentially, if something goes wrong with the tracking, I do not want it to have any impact on the application (frontend and backend) itself. Are there any safeguards I can implement to ensure this?
Any advice appreciated.
Thanks

Extjs 5.0.1 How to send a JSON POST request the proper way

Good day all. I'm totally new to Extjs and I've been inserted into a big project already started and left alone.
I'm studing the framework of course, but I'm getting struck every bit of code.
Now, I'd like to understand the proper way to make a rest call, using JSON parameters in POST.
this is my actual situation:
I have defined a combobox in the view file (called setup.js) and I've put a listener on select like the following
emptyText: 'Select a country',
listConfig: {
itemTpl: [
'<div><span class="" style="margin-right: 10px;"><img src="resources/flags/{id}.png"></span>{name}</div>'
]
},
listeners: {
/*created the after render listener to wait until the store is loaded. then I set the default value*/
select: 'onCountrySelect',
afterrender: 'onAfterRenderCombo'
}
on another file, called setupController.js I've defined all my functions:
onCountrySelect: function(a){
console.log("selected ",a.value);
var controller = this,
userData = controller.getUserData();
console.log("user.id",userData.id);
},
Now, on every country select action, I've to send a JSON to a server, to "set" the country used by the user. The call depends also on the enviroment as the dev one is different from the production one, so I guess that I have to make some sort of proxy, but maybe this is a later issue, now I'd like to setup a call for this selection, so I'll use this logic for all the future calls I have to do.
questions are, is there a proper way to define it? do I need a model? or is good to have al the calls in the store? do I need a... proxy(?) or a store or something "external" so I can use the very same call in some other places? is there an example for this?
Guys/Girls, thanks in advance.
Like written here http://docs.sencha.com/extjs/6.0.2/classic/Ext.data.proxy.Ajax.html
A proxy is made to work with a server on the same domain:
AjaxProxy cannot be used to retrieve data from other domains. If your application is running on http://domainA.com it cannot load data from http://domainB.com because browsers have a built-in security policy that prohibits domains talking to each other via AJAX.
Personally Having a console connecting with more than one server, I use an ajax request like that http://docs.sencha.com/extjs/6.0.2/modern/Ext.Ajax.html#method-request
Ext.Ajax.request({
url:'',
method:'POST',
params:{
json:YOURJSON
},
success:function(response){
},
failure:function(response){
}
});
I'm working on a personal proxy, extended by ajax proxy, to do the ajax call without different domain problems. If you want to do an home made proxy you can read all you want about proxy here: http://docs.sencha.com/extjs/6.0.2/classic/Ext.data.proxy.Proxy.html
or simply you can use an external JS class that do the ajax request for you.

How to hide serious business logic in JS file

In our recent applications we are using lots of AJAX in JS files to avoid frequent postbacks. But I'm worried about the public getting into some of our business logic by just checking the JS file. They can also alter the data being sent to the server using firebug or such features. So how can we avoid this scenario and protect our code from being easily visible to the world.
In this case, the public can see the server side function, parameters etc easily. So how can we avoid this headache to some extent.
var param = { id: id };
var param = JSON.stringify(param);
$.ajax({
type: "POST",
url: "qmaker.aspx/deleteQuestion",
data: param,
contentType: "application/json; charset=utf-8",
dataType: "json",
global: false,
beforeSend: function () {
$.blockUI({
message: '<h3>Deleting Question..<br><small>Please wait for a moment...</small></h3>'
});
},
success: function (data) {
if (data.d == 1) {
var n = noty( type: 'success', text: 'Question Deleted successfully.', /* ... */)
var oTable = $('#table_question).DataTable();
var row = oTable.row($(that).parents('tr:first'));
/* ... */
You don't get to pick what the client sends you. I can submit forms without even reading your HTML.
You also don't get to pick what, out of what you send to the client, the client may or may not read. You sent me a JS file, it's out of your hands now.
In traditional programs, you'd be able to relatively safely sell programs by compiling them, because the original source code was unrecoverableto some definitions of unrecoverable.
With JavaScript, you send your code to the browser, and ask them nicely to execute it. You can't expect the browser not to read all of the code, right? So why can you expect the same of the user, who is using the browser to view your page?
Make sure you application is secure and airtight even if details about your business logic are leaked. A good security stands strong even if everything about the system is known to an attacker, including the source code and the database structure.
Then again
You don't need to expose the inner workings of the server to JavaScript. The "code" you posed doesn't really reveal anything in terms of how the server works, all I know is that there's a page on qmaker.aspx that supports the deleteQuestion path, and when I hit that, with an ID, that question will be deleted. It's now up to you to think what an attacker might do with this information, and seal any attack vectors.
If you want to make it safe you should implement authentication and tokenized requests. This way it doesn't matter if the public see the requests, they will not be able to make successful requests without being authenticated and having a valid token.
Edit below: to provide some extra information.
Surely in your applications you implement some kind of login so users are authenticated and allowed (or forbidden) to use certain parts of your application.
When a user logs in, you could generate a (temporary) token on the server side, store it and pass it back to the user through browser session or similar. Then pass the token as a parameter to the ajax calls.
$ajax(url, {
data: {
token: session.token,
action: 'delete',
id: entryID
}
}
The server will check if the token has been passed and it's valid against the db records. If it is it will just perform the requested operation and return a reply, or it could just return a 401 (unauthorized) error..
If you want something more advanced and perhaps safer, you could search for oauth 2.0 authentication.

Javascript Files that enable sending and receiving json data in phonegap

Which javascript files must be available either in client-side or server-side for you to be able to send and receive json data in your BlackBerry phonegap application.
I see this often omitted in all the solutions to json-related questions that have been posted.
I am completely new to phonegap and jQuery and so I need help also I am trying to send form details (like firstName and lastName) to a php file on the server-side.
So that the data would be processed by the php and the record would be stored on my database.
Can some one work me through how to send the data using json?
You can get detail on Json integration in phonegap from this blog.
this blog will explain through a simple example how you can use JSON to ease the client-server data transmission.
Don't bother about server site, server team (PHP/Java) will take care of it.
In phonegap app every logic is buid in javascript, so in your case if you want to send some information to server, you need to create json object and append it to $.ajax function and same function to receive the response from server:
$.ajax({
url:'stringURL',
beforeSend: function(x) {
x.setRequestHeader('Authorization','username/pwd');
},
dataType:"json",
contentType:'application/json',
timeout:10000,
type:'POST',
data : {
//append json data here if you want to send some data to server
},
success:function(data) {
alert(data); // here you will get json data on success, parse it like key-value mechanism in js
},
error:function(XMLHttpRequest,textStatus, errorThrown) {
alert("Error status :"+textStatus);
alert("Error type :"+errorThrown);
alert("Error message :"+XMLHttpRequest.responseXML);
}
});
Please have a look at this blog to write php-web service or share with you server team.

Categories