I have ButtonClick.js and TakeData.js files. I defined my json data in TakeData.js as below
var dataObj = {};
var locationsObj = "locations";
dataObj[locationsObj] = {};
dataObj[locationsObj].source = [];
dataObj[locationsObj].target = [];
When I click the button in ButtonClick.js and the code snippet as below
button()
.container(g2)
.text(text2)
.count(1)
.cb(function()
{
console.log(dataObj[locationsObj].source[0]);
console.log(dataObj[locationsObj].source[1]);
console.log(dataObj[locationsObj].target[0]);
console.log(dataObj[locationsObj].target[1]);
console.log("SaveFile");
})();
I want to send json data into the nodejs file writing function as the following.
fs.writeFile('sample.txt', [need to insert my JSON], function(err) {
if(err) return console.log(err);
console.log('Hello JSON > sample.txt');
});
How can I do that? Is there another effective way?
Your backend needs to have an HTTP server listening on some port that is accessible to your frontend. Then your frontend needs to make an AJAX request to your backend (most likely a POST request) and send the required data in the request body.
Now, your backend needs to handle the request, get the data and write it to the file or do whatever you want with that.
Things to keep in mind:
use body-parser if you're using Express
remember about CORS
It's easier if you use a higher level framework on the backend like Express, Hapi, Restify, LoopBack etc. instead of the low level http module in Node.
It's also easier if you use a framework on the frontend like jQuery, Angular, React, Aurelia, Ember etc.
The first step is to set up a RESTful POST operation (an HTTP POST) on your server. This is the typical service mechanism for what is sometimes called an AJAX call. Once you have the server set up to receive a string via the POST, you can serialize your objects on the client side and deserialize (reconstitute) the objects on the server side.
To serialize, you can use stringify on the client side. A simple web search for "stringify" will show you different ways to use stringify in a browser-independent, backward compatible way.
stringify(obj)
On the server side, node.js has a global JSON object. Use parse to reconstitute an object or objects from the string. Other major languages now have similar parser methods. 1
JSON.parse(strJSON)
To get started, you can test the mechanism with just one simple object. Then you can aggregate the objects in a JSON array or associative array and send them all at once in a single POST.
[1] There are frameworks that encapsulate this process, but it may be of value to you to NOT initially use them so you get a clear picture of the mechanics of a RESTful POST over the HTTP protocol. It is the key thing that a browser does when you submit an HTML form, and RESTful operations are key communications elements in today's IT world.
Related
I'm working on web application where I need to send some data using ajax with post method. So I have two choices to send data whether in JSON format or query prams. I'm confused which should I use? and is it safe to send data in JSON format?
As #lucasreta mentioned, if you use HTTPS, it doesn't really matter either way.
Both methods are widely used. I know that Google accepts a Post request with query params and responds with a JSON object for ReCaptcha Server side validation.
Sometimes, the decision to use one or the other (or both) is dependent on how easy your chosen back-end technology makes it for you to either parse out query params or serialize JSON.
I will say that there is a general trend in using JSON in the request body as opposed to query params.
I found a couple of SO questions that are more down the lines of what you are asking...
REST API Best practices: args in query string vs in request body
REST API Best practices: Where to put parameters?
I have a JSON file 'DealerList.json' and I can access it from my app by importing it using
import DealerList from './json/DealerList'
let tasks = DealerList;
The tasks here contain the JSON and I can easily access it.
Is there any way by which I can update the JSON back like if I update the values OR if I delete the values. I have also tried require("fs") but that too is throwing error.
The JSON file is present in a folder called json in the React App.
No, and this is a good thing. You do not want any web browser to be able to come along and rewrite files on your HTTP server.
Write a web service which will read and update the data based on HTTP requests (with appropriate authentication/authorization to stop undesirables from changing the data). Then interact with it via XMLHttpRequest / fetch / an abstraction library wrapping one of them (like axios).
(Or use localStorage if you want to store the data on a per-browser basis rather than shared between visitors).
I'm a little confused with how to support both server-side queries and client-side filtering with dstore, and am hoping for some guidance. My scenario:
I am communicating with an archive server, so I only have get and query requests, nothing that updates the data.
I want to perform both server-side queries and client-side filtering.
I'd like to cache the results so I'm not accessing the server for every fetch().
If I use a Request, filter() will pass its query parameters to the server, but the data isn't cached and I can't tell how to filter on the client side.
If I use a RequestMemory, filter() is applied to the local cache, and I can't tell how to specify parameters for the server.
All the pieces seem to be there with dstore, I just haven't figured out how to put them all together yet. Thanks for any help.
Looks like I figured it out. There were a couple issues with how I was using RequestMemory. The first was that I didn't realize RequestMemory invoked fetch() automatically. The second issue was that I used an object as the queryParam when it should have been an array.
To meet my requirements I created a new store that extended from Request and Cache, just like RequestMemory, but I did not call fetch() in the postscript() function. Then I could pass parameters to the server:
store.fetch({queryParams: ['key=value']}).then(function(data) {
console.log("fetch", data);
});
I could then 'freeze' the store by setting store.isValidFetchCache = true and subsequently perform client-side filters:
store.filter({type: 'xyz'}).fetch().then(function(data) {
console.log("filter", data);
});
I'm a full-time backend developer just starting to learn angular for some of my own projects.
By default it seems angular $http requests are sent as JSON strings. I am currently overriding the transformRequest method to parameterize it like jquery. Its more convenient for my backend framework (Phalcon PHP) to receive it this way.
Before I commit to this path, are there any cons to structuring it this way? Any problems unit testing or using third-party modules?
Edit
To clarify, angular sends POST as JSON string in the body. jQuery and other frameworks I've used send as form-urlencded like:
Name=Jonathan+Doe&Age=23&Formula=a+%2B+b+%3D%3D+13%25%21
http://en.wikipedia.org/wiki/POST_%28HTTP%29#Use_for_submitting_web_forms
Which, perhaps due to the content header populates the $_POST global in php (I assume) with the form data;
I would recommend you to stick to the JSON format and send data in JSON request body instead of key=value param pairs. You can receive JSON cleanly with Request::getJsonRawBody() in Phalcon.
The main difference is that POST vars format allows you to send key=value pairs of data. When it comes to more complex structures (arrays, associative arrays, nested objects and so on), you will start to have problems which you will have to solve some way. It won't happen if you send JSON objects in POST/PUT request bodies. And, of course, you get serializing and deserializing OOTB in both AngularJS and Phalcon.
You should strongly consider key=value params for GET parameters only and JSON data for everything else. Obviously, you can mix those two (I mean i.e. sending new content for your article as PUT request with JSON body, but specifying article id in URL like /article?id=123).
You may be also istresed in reading REST API: Request body as JSON or plain POST data?.
I have a website with a form (currently it's plain HTML but we're switching to JQuery). The flow is like this :
Take in the user's inputs --- 5 integers
Make a call to a web service via REST
Run some calculations server side... and generate a JSON object
??? Now I have my result JSON object, but how do I get it to the client? Persist it?
??? Does the URL need to be the exact location of the JSON file? That would mean 100's
??? of JSON files in my web server's DIR.
D3.js on the client side, waits for the data to be present (via AJAX?).
var data; // a global
d3.json("path/to/file.json", function(error, json) {
if (error) return console.warn(error);
data = json;
visualizeit();
});
Once data is present, render for the client, and remove the calculator from the screen.
I'm having a tough time here, because I notice all AJAX requests need a URL.. but then does that mean I need to give a unique URL to each resulting JSON object? Doesn't that mean I need to persist that object?
I'd just like to have d3.js render my JSON object but unclear what are my options for where to put it.
How do I post parameter on d3.json?
Typically, you will pass some parameters via a javascript object or
a query parameter.
Basically, something like...
data = {}
data.var1 =5;
data.var2 =10;
var my_request = d3.xhr(url)
my_request.post(JSON.stringify(data), function(error,received)){
};
Or
d3.json(url+"?"+"var1=5&var2=10",function(error,received)){
}
Obviously, these form parameters can be parsed on the server easily. After the values are parsed on sever, the server can generate the new JSON using the form parameters that have been parsed.
Make sure that if you are running the script from a local page (or a page that is not on the website) that the server has the ability to allow cross origin (or domain) requests.
If you want to persist the data across multiple calls, you will probably have to to embed the callbacks, or use global variables.