AJAX file upload to php, nothing being sent? - javascript

I have an input on my website which allows the user to select a file for upload
<input type="file" name="file" id="file" />
At the end of my page, I have a button which calls a javascript function. This function needs to check if the user has specified a file for upload and if so, upload the file (php) and obtain the filename.
How can I go about accessing the file input form from javascript? i.e. how can I get the 'post' file information to call 'upload_file.php' with.
ps. I'd rather not use JQuery
edit - i've tried this and it doesn't seem to work
function uploadFile(){
var files = document.getElementById('file');
var file = files.files[0];
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST","uploadfile.php",true);
xmlhttp.setRequestHeader("Content-type", "multipart/form-data")
var formData = new FormData();
formData.append("thefile", file);
xmlhttp.send(formData);
}
php:
<?php
echo "Upload: " . $_FILES["thefile"]["name"] . "<br />";
echo "Type: " . $_FILES["thefile"]["type"] . "<br />";
echo "Size: " . ($_FILES["thefile"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["thefile"]["tmp_name"] . "<br />";
?>
is giving me an alert saying the file name is blank, the type is blank, size is 0 etc...

It is accessable through the DOM, just like any other element. The only restriction is you can't alter it for security reasons.

http://www.simonerodriguez.com/ajax-form-submit-example/
Check this link for ajax post.
You can simply post it like a normal form, need no extra efforts for same.

Have u considered HTML5 File API?
Related StackOverFlow:
Html 5 File upload

I think you need some thing like this:
http://jsfiddle.net/kHQLp/4/

Doing this through AJAX has the following problems can achieved as thus (except for IE).
1) It is impossible for IE. If somebody has found a way give me a shout. What I did is just submit the form in the normal way and return an updated page.
2) For FF (and if memory serves me right Opera and Safari) the following snippet works
var fileTag = document.getElementById('id for input element');
var file = fileTag.files[0];
// You can check the type here by checking the string file.type
var data = file.getAsBinary(); // Or getAsText()
3) For Chrome use this code
var fileTag = document.getElementById('id for input element');
var file = fileTag.files[0];
var reader = new FileReader();
reader.onload = function() { /* Use reader.result as it has loaded */ };
reader.onerror = function(e) { /* and error occurred - handle it */ };
reader.readAsText(file); // I think there is also a function readAsBinary.
When you have got the contents of the file you can post it using AJAX

Solved my problem by replacing:
xmlhttp.setRequestHeader("Content-type", "multipart/form-data")
with
xmlhttp.setRequestHeader("enctype", "multipart/form-data")

Related

How can I run a php script when a user clicks a link without redirecting to that particular php page, and download an mp3 file at the same time?

I have an mp3 file whose downloads value am counting and updating well in a MySQL database when I run my php script by going to the scripts address in the address bar like this https://groupkse.net/music_files/countDownloads.php?id=3. My issue is I want to run this php script without redirecting my browser to this location, when a link is clicked to download that mp3. NB: The mp3 is in the same directory with the countDownloads.php and the page containing the link is in a different directory, but on the same server, i.e. https://groupkse.net/songReleaseHtml/megaMuQuarantine.php
Code from countDownloads.php is below:
<?php
//Make connection with database
$conn = mysqli_connect("localhost", "groupkse_music_admin", "my_Password", "groupkse_music_downloads");
//Check connection
if (mysqli_connect_errno()) {
printf("Connection failed: %s\n", mysqli_connect_error());
exiit();
}
//Passing which song needs download increment
$incomingData = $_SERVER['QUERY_STRING'];
$data = substr($incomingData, strpos($incomingData, 'id=') + 3);
$id = mysqli_real_escape_string($conn, $data);
//echo "$id";
$query = "UPDATE `music_downloads` SET `downloads_number` = `downloads_number` + 1 WHERE `Id` = '$id'";
mysqli_query($conn, $query);
?>
And code from my link in the megaMuQuarantine.php:
Download MP3
Download MP3
Add this input to point to the php file that counts downloads.
<input type="hidden" id="downloadCounter" value="LINK TO COUNTER" />
Put this at the bottom of your web page:
<script>
document.getElementById("dButton").addEventListener("click", function(event){
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
location.relod;
}
};
xhttp.open("GET", document.getElementById("downloadCounter").value(), true);
xhttp.send();
});
</script>
To execute a PHP code without actual page action requires AJAX as pointed out by #nikistag; security issues being secondary as per now. For file downloads, this can be tricky and I would advice that you go with the 'download' attribute for html5. If such links with download attribute is clicked, it will download the file - major file types already covered. Now figure out a way to create this dynamic link; you can easily do this with jQuery or pure JS and perform auto-click on it when your button is clicked.
//hide this somewhere in your current page
<a id="choiceMusic" href="../music_files/default_music.mp3" download>
//to change href according to choice, use something like this in that master function
var currentMusic = "../music_files/"+ chosenOne.mp3;
$("#choiceMusic").attr("href", currentMusic);
//when ready to call this; //if fails, try: $('#choiceMusic')[0].click(function(){});
$('#choiceMusic').trigger('click');
Ensure that all these happen after the document if fully ready
$(document).ready(function(){
//safe to do your staff now,
});
Now call your master function and don't forget to include your Ajax function for updates
I put together the information from the above answers and came up with a solution that works for me. I hope it's a practice that is allowed!
Made two interdependent links with one of them invisible:
Download MP3
<a href="../music_files/mu_quarantine.mp3" download id="downloadSong" hidden></a>
Some AJAX and another JavaScript function to run my PHP file in the background and auto click the invisible link:
var dButton = document.getElementById("dButton"),
hidden_dLink = document.getElementById("downloadSong");
// Act on clicks to a elements
function downloadMP3() {
// Clicks the hidden anchor tag
hidden_dLink.click();
}
$(document).ready(function () {
$('#dButton').on('click', function () {
$.ajax({
url: 'https://groupkse.net/music_files/countDownloads.php?id=3',
method: 'GET',
xhrFields: {
responseType: 'blob'
},
success: function (data) {
var a = document.createElement('a');
var url = window.URL.createObjectURL(data);
a.href = url;
a.download = 'file.mp3';
document.body.append(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
}
});
});
});
If there is a way in which this code can be properly written, I would appreciate the guidance! Like I have earlier said somewhere, am new to programming. I further need to refresh a certain element where am echoing the id value from my database after the ajax has run successfully so that the number of downloads is updated on link click.

Passing variables in a URL of a php page to JavaScript and to another PHP

Based on the code in this link http://webaudiodemos.appspot.com/AudioRecorder/index.html, I am making changes to send the recorded audio file to server by passing a sessionId via URL. The php page is http://xxxxx/abc.php?sessionId=Sam. PHP versions: PHP 5.4 PHP 5.5.22. I am using the 2nd method from this link:How to pass variables and data from PHP to JavaScript?. The abc.php page has reference to a few JS codes as with the index.html from the link above. abc.php page process the URL values correctly with the following code:
<div id="bottom">
<?php
$faid = $_GET["sessionId"];
echo htmlspecialchars($faid); // tested working
?>
</div>
On the recorder.js JavaScript,I have a function that tries to pass the URL values to another PHP while uploading the audio file to server - The fname is not being passed on ... it seems .. can the xhr.send(blob) will still send the fname?
Recorder.setupDownload = function(blob){
var div = document.getElementById("bottom");
var fname = div.textContent;
var xhr = new XMLHttpRequest();
xhr.open('POST', "./uploads.php?" + fname, true);
xhr.onload = function(e) {};
// Listen to the upload progress.
var progressBar = document.querySelector('progress');
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
progressBar.value = (e.loaded / e.total) * 100;
progressBar.textContent = progressBar.value; // Fallback for unsupported browsers.
}
};
xhr.send(blob);
The uploads.php in the server has the following script to receive the value and to create an audio file - but it is not creating the audio file - however, if I fix the file name (eg: "filename123") it writes the audio file - so the issue is in passing the variable name - I am a newbie and I wonder what am I missing?:
<?php
ini_set("display_errors", true);
error_reporting(E_ALL);
if(isset($_GET['fileId']) && !empty($_GET['fileId'])){
$id = $_GET["fileId"];
}
$fp = fopen( $id, 'wb' ); // writes the audio file
fwrite( $fp, $GLOBALS['HTTP_RAW_POST_DATA'] );
fclose( $fp );
?>
Update: It is working!
You didn't give your value a name, so you're passing a value that will appear as DIFFERENT key in every page.
e.g. each of your users will have something like
http://example.com?foo
http://example.com?bar
leading to $_GET['foo'] and $_GET['bar'] in PHP. But since foo/bar are some randomish value representing your session ID, you have no idea what that value will be. So... give it a name:
http://example.com?key=foo
Now you just do $key = $_GET['key'] and can always access your session value, no matter what value it really as - it'll always be assigned to the key.

How do i post variables inside a .js file to a php file without including jquery?

I'm abit confused as to how i will go about doing this, so i'm making a .js file to collect data on a page(100% with js) and i want to POST it to a php file which will then take care of it and insert it into the db etc..
How will i go about doing this? I know you can use jquery in a html document, but i want to use it in a .js file not a .html file.
I've successfully done it using a .html file and importing the jquery file, but i want to do it all in a .js file.
Any help is greatly appreciated. Thank you very much (:
I'd comment, but I can't. Can you post some samples of your code?
What I got is that you are using JavaScript (jQuery) to POST (form data?) over to a PHP file. If you want to use jQuery inside of a .js file, all you have to do is include the jQuery library before you include your .js file, like so:
<script src="jquery.js"></script>
<script src="myExternalScript.js"></script>
And then, inside of myExternalScript.js, you can use jQuery methods.
The external script is aware of your DOM elements, really, just like inline JavaScript would be, so you can still do whatever you want with your form or wherever you are getting the data to POST from.
EDIT: (in accordance to what you commented on this answer)
EDIT 2: I had forgotten to add the request header for POST
If you want to send an AJAX POST request (notice that I set the Content-Type request header, so that the data gets sent correctly):
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","http://zegita.tk/stargazer/magic.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("n="+user);
If you want to send an AJAX GET request:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://zegita.tk/stargazer/magic.php?n="+user, true);
xmlhttp.send();
It is important that you use the correct method, depending on whether you are using $_GET or $_POST in your magic.php file.
Clicking on the button runs this SCRIPT (which further passes 3 JS-variables to the abc.php)
<script type="text/javascript">
function sendJSValsToPHP(){
var xmlhttp;
//These are the variables i am going to post to illustrate the example, what you want
var var_1toPost = 1;
var var_2toPost = 2;
var var_3toPost = 3;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//You can get the response text from abc.php file and process it in any of the tags you want by javascript code
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","abc.php?recieve_1="+var_1toPost+"&recieve_2="+var_2toPost+"&recieve_3="+var_3toPost,true);
xmlhttp.send();
}
</script>
The echo'ed data in abc.php will come in the div="myDiv" //as a response.
<body>
<div id="myDiv" style="border: 1px solid BLUE; height: 100px;">
the things echo'ed in abc.php will come in this div
</div>
<button onclick="sendJSValsToPHP();">Click Me To Send JS-Values to abc.php</button>
</body>
and then in abc.php //file
<?php
$recieved_1 = $_GET['recieve_1'];
$recieved_2 = $_GET['recieve_2'];
$recieved_3 = $_GET['recieve_3'];
//Do your processing here and insert it in the database
//Insert Query OR Update Query (whatever)
// after you have inserted you can get the response in
// the <div> having id="myDiv" Or whatever you want
// Suppose you have successfully inserted data then
$insertedDataBoolean = true;
if($insertedDataBoolean){
echo "Data: " . $recieved_1 . ", " . $recieved_2 .
" and " . $recieved_3 . " inserted successfully.";
}
else{
echo "Data-insertion error.";
}
?>

jQuery load PHP that display flash content

What my php side does is load data use 'id' from database, and then show the raw data of swf files.
The code of php like this:
<?php
if(isset($_GET['id']))
{
include ('database.php');
$record = mysql_query("SELECT `Flash`, `FlashBlob` FROM `information` WHERE `id` = '". $_GET['id'] ."'; ", $link);
$swf = mysql_fetch_array($record);
mysql_close($link);
header("Content-type: " . $swf['Flash']);
echo $swf['FlashBlob'];
exit;
}
So if I just load the php in the web link, it goes well( the whole php page will show the flash I stored in database).
In my main page, I want to load the page into my div($("#gameArea")), I have tried:
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", 'api/swfInfo.php?id=' + id,true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('gameArea').innerHTML=xmlhttp.responseText;
}
}
but the result is it load only raw data( binary data) not the flash(swf file to be shown), what should I do?
I even not sure whether I should find a flash plugin for my flash or not
because I put my flash(swf file) in the database for some reason......
Please help me for the direction, thanks in advance!
Your overcomplicating the problem. If in-fact your swfInfo.php is outputting the swf file's bytes with a content type of application/x-shockwave-flash all you need to do is set the data attribute of your <object> tag to that URL.
<object type="application/x-shockwave-flash" data="api/swfInfo.php?id=7">
<param /> <!-- parameters -->
</object>
I would also recommend a content-length declaration to ensure your connection closes properly when loading files this way.
header('Content-length: ' . mb_strlen($swf['FlashBlob']));
header('Connection: close');
Try the following:
header('Content-Type: application/x-shockwave-flash');
header("Content-Disposition:attachment; filename="test.swf");
My questions are:
What is $swf['Flash'] ? Maybe there is the error?
Have you tried your script with a file_read_content() just for debugging reasons?

To load a text file in text area on selection of a drop down option in javascript

I have created a drop down with 3 options as
a
b
c
I want to load a local file in the text area on same page besides the drop down on selection of options.
For ex. When I click on option a, Content of a.txt should be displayed on the text area.
When I click on option b, Content of b.txt should be displayed on the text area.
Please help.
You shouldn't do that with javascript. To access the file system you need some server side language, like C# or PHP. There is the new file system API, but is only supported in modern browsers (HTML 5) which will limit your users using older versions of the protocol.
http://www.html5rocks.com/en/tutorials/file/dndfiles/
You need to use HTML5 File system API for reading local files.
sample code:
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
alert( "Got the file.n"
+"name: " + f.name + "n"
+"type: " + f.type + "n"
+"size: " + f.size + " bytesn"
+ "starts with: " + contents.substr(1, contents.indexOf("n"))
);
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
More details are available here http://www.html5rocks.com/en/tutorials/file/filesystem/
http://www.htmlgoodies.com/beyond/javascript/read-text-files-using-the-javascript-filereader.html#fbid=EF1E1e1JJgF
If you want to do it in browser on local filesystem - no chance. At least you have to run local web server.
On web server it would look alike this: http://webkurz.kvalitne.cz/pracovni_soubory/zima2013/ajax.html , only you can use jQuery get
You could use PHP in your script if you want (assuming the script is in a .php file)
<?php
function readTextFile($file) {
$myfile = fopen($file, "r") or die("Unable to open file!");
return str_replace("'", '"', fread($myfile, filesize($file)));
fclose($myfile);
};
?>
var optionsObject = {
a: '<?=readTextFile('/path/to/a.txt') ?>',
b: '<?=readTextFile('/path/to/b.txt') ?>',
c: '<?=readTextFile('/path/to/c.txt') ?>'
};
var optionsArray = [
'<?=readTextFile('/path/to/a.txt') ?>',
'<?=readTextFile('/path/to/b.txt') ?>',
'<?=readTextFile('/path/to/c.txt') ?>'
];
The first JS variable (optionsObject), is an object. To get the the text file from this variable, use optionsObject.{abc} (replace {abc} with either a, b, or c).
The second JS variable (optionsArray), is an array. To get the the text file from this variable, use optionsArray[{0-2}] (replace {0-2} with either 0, 1, or 2).
You could also use JavaScript's Ajax, but you are using .txt files, and to do that you have to add some extra code because most browsers cache text files and don't like to reread them. PHP will always reread them, and won't cache text files the same way browsers do.

Categories

Resources