I want to send a message to the server comprises of a few different sections. The goal is to send some x-www-form-urlencoded info with an image. I tried do sth similiar to this: http://en.wikipedia.org/wiki/MIME#Multipart_messages
This is my js function to do that:
function sendPage() {
var source = document.getElementById("pageContainer")
var serializer = new XMLSerializer
if (!source.hasChildNodes()) {
alert("nie ma nic do wysłania")
return
}
var DOMNodeInString = "content=" + escape(serializer.serializeToString(source))
// sendToServer("savePage.php", true, handleAndShow, DOMNodeInString);return
xhttp.open("POST", "savePage.php", true)
var boundary = "xxx"
var body = "--" + boundary + "\r\n"
var file = document.getElementById("imgSource").files[0]
//wysyłam obrazek
if (file) {
var reader = new FileReader()
reader.readAsBinaryString(file)
body += "Content-Disposition: form-data; name='upload'; filename='" + file.name + "'\r\n"
body += "Content-Type: application/octet-stream\r\n\r\n"
body += reader.result + "\r\n"
body += "--" + boundary + "\r\n"
}
//wysyłam pozostałe pola formularza
body += "Content-Type: multipart/x-www-form-urlencoded \r\n\r\n"
body += DOMNodeInString
body += "\r\n--" + boundary + "--"
xhttp.setRequestHeader("Content-Type", "multipart/mixed; boundary=" + boundary)
xhttp.onreadystatechange = handleAndShow
alert(body)
xhttp.send(body)
}
however, the function doesn't work. My php script is unable to receive $_POST["content"]. What should I change to improve the js script?
It is not possible to upload a file using an XMLHttpRequest. You'll need to use Flash/Java or create a hidden iframe and do an actual submit. I'd suggest using a javascript plugin for "AJAX" file upload.
Apart from #tvanfosson answer, you are missing a creation of the xhttp object:
var xhttp = new XMLHttpRequest();
Use any debugger to see that the JS works without exceptions...
Related
I have a problem with this script I got from github.
I added value.appid myself because that seemed logical but I believe it data.response.games is a response for all my games and its values.
How do I get them to either print or see what is defined?
I would need something like value.description or maybe value.ownedAchievements.
I want to see what data i have to work with for the CSV.
I am a complete noob with this so be nice, also too expert comments I will have no clue what to do with cause I have never touched javascript in my life before.
I am currently learning HTML CSS and PHP.
I have a Docker running with my SQL as well... is there also a way to re-engineer this script to directly put these value.* values inside a column? without the need to download a CSV and import it manually all the time.
<script src='http://code.jquery.com/jquery-2.1.1.min.js' type='text/javascript'></script>
<script type='text/javascript'>
$(document).ready(function () {
function exportSteamToCSV(filename) {
var url = "http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=" + $('#webkey').val() + "&steamid=" + $('#steamid').val() + "&format=json&include_appinfo=1";
$.get(url, function(data) {
colDelim = ',';
rowDelim = '"\r\n"';
csv = '"Name","Playtime","Store' + rowDelim;
$.each(data.response.games, function(index, value) {
url = "http://store.steampowered.com/app/" + value.appid;
csv += value.name + colDelim + value.playtime_forever + colDelim + value.appid + colDelim + url + rowDelim;
//csv += value.name + colDelim + value.playtime_forever + colDelim + url + rowDelim; Was correct eerste versie
});
csv += '"';
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
var link = document.createElement("a");
link.download = filename;
link.href = csvData;
link.target = "_blank";
link.click();
});
};
$(".export").on('click', function (event) {
// CSV
exportSteamToCSV.apply(this, ['steamgames.csv']);
});
});
</script>
Solved this later in Laravel with the query from the APU. the URL just gets all the data.. from there you casn pretty much do anything.
$url = "https://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=XXXXXXXXXX&steamid=XXXXXXXXXXformat=json&include_appinfo=1";
$jsondata = file_get_contents($url);
$parsed = json_decode($jsondata,true);
$games = $parsed['response']['games'];
echo SteamGame::count();
foreach($games as $game){
echo $game['name']."<br>";
$imgid = $game['appid'];
SteamGame::updateOrCreate(['name' => $game['name']],[
'name' => $game['name'],
'appID' => $game['appid'],
'storeURL' => "https://store.steampowered.com/app/".$game['appid'],
'imageURL' => "https://cdn.akamai.steamstatic.com/steam/apps/${imgid}/header.jpg",
'minutesplayed' => $game['playtime_forever']
]);
I am trying to get a very simple Stock API to work on JSFiddle.net using Quandl API: https://www.quandl.com/blog/api-for-stock-data
If I use the current ".csv" format as below, I am returned a CSV file. If I change the format to ".json" in my API, how do I recover the data so that I can use it on a website for example?
I believe I need to use a getJSON command, but I am confused as to how it works. Can someone help me out?
HTML:
<input type="text" id="symbol">
<button id="getPrice">Get Price!</button>
<div id="result">Stock Market Ticker</div>
JavaScript:
function getPrice() {
var symbol = $("#symbol").val();
var baseurl = "https://www.quandl.com/api/v3/datasets/WIKI/";
var stock = symbol+".csv";
var endurl = "column_index=4&rows=1&api_key='8mii36sd1q46uLgSTkLm";
var url = baseurl+ stock + "?" + endurl;
$("#result ").html("<a href = '" + url + "' >Hyperlink</a>");
}
$("#getPrice ").click(getPrice);
My OUTPUT using stock ticker KORS (.CSV file) is: Data Close
1/5/2016 40.72
I've recently answered to "How do I use a Quandl API?" with the following snippet, which you should adapt for your JSON:
var baseurl = "https://www.quandl.com/api/v3/datasets/WIKI/";
var endurl = "column_index=4&rows=1&api_key='8mii36sd1q46uLgSTkLm";
var quandlcode = "KORS"; // if is it's your choice?
var url = baseurl + quandlcode + ".json?" + endurl; // dont forget the "?"
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function() {
var data = JSON.parse(this.responseText).dataset.data;
// {}.dataset.data is the data matrix in Quandl
// for most datasets as far as I know ...
// then process your own way
}
xhr.send();
I need the complete code for uploading a file in dojo.
Especially the ajax call and its button creation, and its url must get stored into database. I use the following code, but it's not working:
function uploadPicture()
{
alert("yes");
var xhrArgs = {
url:"/service/ajax/uploadPictureToOption/",
form: dojo.byId("optionsForm"),
handleAs: "json",
content :{},
load: function(response, ioArgs){
if (response == "failed")
{
alert("Failed");
window.location.reload();
}
else if (response == "success")
{
window.location.reload();
}
else
{
alert("Successfully deleted");
window.location.reload();
}
},
}
var deferred = dojo.xhrPost(xhrArgs);
}
Making assumption that your file is binary, otherwise see Moz MDN - File.getAsBinary
Optionally you could make use of FormData (xhr2).
IFrame is the way to go since IE doesnt support HTML5 up until IE10
var xhr=(window.XMLHttpRequest && new window.XMLHttpRequest()),
input = dojo.byId('inputelementId')
boundary = "---------------------------" + (new Date).getTime(),
message = ""
xhr.open("POST", this.getUrl());
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
// if(input.files.length > 1) {
message += "--" + boundary + "\r\n"
+ 'Content-Disposition: form-data; name="' + input.name + '";'
+ ' filename="'+ (input.files ? input.files[0].name : input.value) + '"' + EOL;
message += "Content-Type: application/octet-stream" + "\r\n" + "\r\n";
// }
if(!!xhr.sendAsBinary) {
xhr.send(message + input.files[0].getAsBinary())
} else {
// here is the kicker; IE does not support neither FileData nor AsBinary
var fobj = new ActiveXObject("Scripting.FileSystemObject"),
fd = fobj.OpenTextFile(input.value, 1);
xhr.send(message + fd.ReadAll());
fd.Close();
}
to begin with your idea for a file upload is currently imposible using the xhr modules of dojo (AKA AJAX[only handdles plain text]).
The closest posible thing you can do is to subbmit the form to a hidden iframe.
EDIT
The code for a hidden iframe should be something like this:
<form method=”post” action=”formProcess.php” target=”hiddenIFrame”>
<input type=”file” name=”test” />
<input type="submit" value="Submit">
</form>
<iframe style=”width:0px;height:0px;border:0px;” name=hiddenIFrame />
you can also search in google as "hidden iframe submit"
i need upload a file in Chrome, and need post some params at the same request, and need Basic Authentication.
i want use javascript AJAX to do this.
but chrome do not support sendAsBinary, how can i do this?
function sendMsg(status){
var user = localStorage.getObject(CURRENT_USER_KEY);
var file = $("#imageFile")[0].files[0];
var boundary = '----multipartformboundary' + (new Date).getTime();
var dashdash = '--';
var crlf = '\r\n';
/* Build RFC2388 string. */
var builder = '';
builder += dashdash;
builder += boundary;
builder += crlf;
var xhr = new XMLHttpRequest();
var upload = xhr.upload;
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
//
}
};
if(upload){
upload.onprogress = function(ev){
onprogress(ev);
};
}
/* Generate headers. [STATUS] */
builder += 'Content-Disposition: form-data; name="status"';
builder += crlf;
builder += crlf;
/* Append form data. */
builder += msg;
builder += crlf;
/* Write boundary. */
builder += dashdash;
builder += boundary;
builder += crlf;
/* Generate headers. [PIC] */
builder += 'Content-Disposition: form-data; name="pic"';
if (file.fileName) {
builder += '; filename="' + file.fileName + '"';
}
builder += crlf;
builder += 'Content-Type: '+file.type;
builder += crlf;
builder += crlf;
/* Append binary data. */
builder += file.getAsBinary(); //chrome do not support getAsBinary()
builder += crlf;
/* Write boundary. */
builder += dashdash;
builder += boundary;
builder += crlf;
/* Mark end of the request. */
builder += dashdash;
builder += boundary;
builder += dashdash;
builder += crlf;
xhr.open("POST", apiUrl.sina.upload, true);
xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
xhr.setRequestHeader('Authorization', make_base_auth_header(user.userName, user.password));
xhr.sendAsBinary(builder); //chrome do not support sendAsBinary()
xhr.onload = function(event) {
/* If we got an error display it. */
if (xhr.responseText) {
console.log(xhr.responseText);
}
};
};
Use xhr.send(FormData). You don't need to construct the multipart-form-data yourself :)
See my response here:
Javascript/HTML5 file API reading sequential files into multipart form data
builder += file.getAsBinary();
//chrome do not support getAsBinary()
Use the readAsBinaryString method of the FileReader API. Chrome does support it.
xhr.sendAsBinary(builder); //chrome do
not support sendAsBinary()
Learn how to accomplish it at the following URLs:
http://javascript0.org/wiki/Portable_sendAsBinary
http://code.google.com/p/chromium/issues/detail?id=35705
Use a form to submit the file upload request just like you would normally, but set the target of the form to a hidden iframe. This will not refresh the page, but will still upload the file. You can also have the server spit out some JavaScript code which, once loaded into the hidden iframe, will tell you when the file is uploaded. Here's the form:
<iframe name=UploadTarget style="visibility: hidden;"></iframe>
<form method=post target=MyHiddenIframe action="Upload.php" enctype="multipart/form-data">
<input type=file name=File1>
<input type=button value="Upload">
</form>
To post some additional params, I have found the easiest way was to append them to the form's action string:
Upload.php?MyVar1=value1&MyVar2=value2
As far as I know there's no way to read form data and file data in the same request, but you can read from the information sent through the URL.
In the web, I'm building local file drag and drop upload to the server with the ruby on rails, dragging and drop a file working fine, but how to get the dragged file content in the controller with the drop event? I'm getting the file with event.datatransfer, send file through Javascript with XMLHttpRequest.
function handleDrop(event)
{
preventDef(event)
var dt = event.dataTransfer;
var files = dt.files;
for(var i = 0; i < files.length;i++)
{
http_request = new XMLHttpRequest();
var boundaryString = 'the_boundery--';
var boundary = '--' + boundaryString;
var requestbody = boundary + '\n'
+ 'Content-Disposition: form-data; name="thefilename"' + '\n'
+ '\n'
+ files[i].fileName + '\n'
+ '\n'
+ boundary + '\n'
+ 'Content-Disposition: form-data; name="thefile"; filename="'
+ files[i].fileName + '"' + '\n'
+ 'Content-Type: application/octet-stream' + '\n'
+ '\n'+files[i].path
+'\n'+ files[i].getAsBinary()
+ '\n'
+ boundary;
var preview = document.getElementById("preview");
preview.src = files[i].getAsDataURL();
var queryString="";
queryString="filename="+files[i].fileName+'&'+"file_to_upload=="+files[i].getAsBinary();
var actionUrl="/shortening/dr";
http_request.open('POST',actionUrl,true);
http_request.setRequestHeader("Content-type", "multipart/form-data; \
boundary=\"" + boundaryString + "\"");
http_request.setRequestHeader("Connection", "close");
http_request.setRequestHeader("Content-length", requestbody.length);
http_request.sendAsBinary(requestbody);
}
}
using this script calling the url and send the file through sendAsBinary method
Post method not calling the controller with the respective action
How to get the requestbody in the controller ?
Any idea?
First off, use some kind of javascript library to do AJAX and pretty much everything else. I'd suggest jQuery (http://jquery.com/)
Unfortunatelly no browser supports file uploads through XmlHttpRequest.
Read sometime ago something about Firefox supporting it, but that would be restricting and I'm not even sure that really works.
You could make an iframe and with the drop event, set the file field inside the iframe and then submit the iframe.