Java Script - JSON in hidden form field - javascript

Is it possible to send POST with JSON content, which comes from hidden form field?
My form looks like this:
<form method="POST" name="form0" action="https://my_url/comment/id?Id=5">
<input type="hidden" name="id" id="inputField" value='{"number":5,"content":"aaaa"}'/>
</form>
And I would like to send POST with {"number":5,"content":"aaaa"} as JSON not as string.
If I use:
document.forms[i].submit();
it is send as a string.

An HTML form can only encode data as application/x-www-form-urlencoded, multipart/form-data or text/plain (the latter is not of any practical use).
Your existing code will encode the JSON within that.
If you want to send an application/json encoded form body, then you'll need to use XMLHttpRequest or fetch.
For example:
var xhr = new XMLHttpRequest();
xhr.open("POST", "/path/to/handler");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify({"number":5,"content":"aaaa"}));

Yes, you can do so. But you'd need to decode this on the server side, as it will just be transported as string.
Using jQuery, this would be super easy to accomplish:
$.post('https://my_url/comment/id?Id=5', {"number":5,"content":"aaaa"});
You could even pass a callback to react to whatever is returned:
$.post('https://my_url/comment/id?Id=5', {"number":5,"content":"aaaa"}, function (response){
// Do something cool here.
});

Related

$_FILES empty after AJAX upload

I'm developing a simple script to upload a file through AJAX but after form submission, the variable $_FILES is completely empty, although the file exists within php://input, but with no simple way to extract only the file. Anyone knows the reason and/or solution to this problem?
I've checked all the common solutions.
enctype="multipart/form-data"
rights to temp folder
form-tags closing
doublequotations
and the output of the file-input in JS
Nothing has solved my problem.
RED
This is NOT jquery, and I haven't found a duplicate in 24h. So please don't mark as duplicate unless you're sure it is one.
HTML
<form action="upload.php" method="POST" enctype="multipart/form-data" id="testf">
<input type="file" name="file" accept=".jpg">
<input type="submit" value="Skicka">
</form>
JavaScript
let data = document.querySelector("#testf");
data.onsubmit = function() {
var http = new XMLHttpRequest();
http.open("upload.php", data.action);
http.onreadystatechange = function () {
console.log(http.response);
}
http.setRequestHeader("Content-type", data.enctype);
http.send(new FormData(data));
event.preventDefault();
return false;
}
PHP
<?php
var_dump($_FILES);
?>
This should print the contents of my file, but
array(0) {}
is all I get.
Request payload is:
------WebKitFormBoundaryZVGq8suqFUUSFDtW
Content-Disposition: form-data; name="file"; filename="david.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryZVGq8suqFUUSFDtW--
You have a problem with your JavaScript method XMLHttpReqest. It takes at least two parameters: Method and url.
Full parameters are:method, url, async, user, password
Change your code from:
http.open("upload.php", data.action);
To:
http.open("post", data.action );
Update:
Also remove
http.setRequestHeader("content-type", "multipart/form-data")
Form data already sets its headers for content-type.
Did you checked if memory limit is set to -1 or high enough in php.
Sometime on Apache or iis server, there is also a block on high file uploads.

Escaping xsrf in Tornado with javascript POST

I have a simple form I would like to submit to a Tornado POST and I am running xsrf in tornado. The following produces the known error: '_xsrf' argument missing from POST
Has anyone solved how to submit the xsrf (like {% module xsrf_form_html() %}) in a regular HTML form using javascript? Here is the code:
<form action="#" id="form_field">
{% raw xsrf_form_html() %} # DOES NOT WORK!
<p><input type="text" id="field1" value=""></p>
</form>
<button id="button">UPDATE</button>
<script>
button.onclick = function changeField() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "/chatdata", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
value: document.getElementById("field1").value
}))
};
</script>
xsrf_form_html is for traditional html forms using x-www-form-urlencoded. It won't be recognized if you submit your form as JSON. To use non-form-based encodings with Tornado's XSRF protection, pass the XSRF token as a X-XSRF-Token X-XSRFToken HTTP header.
According to the documentation page you would just create a request that has a _xsrf request field, for example a x-www-urlencoded string of _xsrf=yourtoken. The way you had it you were sending just some JSON that had a value property, ie {"value":"token"}.
Now you can get the token in a couple ways from what I have seen, either through a set cookie or from the field that is generated from the xsrf_form_html() call.
From cookie
//helper function to read cookie, from http://www.tornadoweb.org/en/stable/guide/security.html sample
function getCookie(name) {
var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
return r ? r[1] : undefined;
}
var data = "_xsrf="+getCookie('_xsrf');
//note using this method you don't set the content-type,
//you want it to default to x-www-urlencoded
xhr.send(data);
Note you would have to build up the string to contain your other input form fields, either directly or through library methods like jQuery's serialize()
If want to just use the data straight from the form without the hassle of grabbing each input and generating a proper x-www-urlencoded string yourself; Then continue using xsrf_form_html() and create a FormData object from that form and send that. When you pass a form element to FormData() it will collect all the input values for you.
var data = new FormData( document.getElementById('form_field') );
//again no need to set the content-type as it will be automatically set internally
xhr.send(data);
//You could also use library methods like jQuery's serialize()
var data = jQuery('#form_field').serialize();
xhr.send(data);
Using FormData helps if you don't know how to get a reference to the generated field directly. Though it would more than likely have name="_xsrf" so a selector like input[name="_xsrf"] should find it. Though you would have to look at the generated html to find out.
var data = "_xsrf="+document.querySelector('input[name="_xsrf"]').value

send from client side to google apps script (server) base64 string

I have this base64 string that represents a picture that I need to send to the server. All of the ajax requests just append the data to the query string to send to the server through the url and a query string/url sort of has a limit of 2,000 characters. Well my base64 string is around 97,000 characters so how do I get this thing over to the server?
POST - this would use url and restrict to 2000 characters...right?
GET - same as post...right?
what else could I do? Convert it to a blob? what would you do if you knew what you're were doing.. because I dont lol
thanks for your time!
Edit:
I think I ended up doing something like
<form id="gform" method="POST" action="http://script.google.com/someScriptHash">
<fieldset>
<textarea id="message" name="message" placeholder="Message Body"></textarea>
</fieldset>
<button id="sendEmail">Send</button>
</form>
Then with javascript after setting the data within the form I submitted it with jquery like
$(gForm).submit();
I prefer using FormData object, its pretty straightforward, you can find clean and slick tutorial here.
Use json to post the data:
fetch('url', {
method: 'post'
headers: new Headers({'Content-Type': 'application/json'}),
body: JSON.stringify({'payload': 'base64str'})
})

Why when sending data over AJAX, do you have to JSON.stringify() your objects?

JSON stands for javascript object notation (as I'm sure you're aware), so why, when sending json via ajax do you need to turn it into a string to send it? Is it simply a formatting thing, or what?
This may belong in another place, if so, let me know, I'll close it and move it.
Obviously, I'm not looking for opinions, I'd like to know the actual answer.
Just to make sure I'm clear, I understand what JSON.stringify() does, and its counterpart JSON.parse(). I just want to know, why using stringify is required.
Thanks!
when sending json via ajax do you need to turn it into a string to send it?
If it isn't a string, then it isn't JSON in the first place.
JSON is a text based data format. HTTP is a text based communications protocol.
JSON stands for javascript object notation
JSON is based on the syntax for JavaScript literals. A JavaScript object is not JSON.
AJAX is all about HTTP requests, which are basically "text" requests to a server. That's the main reason why you have to stringify your object: That way it's turned into text that can "travel" over HTTP.
When sending data to a web server, the data has to be a string.
That's why we are using JSON.stringify() function to convert data to string and send it via XHR request to the server.
// Creating a XHR object
let xhr = new XMLHttpRequest();
let url = "submit.php";
// open a connection
xhr.open("POST", url, true);
// Set the request header i.e. which type of content you are sending
xhr.setRequestHeader("Content-Type", "application/json");
// Converting JSON data to string
var data = JSON.stringify({ "name": name.value, "email": email.value });
// Sending data with the request
xhr.send(data);

Get data using POST and AJAX

I'm trying to send some data in my server asynchronously using AJAX.
I need to send the data using the POST method because the data sent are quite
many characters and by using GET the created URL will be too big. Well that's not a problem, but for aesthetically reasons I would rather have small URLs. In order to do so I used the solution (question) explained here.
My Javascript code sending the data is:
var code = "code=" + document.getElementById("code_area").value;
xmlhttp.open("POST", "run_code.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(code);
The above code is executed when I click a button, but then the URL changes to this: localhost/code.php?code=datadatadatadatadatadatadatadatadatadatadatadatadatadata which seems is no different of using GET instead (my URL has become quite big). I used POST, not GET but still data seems to get transmitted by the URL. Any ideas why is this happening?
You could do that much more easily using jQuery.
$.post("run_code.php", { code: $("#code_area").val() });
Links:
How to add jQuery support to your code.
jQuery documentation.
$.post() documentation.
Way easier with jquery...
$.post( 'yoururlhere.com/phppage',
{code:$("#code_area").val()},
function(responseData){
// responseData is the echo'd data set from your php page
}, 'json'
);
the data within { } are the post K-V pairs
responseData is the dataset echo'd back from php
The problem after all was that I was using a submit input field in my HTML page like this:
<input type="submit" />
which when used changed (refreshed) the URL.
By using:
<input type="button" />
the problem has been fixed.

Categories

Resources