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

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'})
})

Related

Java Script - JSON in hidden form field

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.
});

Sending ajax request when data sent is html data

I worked on a mvc program where on a click of a button I send data inside a TextArea to the controller. Typically my code worked as expected but this was not the case when the data inside the TextArea consisted of a html based data.
Html Code:
<textarea id="bodyInfo"> </textarea>
<button onclick="Submit()" id="submitInfo">Create Notification</button>
ajax:
function Submit() {
$.ajax({
url: '#Url.Action("GetResults", "notification")',
type: 'GET',
data: { body: $('#bodyInfo').val()),
cache: 'false',
dataType: 'html',
success: function (result) {
$('#resultsTblInfo').html(result);
}
});
return false;
}
Sample Example of TextArea data:
<table style="width:100%">
<tbody>
<tr>
<td class="ellipses-title" style="color:#22557f;font-size:15px;font-weight:bold;margin-bottom:10px;margin-top:7px;border-right:1px solid #BFF1FD;text-align:right;padding-right:15px;"> The New Admin is Coming</td>
<td class="ellipses-text" style="padding-left:15px;" valign="center">Hello<br> Hello2</a>.
</td>
</tr>
</tbody>
</table>
What was seen above would work when TextArea was not html data but raw text but would fail when it was html data.
I was able to make this work by using
"encodeURIComponent($('#bodyInfo').val())" instead of "$('#bodyInfo').val()"
In the controller side, doing
"body = HttpUtility.UrlDecode(body)";
Are there better alternatives to achieve the same thing? Am I using encodeURIComponent against its intended nature? Why does $('#bodyInfo').val() not work when passing html values through ajax? If this question is a duplicate I would appreciate it if someone could provide me a link (i tried searching through google but found no satisfying answer)
That's exactly what you'd use encodeURIComponent for. The idea is to encode the (potentially problematic) value when sending it, then decoding it server-side in order to use it however it is need.
In fact, there's an example of this on MDN's encodeURIComponent documentation page:
To avoid unexpected requests to the server, you should call encodeURIComponent on any user-entered parameters that will be passed as part of a URI. For example, a user could type "Thyme &time=again" for a variable comment. Not using encodeURIComponent on this variable will give comment=Thyme%20&time=again. Note that the ampersand and the equal sign mark a new key and value pair.
I think that in your textarea html data, there was a "&" character.
is so, the problem is that the character & cannot be sent to a server. this is because when sending data, the browser gathers data, separed by & character http://example.php?a=something&b=other. so, if there is & character in your data the browser will not be able to distinguish if it is a data or URI component.
The common solution is to transform your data to base64 text before it is sent. this way you can decode it in your server using base64_decode fonction (case of php). you can base64 encode your data using window.btoa function in javascript. another solution is what you used.
a third solution is to replace & chars by something you know it will never exist in you textarea like [##alpha].
hope it helps

Is jQuery / Backbone mangling my UTF-8 characters?

I'm migrating the front-end of a site from an old YUI2 framework to jQuery/BackBone. The PHP/mySQL back-end hasn't changed. All is well, except UTF-8 characters sent via Backbone save (via $.ajax) are getting mangled and I can't figure out why.
Here's what I do know:
The backend handles UTF-8 fine. It hasn't changed as part of this rebuild. I know that's true, because when I change the config to load the old YUI2 front-end, UTF-8 characters work fine. They're escaped in Javascript using escape(string), passed via YAHOO.util.Connect.asyncRequest as JSON in an XMLHttpRequest, unescaped and saved in the database as UTF-8, fully readable and nice.
In the new front-end, I've added <meta charset="UTF-8"> and <meta http-equiv="content-type" content="text/html; charset=UTF-8"> to all page headers. The old front-end didn't have these settings. I only mention that because it's a difference.
In the new front-end, UTF-8 characters work fine when I save them as a <form> submit.
I the new front-end, the request Content-Type looks fine in the console. Content-Type:application/x-www-form-urlencoded; charset=UTF-8
How am I passing data in the new front-end?
Sometimes via a regular Backbone model.save(), other times passing data in options like this:
var text = $('#input-' + targetId).val();
var atts = {};
atts['target_id'] = targetId;
atts['user_id'] = userId;
atts['text'] = text;
var comment = new Comment(atts);
comment.save(
{},
{
type: 'POST',
url: '/api/comment?',
data: atts,
processData: true,
success: function(comment, response){
//success handling
},
error: function(model, response){
//error handling
},
},
);
So, what do these mangled special characters look like?
As entered in the input: テクス テクサン テクス テクサン
When I pass completely unescaped, they look fine in the request in the console in the Form Data section: text: テクス テクサン テクス テクサン, but mangled in the database as ãã¯ã¹ ãã¯ãµã³ ãã¯ã¹ ãã¯ãµã³. Perhaps this is a clue, I don't know. I've always escaped user-entered text when passing via AJAX.
When I escape(text), I get text:%u30C6%u30AF%u30B9%20%u30C6%u30AF%u30B5%u30F3%20%u30C6%u30AF%u30B9%20%u30C6%u30AF%u30B5%u30F3 in the console, and テクス%20テクサン%20テクス%20テクサン in the database.
That's better, but it's different from the old front end, which uses escape(text), passes %u30C6%u30AF%u30B9%20%u30C6%u30AF%u30B5%u30F3%20%u30C6%u30AF%u30B9%20%u30C6%u30AF%u30B5%u30F3, shows in the console as text: (unable to decode value) and saves in the database unescaped as テクス テクサン テクス テクサン
Of course, it's 2016 now and we all know escape() should not be used. We should use encodeURIComponent() instead. So, when I encodeURIComponent(text), here's what I get in the console: text: %E3%83%86%E3%82%AF%E3%82%B9%20%E3%83%86%E3%82%AF%E3%82%B5%E3%83%B3%20%E3%83%86%E3%82%AF%E3%82%B9%20%E3%83%86%E3%82%AF%E3%82%B5%E3%83%B3 which is saved in the database as %E3%83%86%E3%82%AF%E3%82%B9%20%E3%83%86%E3%82%AF%E3%82%B5%E3%83%B3%20%E3%83%86%E3%82%AF%E3%82%B9%20%E3%83%86%E3%82%AF%E3%82%B5%E3%83%B3 That technically works, and I can always decodeURIComponent when displaying this text, but that's a real pain and it's just masking the issue.
I've also tried unescape(encodeURIComponent(text)) with the following result: text:ãã¯ã¹ ãã¯ãµã³ ãã¯ã¹ ãã¯ãµã³ in the console, ãÂÂã¯ã¹ ãÂÂã¯ãµã³ ãÂÂã¯ã¹ ãÂÂã¯ãµã³ in the database.
It seems that there's some sort of double-encoding going on, or perhaps the back-end was built to handle the specific format that's passed via the YUI2 Async request. I don't know.
Any ideas for what I should try next? What are the best practices?
Now that I've had a night to sleep on it, I've realized a few things and I think I've found a solution.
It's clear now that the old front-end wasn't passing data correctly...that's evidenced by the text: (unable to decode value) in the console when sending the request. Somehow, the PHP back-end was able to handle the passed text even though there was no decoding in the api or db storage classes. That's a mystery for another day.
Here's what I did to fix the problem:
Pass text from the front-end as encodeURIComponent(text)
Decode the text in the PHP back-end api using $comment->set_text(urldecode(Request::get('text')));
The text is stored in the DB unescaped as readable UTF-8 characters and I don't need to do anything special on read/display. I will need to add the urldecode to all of my api endpoints on the back-end, but that feels like a solid approach, so I think it's resolved.
I'd be interested to hear thoughts on the use of encodeURIComponent on the front-end and urldecode on the back-end. Is this the best way to solve the problem?

OrientDB - upload image via HTTP API

Hey OrientDB Community.
I'm attempting to upload an image into my DB via HTTP API. In my super basic web-page, I select a file and click upload. Simple. Once the button is clicked, I have javascript handling it with jquery and ajax.
Context: This is an educational tool which will have student profiles with their pictures. These images won't be too big (10MB - 20MB-ish).
Here is the HTML upload form:
<h2 class="heading-blue">Upload Image</h2>
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input id="upload_image" type="button" value="Upload" />
</form>
Here is the javascript code:
$('#upload_image').on('click',function(){
console.log("UPLOADING IMAGE");
var formData = new FormData($('form')[0]);
$.ajax
({
type: "POST",
url: "http://localhost:2480/uploadSingleFile/DemoPlayground",
data: formData,
??
??
success: function (){
alert('SUCCESS!');
}
});
});
I'm not sure what to use where it says "/uploadSingleFile/" in the ajax URL parameter. Also, I'm not sure what else needs to be included in the ajax call. (Hence the "??"'s up above).
Some possibilities that I've been reading about:
Call a server-side function and pass the binary data (the image) to the function for it to handle the rest. If this is a good idea, I'm not sure how to do it...so help would be appreciated.
I've read in a couple places that Orient uses Jetty to perform this action. Any pointers on that?
I've got other types of HTTP API to OrientDB requests working, but this one is troublesome and I can't figure it out on my own.
I'm open to looking at this from new angles. Please help! :) THANKS!

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