I am trying to send a user uploaded text file via an XMLHttpRequest with the following code:
HTML
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
Javascript
function Upload_Text()
{
var file = document.getElementById("file").files[0];
var table_type = 2;
if (document.myform.Table_Name_Text[0].checked == true) {table_type = 1;}
var Choose_Class = document.getElementById("Choose_Class").value;
var formData = new FormData();
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var result = xmlhttp.responseText;
alert(result);
}
}
var url = "Upload_Text.php";
url = url + "?table_type="+table_type;
url = url + "&Choose_Class="+Choose_Class;
formData.append("thefile", file);
xmlhttp.open('POST', url, true);
xmlhttp.send(formData);
}
However with the following PHP code, I do not receive any data from the text file server side.
<?php
$file = $_FILES['thefile'];
$table_type=$_REQUEST["table_type"];
$Choose_Class=$_REQUEST["Choose_Class"];
$fh = fopen($file, 'r');
$theData = fread($fh, filesize($file));
fclose($fh);
echo $theData;
?>
Any help with this would be great, thanks.
Try adding ["tmp_name"] to the file string. So: $file = $_FILES['thefile']['tmp_name'];
This will get the file's temporary location. Looking through your code everything else seems fine.
Related
I have list of html stored in database, I want to retrieve the data and convert it to pdf and after converting download it with via ajax request.
I tried hands on it but when the pdf get download the downloaded file is empty.
Please what do i need to do?
Thank you.
JS Code
SMSLiTe('click','.export-to-pdf',function(event){
event.preventDefault();
///export note to pdf via ajax
if (typeof notes[0].note.nid !== typeof undefined && notes.length) {
var nid = notes[0].note.nid;
var fd = new FormData();
fd.append('export_to_pdf',true);
fd.append('note_id',nid);
request.open(bigPipe.formMethod.a, 'pdf/pdf');
request.send(fd);
request.onload = function(e){
if (request.readyState == request.DONE && request.status ==200) {
//code here ....download
var data = request.responseText,
blob = new Blob([data]),
a = document.createElement('a'), d = new Date();
a.href = window.URL.createObjectURL(blob);
a.download = d.getTime()+'.pdf'; a.click();
}
}
}else{
sustainScroll(bigPipe.c_w,bigPipe.class.fixed);
var msg = 'Sorry! something gone wrong, please refresh this page and try again.',title = 'Export Failed';
$(bigPipe.document).append(flexibleDialog({content:templateHTML.flexDialog(msg,title,'_2d0',null,'Close',null,0),isClass:'export_to_pdf_failed _2d0',heigt:140,width:600}));jkg();
}
});
PHP Code
if (isset($_POST['note_id'],$_POST['export_to_pdf'])) {
$nid = (int)$_POST['note_id'];
$sql = "SELECT content FROM $notes_table WHERE note_id='{$nid}' LIMIT 1";
$query = mysqli_query($conn,$sql);
if (mysqli_num_rows($query)) {
$row = mysqli_fetch_assoc($query);
$content = $row['content'];
//create PDF file
$mpdf = new mPDF();
$mpdf->WriteHTML($content);
$mpdf->Output(time().'.pdf','D');exit;
}
}
Inspecting the response data returning from MPDF I realized the output data was a blob and since the data was already blob data. I had a clue of changing the responseType of XMLHttpRequest.responseType to blob
and it worked for now.
modified JS:
SMSLiTe('click','.export-to-pdf',function(event){
event.preventDefault();
//set request method
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
var request = new XMLHttpRequest();
} else { // code for IE6, IE5
var request = new ActiveXObject("Microsoft.XMLHTTP");
}
///export note to pdf via ajax
if (typeof notes[0].note.nid !== typeof undefined && notes.length) {
var nid = notes[0].note.nid;
var fd = new FormData();
fd.append('export_to_pdf',true);
fd.append('note_id',nid);
request.open(bigPipe.formMethod.a, 'pdf/pdf');
request.send(fd);
request.responseType = 'blob';//change reponseType before onload
request.onload = function(e){
if (request.readyState == request.DONE && request.status ==200) {
//code here ....download
var data = request.response,
blob = new Blob([data],{type: 'application/pdf'}),
a = document.createElement('a'), d = new Date();
a.href = window.URL.createObjectURL(blob);
a.download = d.getTime()+'.pdf'; a.click();
//console.log(data);
}
}
}else{
sustainScroll(bigPipe.c_w,bigPipe.class.fixed);
var msg = 'Sorry! something gone wrong, please refresh this page and try again.',title = 'Export Failed';
$(bigPipe.document).append(flexibleDialog({content:templateHTML.flexDialog(msg,title,'_2d0',null,'Close',null,0),isClass:'export_to_pdf_failed _2d0',heigt:140,width:600}));jkg();
}
});
PHP Code:
We have to output MPDF as string since we're not appending MPDF to browser;
//create PDF file
$mpdf = new mPDF();
$mpdf->WriteHTML($content);
$output = $mpdf->Output(time().'.pdf','S');//output as string
echo($output); //final result to JS as blob data
I am generating a CSV string with PHP and send it via AJAX to my Javascript function.
A simple button
<button id="download" type="button" onclick="csvExport()" name="button">CSV</button>
Call that function and should download a CSV file from the string. How can I handle that?
My PHP Function
function exportCSV(){
$profs = $this->getAllDozent();
$profs = json_decode($profs, true);
$currentID = 0;
$csv = "IDDOZENT,IDVERANSTALTUNG,BEZEICHNUNG,SWS,CREDITS,HAEUFIGKEIT_PA,FAKTOR_DOPPELUNG,SOMMER,WPF,KOSTEN_PA,\n";
// Iteriere durch Professor Array
foreach($profs as $key => $value){
$currentID = $value['IDDOZENT'];
//Hole für ID die Veranstaltungen
$veranstaltungen = $this->getVeranstaltungenByID($currentID);
$veranstaltungen = json_decode($veranstaltungen, true);
//Nur wenn Veranstaltungen da sind, abrufen.
if($veranstaltungen != "NULL"){
foreach ($veranstaltungen as $key => $value) {
$csv = $csv.$currentID.","
.$value['IDVERANSTALTUNG'].","
.$value['BEZEICHNUNG'].","
.$value['SWS'].","
.$value['CREDITS'].","
.$value['HAEUFIGKEIT_PA'].","
.$value['FAKTOR_DOPPELUNG'].","
.$value['SOMMER'].","
.$value['WPF'].","
.$value['KOSTEN_PA']."\n";
}
}
}
return $csv;
}
returns a valid csv string like that "a,b,c,d".
My Javascript looks like:
function csvExport(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200){
console.log(this.responseText);
}
};
xmlhttp.open("GET", "csvExport.php", true);
xmlhttp.send();
}
In the callback, I want to download the this.responseText as a CSV file. Is that possible?
Instead of console.log in ajax onreadystatechange handler call this function
function downloadAsFile(csv, fileName) {
var file = new File([csv], fileName, { type: "text/csv" })
var anUrl = window.URL.createObjectURL(file)
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(file)
a.download = fileName;
a.click();
}
With reference to the code attached below, I wish to reference variables which have been initialized in my processUsersAnswers.php, in my index.php file.
Code snippet in index.php
<script type="text/javascript">
function checkAnswers(){
var xhr = new XMLHttpRequest();
/* code */
xhr.open("POST", "processUsersAnswers.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
/* code */
}
}
xhr.send(vars); //
}
Code snippet in processUsersAnswers.php
<?php
$score = 403;
$userAnswers = array();
$userAnswers[0] = "bla bla";
$userAnswers[1] = "asfasfaeg";
$userAnswers[2] = "erhehdfh";
/*How can I retrieve $userAnswers in my index.php file? */
?>
For instance, how can I retrieve the value for $score in my index.php file?
Try this :
Your new processUsersAnswers.php file
<?php
$score = 403;
$userAnswers = array();
$userAnswers[0] = "bla bla";
$userAnswers[1] = "asfasfaeg";
$userAnswers[2] = "erhehdfh";
echo json_encode('score' => $score);
exit;
And in your JS :
<script type="text/javascript">
function checkAnswers(){
var xhr = new XMLHttpRequest();
/* code */
xhr.open("POST", "processUsersAnswers.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
alert(json.score);
}
}
xhr.send(vars); //
}
This is not mandatory to use JSON, but this way you can easily add more info from the server.
This question already has answers here:
handle json request in PHP
(4 answers)
Closed 6 years ago.
i try to do a very simple Webserver witch can send and get JSON Data.
JavaScript:
var username = document.getElementsByName('username')[0].value;
var antwort1 = document.getElementsByName('frag1')[0].value;
var antwort2 = document.getElementsByName('frag2')[0].value;
var antwort3 = document.getElementsByName('frag3')[0].value;
//JSON
var jsondata = {"data" :[
{"name": username},
{"antwort1":antwort1},
{"antwort2":antwort2},
{"antwort3":antwort3}]};
var url = "https://...../apps/server.php";
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "POST", url, true );
xmlHttp.send(JSON.stringify(jsondata));
console.log(xmlHttp.responseText);
alert(xmlHttp.responseText);
PHP:
<?php
$json_data;
if( $_GET["json"]) {
echo $json_data;
exit();
}
/*
if(!isset($_POST)){
//$json_data = json_decode($_POST["data"]);
echo "test POST";
exit();
}
*/
if(!isset($_POST)){
$json_data = file_get_contents('php://input');
echo $json_data;
exit();
}
?>
My main Problem is how can i send JSON to my php server. Ando how can i check this. Finaly i just want to save the Json Data and send it back.
Send JSON data from Javascript to PHP?
I try it like in the link above.
UPDATE: like rick
JavaScript: Two Button one for GET one for POST
function btn1() {
alert("btn1");
var url = "https://....../apps/server.php?json=null";
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", url, false ); // false for synchro nous request
xmlHttp.send( null );
alert(JSON.stringify(xmlHttp.responseText));
console.log(xmlHttp.responseText);
};
function btn0() {
alert("test");
var username = document.getElementsByName('username')[0].value;
var antwort1 = document.getElementsByName('frag1')[0].value;
var antwort2 = document.getElementsByName('frag2')[0].value;
var antwort3 = document.getElementsByName('frag3')[0].value;
//alert(username+" "+antwort1+" "+antwort2+" "+antwort3);
//JSON
var jsondata = {"data" :[
{"name": username},
{"antwort1":antwort1},
{"antwort2":antwort2},
{"antwort3":antwort3}]};
//alert(jsondata.data[0].name);
var url = "https://...../server.php";
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
alert(xmlHttp.responseText);
}
};
xmlHttp.open( "POST", url, true );
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send("jsonData="+JSON.stringify(jsondata));
};
PHP
<?php
$json_data = "";
if( $_GET["json"]) {
echo $json_data;
exit();
}
if(!isset($_POST)){
$json_data = $_POST["name"];
echo $json_data;
exit();
}
?>
For the POST part it's esier to use application/x-www-form-urlencoded so you can treat the POST data as if it's a form.
For the response you have to setup a callback cause your call is async.
try something like that
var url = "https://...../apps/server.php";
var xmlHttp = new XMLHttpRequest();
xmlHttp .onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
alert(xmlHttp.responseText);
}
};
xmlHttp.open( "POST", url, true );
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.send("jsonData="+JSON.stringify(jsondata));
For the php
if(!isset($_POST)){
$json_data = $_POST["jsonData"];
echo $json_data;
exit();
}
It's 10 years than I don't write a line in PHP but I hope the concept is clear.
From System.Shell.itemFromFileDrop I get System.Shell.Item object item. I've tried this:
var oStream = new ActiveXObject("ADODB.Stream");
oStream.Type = 1;
oStream.Open();
oStream.LoadFromFile(item.path);
content = oStream.Read();
var thisObj = this;
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myUrl.com//");
xhr.send(content); //NOT WORKING
oStream.Close();
oStream = null;
but I really don't know what to pass in the xhr.send function.
The serverside PHP code is as simple as it could be:
if (file_exists($_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],$_FILES["file"]["name"]);
header("{$_SERVER['SERVER_PROTOCOL']} 200 OK");
header('Content-Type: text/plain');
echo "http://myUrl.com/" .$_FILES["file"]["name"];
}
any ideas what am I doing wrong ? Or any ideas about how to upload files from windows gadget at all?