I'd like to send JSON form data to websocket server instead of submitting the form and reload the page.
In AJAX it is pretty simple and straightforward thanks to native FormData() web-api object:
myform.addEventListener("submit",function(e) {
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.onload = myFormHandler.bind(xhr);
xhr.open('POST',myform.action,true);
xhr.send(new FormData(myform));
}
It would be nice to have similar functionality in webSockets, to transform the form data into JSON object and use it like this:
myWebSocket.omessage = myFormHandler;
myform.addEventListener("submit",function(e) {
e.preventDefault();
myWebSocket.send(JSONformData);
}
But the reference (see the link above) says that FormData has only append method, I don't know how to send the form data to the websocket server and extract them there.
On code.google.com I've found something very close to what I need: form2js but it can't handle files (it can be done using FileReader.readDataAsURL). Should I add the file handling functionality into that code, or is there any native solution like FormData object?
Related
I would like to have a button that when clicked gets a file (in this case a dynamically generated PDF) from a (predefined) URL on the same domain, and sends it to a (php) backend to be saved.
I am guessing that the best way to do this is to somehow load the file returned by the URL into a javascript variable, base64 encode it and send that to the backend with an ajax POST. Then on the backend I would base64 decode it and save it as a regular file.
Is this the right approach, or is there a better way to do it?
If this is the right approach, the part I am not sure how to do is getting the file from the URL into a variable. Once it's there, I guess I can use btoa() to base64 encode it. The other thing I am not 100% sure about is whether that will be compatible with base64_decode() in PHP for when I decode it?
Update
You say, the URL is predefined, and you don't know how to get in into a javascript variable. I guess, the URL is defined in the backend (PHP). So you could simply set/inject it in the client side code (javascript) with PHP.
Don't post the URL back from the client to the server, as there seems to be no need for that, and the URL could easily be changed by the user (security issue)!!!
So, maybe a better way would be to keep the URL on the server side, and inject it in the client page using php, without posting it back to the server.
Original answer
This answer is only appropriate if the client generates the URL and you have a secure way to verify it, as every client side input has to be treated as potential harmful user input.
In my opinion this is the absolutely right approach. Yes, you should base64 encode your variable. You could put the base64 encoded string in a json object and post this json object via ajax, or post it as plain text in your post body. Make sure to verify this as a client input!
I see no reason why btoa()/base64_decode() should not work. Base64 is platform independent.
I figured it out. It's a mix of vanilla and jQuery because the vanilla is from this article and the project I am working in already has jQuery available for $.ajax to make the POST to the backend easier.
var oReq = new XMLHttpRequest();
var fileUrl = '[URL from PHP]';
oReq.open("GET", fileUrl, true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
let arrayBuffer = oReq.response; // Note: not oReq.responseText
if (arrayBuffer) {
let binaryText;
let byteArray = new Uint8Array(arrayBuffer);
for (var i = 0; i < byteArray.byteLength; i++) {
binaryText+=String.fromCharCode( byteArray[ i ] );
}
$.ajax({
type: "POST",
url: "/path/to/backend-upload",
data: {"fileData":btoa(binaryText)},
success: function(resultData){
alert("File Uploaded");
}
});
}
};
oReq.send(null);
and in the PHP backend:
file_put_contents("/path/to/destination", base64_decode($_POST['fileData']));
I am looking for a way to either read an image src in PHP or read a JavaScript variable in PHP.
The plan:
I have a webcam script in JavaScript that takes an image using the base64 Canvas method, but I need it to update a MySQL record using PHP.
After trying many methods; cookies, submit forms, ajax. I decided that making a post here was the best idea.
(!) Use with caution. This is a proof of concept. In PHP you should never just accept and compute client-side data without checking it for malicious code and sanitizing the input. (!)
You could send it to PHP using AJAX by putting your base64-source into formData.
Javascript:
// ajax.js
var xhr = new XMLHttpRequest(); // initialize a new XHR
var formData = new FormData(); // initialize form data
var myFile = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAACWCAYAAABkW7XSAAAEaElEQVR4Xu3UgQkAMAwCwXb/oS10i4fLBHIG77YdR4AAgYDANViBlkQkQOALGCyPQIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiBgsPwAAQIZAYOVqUpQAgQMlh8gQCAjYLAyVQlKgIDB8gMECGQEDFamKkEJEDBYfoAAgYyAwcpUJSgBAgbLDxAgkBEwWJmqBCVAwGD5AQIEMgIGK1OVoAQ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JmqBCVAwGD5AQIEMgIGK1OVoAQIGCw/QIBARsBgZaoSlAABg+UHCBDICBisTFWCEiDwAIGUVl1ZhH69AAAAAElFTkSuQmCC';
xhr.open('POST', '/requestHandler.php') // init your request
xhr.onreadystatechange = function () {
// check if the server was able to compute the XHR
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
// handle the response
console.log(xhr.responseText) // log the PHP output
}
}
// a form data element needs a descriptor/name and a value.
formData.append('myfile', myFile);
xhr.send(formData); // send your xhr to the server
PHP:
// requestHandler.php
<?php
if('$_POST') {
echo $_POST['myfile']; // this is your image source
}
Further information:
XMLHttpRequest
FormData
PHP $_POST
Problem: I'm working on a site written with a master page and a wrapper form. The page I'm writing needs to upload a file to the server to be validated.
What's needed: A way to submit a file without using a form and receive that form on the server in a WebMethod.
What I've tried: Using an XMLHttpRequest to send FormData to a WebMethod. The FormData is created and the file is appended like so:
let dataXML = new FormData();
dataXML.append("xml", $("#fileUpload")[0].files[0]);
sent it like this:
let request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200)
// Do stuff with the request.responseText
};
request.open("POST", PageName + "/" + Route, true);
request.send(dataXML);
with a webMethod like this:
[WebMethod]
public static string myWebMethod(MultipartFormDataContent Files)
{
// Do stuff with the file
}
The WebMethod does not run at all. I'm assuming this is an issue with the WebMethod and its parameters. If I look at Page_Init() (which is run because it's returning the pages html right now rather than running my WebMethod) I can see the file in HttpContext.Current.Request.Files[0] but I don't know how to make the WebMethod run.
And before anyone says it: yes, I tried JQuery AJAX but it doesn't make a difference, the problem doesn't appear to be client side (the file was uploaded in both cases). I don't really care between JQuery AJAX and XMLHttpRequest.
I need to upload pdf,excelsheets,doc. etc format to server - data in request file using simple Javascript.
I was thinking to do with Blob , byte stream .. is it possible.
Can someone explain ?
Using vanilla Javascript you can create an XMLHTTPRequest object and send the file to any endpoint of your choice.
Some questions to consider when you are working doing this:
Are you looking to upload just the file or do you need to upload any associated data with it?
Do I need to support multiple files? If so, you could use the FormData object (it is a defined key value pair type) to hold multiple files if you have an HTML5 input form with the multiple attribute set. Make sure your project allows support for it.
What server/framework are you using? How do you access this? A request object? Something similar?
How do you want/need to create a selector for your html file input for use with Javascript? I'll provide an example of using the html attribute of id below.
Do you need to support CORS? Essentially, are you sending a request to the same server or a remote server? If remote, you'll need to configure CORS in your server.
file input that allows multiple file support
<input type='file' id='multiple-file-input' multiple>
javascript example
// idElementForFiles - id of the <input type="file" multiple>
// endpoint - URL to send your request to
var idElementForFiles = 'multiple-file-input';
var endpoint = '/path_to_server/request';
var formdata = new FormData(); // Create FormData
var uploadedFiles = document.getElementById(idElementForFiles); // set our uploadedFiles variable
// Iterate through each file in uploadedFiles
for (i = 0; i < uploadedFiles.files.length; i++) {
// Appending each file to FormData object
// sending to 'endpoint' as an array of {'name_of_file': 'binary_file_data'}
formdata.append(uploadedFiles.files[i].name, uploadedFiles.files[i]);
}
// create new Ajax call and send
var xhr = new XMLHttpRequest();
xhr.open('POST', endpoint);
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr); // log response object
}
}
I want to do the following and do not know how to best approach it:
I have a Facebook like Wall in a Social Website I created.
Every wall Post is a PHP Object with several "comment" objects attached to it.
All Relevant Data is currently fetched from the Database at the time the page loads and works as I wanted it to.
My Wall is getting quite long so I would like to implement infinite scrolling via JQuery and Ajax.
I wanted to send a request for more post objects to a php page which would instantiate them and send the finished objects back. Now I have read that this is bad practice sending PHP Objects via JSON and that it can lead to Problems and potential attack vectors.
How should I approach this? Write the entire wall in Jquery? Have it send Requests for the Data to PHP but display everything with JQuery instead of PHP?
A few pointers would be very appreciated.
You should send AJAX request for needed posts and return ready HTML which you can just append to the container with $('wall_container').append($(new_post_html));
I would say load the initial page and append the data to the wall as you get it. No need to send objects. All the data you need will be in the responseText of the request object
var request = new XMLHttpRequest();
var form = new FormData();
form.append('param_1',val_1);
form.append('param_2',val_2);
request.open("http://example.com/getPostsForWall.php","POST",true);
request.send(form);
request.onreadystatechange = function(){
if(request.status==200 && request.readyState == 4){
//Successful request
response = JSON.parse(request.responseText);
//Want to append a title using jquery to your wall that has an id of wall?
$("#wall").append("<h2 class='wall-post-title'>"+response.post_title+"<h2>");
}
};
This is assuming you have your server side code returning a variable with the key 'post_title' when you send your response