Adding Datas via Javascript to existing JSON file on Server - javascript

I have following problem. I know that this is discussed quiet often, and i tried a lot of possibilities, but none is working up to now.
I have some datas in my javascript file, which i want to add to a already exsiting .json file on my server. I tried to do it the following way, but whenever i open the .json file after calling ajax_get_json(), no new datas are added.
function ajax_get_json(){
var hr = new XMLHttpRequest();
hr.open('POST', 'myyjson.json', true);
hr.setRequestHeader ("Content-type", "application/x-www-form-urlencoded");
var us = document.getElementById("firstname").value;
var msg= document.getElementById("message").value;
hr.onreadystatechange= function(){
if (hr.readyState == 4 && hr.status == 200){
var obj = JSON.parse(hr.responseText);
obj['participant'].push({"user": us, "message": msg});
var sendingObj =JSON.stringify(obj);
}
}
hr.send (sendingObj);
}
My myjson.json File has following structure:
{ "participant":[
{"user":"Steven", "message":" Hey,i m in!"},
{"user":"Tim", "message":" i wrote sth."},
{"user":"lukas", "message":"example"}
]}
Does anyone have an Idea what the problem yould be or is there a better way doing it?
Thanks in advance!

With javascript on client it's not possible to write JSON on server. If that would be possible, that would be kind of bad from the security perspective. You need to write JSON on server with what ever language you are using there (PHP, Java, javaScript). Then you call that server function from client with AJAX for example. It could go like this:
Javascript on client side request for example url www.yourserver.com/writejson.php?u=steven&m=Hi
On server you catch that request and write to JSON file. username is steven and message is Hi.
By the way, you have misunderstood XMLHttpRequest.send method. You are not sending data to be saved on server. You are firing XMLHttpRequest. Here is walkthrough how your code is executed:
function ajax_get_json(){
var hr = new XMLHttpRequest(); // 1.
hr.open('POST', 'myyjson.json', true); // 2.
hr.setRequestHeader ("Content-type", "application/x-www-form-urlencoded"); // 3.
var us = document.getElementById("firstname").value; // 4.
var msg= document.getElementById("message").value; // 5.
hr.onreadystatechange= function(){ // 6.
if (hr.readyState == 4 && hr.status == 200){ // 8. this is called every time XMLHttpRequest state changes
var obj = JSON.parse(hr.responseText); // 9. this is called when XMLHttpRequest is completed and response is gotten
obj['participant'].push({"user": us, "message": msg}); // 10.
var sendingObj =JSON.stringify(obj); // 11.
}
}
hr.send (sendingObj); // 7. sendingObj is undefined

Related

Open local server file using plain javascript

I want to load locally stored data using plain javascript (no jquery for example) and then use it to display it in a table in html. My project structure looks like this:
root
- js
-- main.js
- res
-- data.csv
- index.html
I tried using a XMLHttpRequest, but somehow I get status 0 when trying to load the file and when printing the response text it prints out nothing at all.
The following method is called using window.onload:
var url = "file://../res/data.csv/";
varxmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
I don't think you can access the file system through most browsers.
Even if it worked locally, it wouldn't work as soon as you put your page up on a server. This is because the client will be asking for a file that is local to itself, not the server.
Chrome may have something for you though:
https://www.html5rocks.com/en/tutorials/file/filesystem/

producing a GET response to an ajax POST

In javascript I am POSTing with ajax and I need to get a reply from my Python program. The following code shows the javascript, but how does I produce the desired responseText from a GET on the Python side?
In this example I am want a Yes or No reply to a question for the user as to whether to change the name provided or not.
I understand how to receive the name and value in the python POST, but I don't know how to produce the response in the associated python GET.
function changeName(name,value){
var json = '[{';
json += '"name":"'+name+'",'
json += '"value":"'+value+'"}]'
loadDoc(json,"edit")
}
function loadDoc(data,url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", ("/"+url), true);
xhttp.setRequestHeader("Content-type", "text"); #or something
xhttp.send(data);
}
My typical response in Python GETs follows one of the following 2 patterns, but neither seems to allow me to reply in this case.
self.response.out.write(template.render( template_values))
return webapp2.redirect("/templatename/%s" % variable)
(No PHP or jquery, please.)

Send multiple files from front end to POST method

Here is my Code sample: https://jsbin.com/qokiyomivu/edit?html,js,output
How can I send multiple files to my POST method and then attach these with email from the Java method?
Currently if I select multiple files only one is being sent and attached to the email written in the Java method. How to attach all I select ?
FYI, I have declared filesToUpload as MultipartFile like private MultipartFile filesToUpload in my Bean.
That’s a good question that I myself have spend some time to refine to a good solution.
I came out with:
$('#filesToUpload').change(function(e) {
$.each(e.currentTarget.files, function(i, file: File){
var xhr = new XMLHttpRequest();
xhr.onprogress = function (event) {
'do something'
};
xhr.onloadend = function(event){
var status = (<XMLHttpRequest>event.target).status;
if (status != 200) {
console.error(String.format("Server did not return a 200 but: {0}.", status));
}
else
'upload completed';
}
xhr.open('POST', 'urlpath', true);
xhr.send(file);
});
});
Thsi will upload yout files on every change - but my main purpose by showing this code, is to guide you towards XMLHttpRequest.
If you have large files, there are a technology to chunk up your data, but that takes a bit af work to get up running.

How to receive data from XMLHttpRequest in chome extension via javascript?

I wanna to send request form a webpage to chrome extension, and then in chrome extenison receive data and read data, is there any way to this?
Ex:
In doman www.nope.com/sendRequest.html will sent data to chrome extension via url chrome-extension://xxxxxxx/getData.htm?isToken=abc, and then extension will receive and can read data "isToken".
Here is my code in sendRequest.html
<script type="text/javascript">
function sendRequest() {
document.write("Sending request");
var req = new XMLHttpRequest();
req.open("POST", "chrome-extension://xxxxxxxxxx/getData.htm?isToken=abc", true);
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
alert(req.responseText);
document.write("OK");
}
}
};
req.send();
}
</script>
And in chrome extension file getData.htm, how can I get data?
(Edit: what type of data are you sending? Could you pass it through as a JSON encoded string, via GET? JSON.stringify() and JSON.parse() may be of use to you. :)
The following may be useful as a guide for accessing that POST/GET data. :) )
As far as I am aware, this is best done using some form of server side scripting. You could use window.location.search in JS, and split the string and perform the necessary functions, but I think server-side scripting may work best. :)
An example of a JS implementation could be as follows:
var url = window.location.search;
var params = url.substr(url.IndexOf("?") - 1, 30);
This would grab the parameters (starting at ? (inclusive), and continue for 30 chars. You could also use something like var params = url.substr(url.IndexOf("?") - 1, url.length); to get the whole parameters list.
How you use this from then on, is up to you, but you could pass it through a switch() or whatever you need. :)
Obviously, this being a chrome extension would limit your options regarding any server-side processing. :/
Edit: The above would go in getData.htm. :)

Json problem in fetching data

<script>
function jsonfunc(){
var data ="publick="+document.getElementById("publickeyval").value+"&privatek="+document.getElementById("privatekeyval").value;
var url="http://www.remoteapiserver.com/example_api/example_adcpatchaapi.php?"+data;
alert(url);
var my_JSON_object = {};
var http_request = new XMLHttpRequest();
http_request.open( "GET", url, true );
http_request.onreadystatechange = function () {
if (http_request.readyState == 4){
alert(http_request.responseText+"#"); // showing only # //
my_JSON_object = JSON.parse( http_request.responseText );
}
};
http_request.send(null);
}
</script>
I was as asked my question as per comment i read Json and writing above code in my php page.But still this is giving problem.I am not getting fetched dada from remote server.I am getting only "#" in alert box.
I highly recommend a JavaScript Framework like jQuery for this kind of stuff. It definitely makes this a lot easier. jQuery lets you do cross-domain requests, if you use JSONP (take a look at the docs). The code would look something like this:
$.getJSON(yourUrlGoesHere, function(data) { // ready callback
// data is an object; no need to parse it manually.
});
Sometimes it't better use some library:
JQuery or Moootools: http://mootools.net/docs/core/Request/Request.JSON
Implement this in native JS is difficulty if we want use it in all browsers ;)

Categories

Resources