I am running a web page that generates random data and displays it in a HTML table. From the table I run a loop to gather the basic information (all rows that exist and exclude headers of table). This data gets stored in a JSON object called jData.
I want to send this data back to the server and store in a sqlite table named data. The way I am trying to do this is therough the YUI IO utility.
I am trying to wade the API documentation, but I am having no luck. I have two buttons on the page. One to generate the data and on to store the data. The store code is as follows:
var savedata = function(){
var tabledata = Y.one("#generatedtable")._node;
var jData = [];
var i = 1;
var length = tabledata.rows.length
while (i<length){
var samplerow = {};
var r = tabledata.rows[i];
samplerow.timestamp = r.cells[0].innerHTML;
samplerow.volts = r.cells[1].innerHTML;
samplerow.amps = r.cells[2].innerHTML;
samplerow.kW = r.cells[3].innerHTML;
samplerow.kWh = r.cells[4].innerHTML;
jData.push(samplerow);
i++;
}
Y.io("./savedata", Y.System_Config.postjData(jData));
};
Using the chrome debugger tools I see the array being stored properly into jData. I need some basic help with Y.io and how to make posts. Any basic help is much appreciated. My server is run bu the Django Python web application framework.
You should read the IO User Guide. Making a POST request with JSON data in YUI is as simple as setting the HTTP method to POST, adding the data and setting the Content-Type to application/json. The only caveat is that you need to turn the JSON object into a string first using JSON.stringify().
Y.io('/savedata', {
method: 'POST',
data: Y.JSON.stringify(jData),
headers: {
'Content-Type': 'application/json'
},
on: {
success: function (id, response) {
// do something with the response from the server, for example
Y.one('#some-node').set('text', response.responseText);
}
}
});
You can read more about all the configuration options for IO in the "Configuration Object" section of the User Guide. There is an example there of a POST request with JSON data.
Related
Background: I'm writing a small web-server in Java using Vert.X. All of that works so far. Currently the web-server is basically acting as an app-server with a few GET/POST endpoints that just return or consume JSON.
I now need to add a few simple UIs to this server. In the spirit of RESTfulness I'd like to keep my URLs clean and also to return data appropriately based on the Accept: string in the request. For example, if you request from your browser http://www.example.com/challenge/fdb123-aa12345-cbbad12-12345 it should try to load the challenge with that GUID and display an HTML form appropriately. If you do so from a commandline and indicate you accept JSON it should return JSON.
My problem is really: how do I write my HTML to extract the challenge-id and then make an ajax query back to my server to get the JSON data to fill in the form? I'm not shooting for anything fancy; the form is mostly static: a textbox, a datepicker and maybe a few other fields, that's it. Loading the JSON data from the same URL with an "accept" type of application/json should return parameters that I can use in my JS/HTML to fill in the form - my only question is, how do I make that request back to my server when I load the HTML? How do I know the challenge ID?
What you describe is a "REST way", one endpoint supplying different outputs based on the header, but most of the frameworks don't do it like that. In frameworks like Ruby on Rails, the output is defined by the suffix: .html, .json
But let's assume that's still what we want to do:
If the Accept: header is JSON, return JSON
Otherwise, return HTML
In HTML, extract some URL parameter, and send it to get JSON
Ok, here we go:
final Vertx vertx = Vertx.vertx();
final Router router = Router.router(vertx);
router.route("/challenge/:id").produces("text/html").handler(ctx -> {
ctx.response().sendFile("index.html");
});
router.route("/challenge/:id").produces("application/json").handler(ctx -> {
final String id = ctx.request().getParam("id");
final Map<String, String> res = new HashMap<>();
res.put("challenge", id);
ctx.response().end(Json.encode(res));
});
vertx.createHttpServer().requestHandler(router::accept).listen(8080, r -> System.out.println("Ready"));
And your client may look like this:
<script>
$(function() {
var path = document.location.pathname.split("/")
var id = path[path.length - 1]
$.ajax({
headers: {
// If you don't limit headers, it will send Accept: */*
Accept: "application/json"
},
url: "/challenge/" + id,
success : function(res) {
console.log(res)
}})
})
</script>
I'm putting together an app using WP-API with an Angular frontend. I'm developing locally, with the data I'm trying to use loaded in from a remote server. Doing a $resource request for all posts works great.
But, I'm trying now to get the result of the X-WP-TotalPages header and can't figure out how to do it. Here's the code as it stands:
var request = function() {
var fullRoute = 'http://dylangattey.com/wp-json/posts/';
var defaultGet = {
method: 'GET',
transformResponse: function(data, headers){
response = {};
response.posts = JSON.parse(data);
response.headers = headers();
console.log(headers['X-WP-TotalPages']);
return response;
}
};
return $resource(fullRoute, {}, {
get: defaultGet,
query: defaultGet
});
};
// This gives me back the first 10 posts
request().query();
Chrome and curl both show that X-WP-TotalPages should be equal to 2 as a header. However, it just logs undefined.
Am I missing something? No matter whether I use $http or $resource I get the same result. I also have the same issue whether I use a remote site or a local WP installation on localhost. Really, I just want to know the total number of pages or even just the total number of posts for a given request, so if there's a better way to do it, I'd love to know.
You probably need to control the access to the specific headers you want on the server side.
See this thread for a brief discussion, or MDN on Access-Control-Expose-Headers.
I have some code that is trying to get a JSON result from the Soundcloud API.
I registered an app, got the client id and such, and I'm trying to make a call like this:
var querystring = require('querystring');
var http = require('http');
var addr = 'http://api.soundcloud.com/resolve.json?url=http://soundcloud.com/matas/hobnotropic&client_id=XXXXX';
var options = {
hostname: "api.soundcloud.com",
path: "/resolve.json?url=http://soundcloud.com/matas/hobnotropic&client_id=XXXXXx",
method: "GET",
headers: {
"Content-Type": "application/json"
}
}
var request = http.get(options, function(response) {
response.setEncoding('utf8');
response.on('data', function(chunk) {
console.log(chunk);
});
});
This produces a result that looks like this:
{"status":"302 - Found","location":"https://api.soundcloud.com/tracks/49931.json?client_id=xxxx"}
When I use the same URL in Chrome, I get the proper JSON info. How do I properly make this call from server side script?
The built-in http client does not handle redirects. However request does and has many other features the built-in client does not support out of the box.
Today I updated my own NodeJS Api-Wrapper Package for Soundcloud, which can be found here: https://www.npmjs.com/package/soundcloud-nodejs-api-wrapper
It does server side API communication, which includes data modification. No user popup window and redirect url is needed.
I did not found yet any other package having support for this in NodeJS.
I tried to use Angular $http.post(url, data) method. But I am facing some problems to post correct data to server (WebAPI). I have tried follwing options but none is working.
var data1 = new Object();
data1.UserName = "UserA1";
data1.Password = "password123";
data1.ConfirmPassword = "password123";
var data2 = angular.toJson(data1);
var data3 = JSON.stringify(data1);
var data4 = { UserName: "UserA2", Password: "password123", ConfirmPassword: "password123" };
var data5 = "UserName=UserA3&Password=password123&ConfirmPassword=password123";
$http.post(url, data1)
$http.post(url, data2)
$http.post(url, data3)
$http.post(url, data4)
$http.post(url, data5)
None is working. What kind of data is correct for this method. I tried JQuery.post() with above data and it works. Its super strange for me why this simple angularjs method so hard to use or I am missing something.
Update:
Basically I am working on following example. I want to register user from client side (/api/Account/Register).
http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api
This is because your server-side expects a request with its content x-www-form-urlencoded.
jQuery's $.post() sends the request with a Content-type of application/x-www-form-urlencoded whereas Angular's $http.post() sends the request with a Content-type of application/json (and also encodes the data as JSON (instad of form-data) if a JS Object is passed).
There are methods you can send x-www-form-urlencoded requests using $http (and there are several related answers on SO), but it involves less straight-forward code.
I suggest you change your server side to consume JSON requests.
Depending on what you have on server side, you should transform your request (that's the case for PHP, for example, or you can read from the input stream: php://input).
See this gist: https://gist.github.com/JensRantil/5713606.
If this is not solving your problem, please inspect the requests angular is creating (using the Developer Tools -> Network tab in Chrome for example), and tell us what you see.
I'm creating a web application that will use a lot of ajax calls. The application will hold user's personal data. In the ajax calls are variables used like Id, profile_id, message_id etc.. to complete operations like adding posts to profiles, getting connections, etc..
I want to make the calls so secure as posible. I already implemented crsf in the $.post calls. What kind of varibales of the ajax calls must/should I encrypt and which not?
Example of a ajax call (simplified):
function post_msg(profile_id, msg) {
var json_data = new Object();
json_data.profile_id = profile_id;
json_data.msg = msg;
var data_str = JSON.stringify(json_data);
$.post("/ajax/get_posts", { data: data_str, csrf_key: "950egg22b771xxxxxxxxxxxxxxxx1a"}, func_that_does_something_with_ret_data);
}
//Some where else in the front-end
$('#button').click(function() {
var msg = $('#input').value();
post_msg(1, msg); //should I encrypt the id?
});
Don't think about encrypting individual bits of data. If security is important, run the entire transaction across HTTPS.