Javascript Files that enable sending and receiving json data in phonegap - javascript

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.

Related

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

Nodejs and Angular. Make changes to mongodb db after posting

I have a nodejs app with Angular for the front-end stuff. I make a post call from the client side that saves a large JSON string in a collection in mongodb. I want the server side to then chop up the data and save it in the desired format in another collection. I cannot post correctly formatted data directly from the browser because that would mean making too many async post calls from the client side. Here is the code to post that big JSON string:
var request = $http({
method: "post",
url: "/students",
data: {
studentData: jsonData
}
}).then(function successCallback(response) {
}, function errorCallback(response) {
console.log(response);
});
I am not sure how to proceed from here. I am new to nodejs and am not sure how the server side code works. Is it handled in the server.js file? If so, is it feasible to do what I have described above?
This is what I understood after reading the whole thing. You have a big chunk of JSON data firstly you want to store it in collection 1 and then you want to perform some operation on it and then save the new refined data in some other collection 2.
I am going to give my answer based upon that.
To use Mongo we have various modules available for node js. Let's take mongoose as an example here, although you can use any because the concept remains the same as it is very simple.
After every insert entry to the mongodb using respective module you'll have a callback with data inserted. You can manipulate it and then make one more save operation in another collection.

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.

Html cloud storage?

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.

Backbone marionette and posting to an asp.net web service

Not wrapping my brain around this concept at all. I've got a backbone marionette app that has a chat component. All working well.
Each time a user hits the send button on a message, SignalR delivers it. All that is good. I also want to, however, after the message is delivered, submit the message to a web service written in asp.net VB by another developer. That web service persists the message to his SQL server db. I get that backbone models and asp.net Web API's are a natural fit. But the other app is a standard asp.net webforms app, not a Web API.
My old Adobe Flex chat app talked to this web service very easily. Was cake. As I rewrite this Flex app as a backbone marionette app I'm missing how, conceptually, to post the chat messages to the persistence service. When I search for something like "asp.net ajax post web service" I get lots of stuff on the server-side control, ScriptManager. Not applicable in a backbone app I would think.
I thought something like below might work, but I get an error deep inside jQuery, "Uncaught InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable."
What is the conceptual misunderstanding I'm having here?
var url = "http://mydomain.com/thesevice.asmx/theoperation";
var formData = {userid: userid, message: msg};
$.ajax({
url: url,
type: "POST",
data: formData,
success: function (data, textStatus, jqXHR) {
//data - response from server
console.log("Successfully posted chat msg to service...");
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("theoperation error: " + textStatus);
}
});
Conceptual misunderstanding is that you don't post the messages to the service from the client. The service in question is on another domain. There are cross domain issues when posting from the browser. Should post from the server side code that is handling the chat routing.

Categories