Add new object to json using javascript - javascript

I have a json file with user information (login and password). How to add a new object to Json using js? (so that after loading the page it would be saved in Json) Is it possible at all? Nowhere can I find the answer. I can use only (javascript, jQuery, json)
json
{
"users":[
{
"login":"admin",
"password":"1207"
}
]
}
js
$(function() {
const getOb=$.getJSON('user.json');
var obj = JSON.parse(getOb);
obj['users'].push({"login":"Donald","password":"78"});
getOb = JSON.stringify(obj);
});

You are fetching data over HTTP.
If you want to save it back to the server, then you need to make an HTTP request to the server (typically a PUT or POST request), and then have server-side code (written in the language of your choice) accept the HTTP request and save the data.
Typically you would save the data to a database from which you generate the JSON on demand rather than using a plain file (which saves you from race conditions).
Note:
Storing passwords in plain text is dangerous. Use a hashing algorithm.
Sending your authentication data to the client and asking it to authenticate itself:
Leaks your authentication data to anyone trying to log in
Allows anyone to edit the JS in their browser and claim to have logged in successfully
Move to a server-side authentication system where you send your credentials to the server, and then server-side code checks if they are good and then returns a token (JWT is currently a popular way to do this) which can be used to prove you are logged in.

Related

In express Node JS , how do I handle a request in which the user requests both a HTML page and a sends a request parameter?

I am creating a web app where a user can type in /poll/:id in order to retrieve a poll with the given id from my database. Presumably, in order to do this, my Node JS express server would first need to send over the HTML I want the poll to be displayed on, the JavaScript that handles the frontend and then JSON data representing the poll.
I am running into a roadblock because I have no idea how to handle such a request. As a jumping off point, I tried to make my server simply send over the html page in question upon receiving the request (and hence not using express's static server). The code is as follows:
app.get('/poll/:id', function(req, res, next){
res.sendFile('poll.html');
});
However, the page on the user's end does not handle any of the CSS, hence the page is not styled at all upon being sent to the user, nor is the frontend JS supported. What exactly do I have to do in order to ensure all of that is functional in the frontend? Is there an easier approach to this that I am not realizing?
If you want to generate the HTML on the server-side, use a templating engine, ejs for example. There u would be able to retrieve the data from the database and easily render the page according to that data.
On the other hand, if you want to retrieve the data using javascript then just serve the HTML files statically, and then create another route which would only respond with the JSON object retrieved from the database, (which the frontend would request), and then the frontend-javascript would render the application

How to push data to external JSON file (Using jQuery)?

I want to push an data to array in external local JSON file using jQuery.
So any ideas?
I have tried this:
$.getJSON('test.json', function(data) {
data.push('Something');
});
And it wont be pushed into local JSON file
You can do this in JavaScript with node.js (or a multitude of other languages/platforms) but not with a browser & jQuery.
Here's how to read and write a json file in node.js
On the other hand, users could upload a JSON file to your server, where you modify the structure and send them a modified JSON file back as a download.
Is not possible to write files using Javascript (can cause security problems through xss, csrf ..)
No, JavaScript doesn't have access to writing files as this would be a huge
security risk to say the least. If you wanted to get/store information server-
side, though, you can certainly make an Ajax call to a PHP/ASP/Python/etc.
script that can then get/store the data in the server. If you meant store data
on the client machine, this is impossible with JavaScript alone. I suspect
Flash/Java may be able to, but I am not sure.
If you are only trying to store a small amount of information for an
unreliable
period of time regarding a specific user, I think you want cookies. I am not
sure from your question what you are trying to accomplish, though.
Read/write to file using jQuery
You cannot access the files in a local client's machine. May be for development setup you can do it. But before you need to restart the browser with file-access flag set.
You can see my answer here that describes the opening browser setup with the flag set.
Then, you can use the following code to read the data.
var data = [];
var url = "/Users/Vignesh/Desktop/test.json";
var req = new XMLHttpRequest();
req.open("GET",url,true);
req.onreadystatechange=function(){
if(req.readyState === 4)
{
data = JSON.parse(req.responseText);
}
};
req.send();
To write into the file you may look into this. (Not sure it is working or not)

Access PHP SESSION value in JavaScript

I generate a session value for each visitor on my website. If they submit the form, it sends the data via a jQuery AJAX request to my PHP validator script.
This script performs several checks on the data the user submitted. If everything has been validated, it returns a sha256 hash which is generated with the function hash_hmac('sha256', 'success', $_SESSION['secret_key']). I hash this so users cannot manipulate the response with software such as Charles.
The jQuery request receives the hashed string and I have to hash 'success' with the secret key again to check if they match. However, the secret key is stored in a PHP session and I am not able to figure out how to get access to it through JavaScript.
An AJAX request to a PHP script would not be ideal — an attacker can then edit the response to make it match with their own hashed strings.
I'll simply elaborate on my comments in this answer.
You say
An AJAX request to a PHP script would not be ideal — an attacker can
then edit the response to make it match with their own hashed strings.
They can edit the response, but if it's all done client side, they can still edit it.
You want to send the data hashed, then you want the client to be able to check the hash, so I'm not sure what the point in hashing would be, other than security in transport. I can't tell you what you really need, because I'm not seeing the use case here.
I do know you'll either need to go to the server for something you want to keep secret from the client. There's no security on the client side.
As long as you are using javascript in your php file, something like this will suffice...
<script>
var secret_key = <?php echo json_encode($_SESSION['secret_key']); ?>
<script>

Get data from URL, or possibly ajax?

I was wondering how I can get data from the server side that is being passed to my page via encrypted url using java script? Let say I have this in visual basic in my code behind,
lnkToAPage.NavigateUrl = RelativePagePaths.ThePage + "?"+ QueryStringModule.Encrypt("PageMode=" + pageMode ...
I need to extract a piece of that data, which I get from an object on the server, to do something with it on the client side using javascript. I understand I can get the data from the url like it says here
but the data in the url is encrypted so the data I get from there is useless, I can send it without the encryption but that exposes to much. So is there a way I can use ajax to retrieve that data or object, or maybe there's another way? Or is it not possible at all?
I am not aware of what encryption protocol you are using, but if you get an encrypted version of your attributes, you need to decrypt it using the same protocol with javascript.
On the web, it is common practice (and a good one) to encrypt the connection using HTTPS. it protects anyone from seeing the parameters as explained here.
This does not seem to be an ajax related problem (from what I understood of the question).

Javascript (client-side): Database query and Data handling

I have built a web application that accepts a Member_ID # from the client (javascript). The Member_ID is stored as a var in my javascript… now I need to make queries with it…first query to get member information (name) and then join tables to gather information for health plans that the member is elligible under … and so on.
As far as I can remember the concept is… send a async request to the server and wait for a response, once the response is received, store it and then parse it to extract useful information.
The end goal is to use the 'useful' information to plot graphs using HTML5 Canvas.
I need some direction with how to make the query? because when I read this forum, it is recommended that client-side query is 'bad' for a plethora of reasons.
Since most of my stuff is happening in the client side... few things in C# asp.net...how do I proceed?
It is also important to note that the web application should be accessible via the internet. outside the local network.
Does it make sense to Call a Web Service from the Client Side Using the AJAX Extension Toolkit??
You must handle it server side. Think about the ajax request as a simple POST or GET in the format of ?member_id=123&time=321 pointed at your handler file.
In your handler file you can construct your query from the request variables, execute it, and give a response by printing to the screen in either JSON or XML format.
Take a look here:
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jQuery.getJSON/

Categories