Calling PHP function with ajax to read file - javascript

I am taking file input from input type file and calling a javascript function on onchange event like below:
<input type="file" onchange="readTheFile(this)">
The javascript function is calling a php file containing another PHP function. The javascrit function is:
function readTheFile(file){
$.ajax(
{
url: 'readFile.php',
type: 'GET',
data: 'fileLoc= '+file,
success: function(output)
{
document.getElementById("content").innerHTML = output ;
}
}
);
}
</script>
I am always getting the error:
Warning: fopen( [object HTMLInputElement]) [function.fopen]: failed to open stream: No such file or directory in D:\xampp\htdocs\sha\readFile.php on line 3
Unable to open file!
content of readFile.php is:
<?php
function readFiles($fileLoc){
$file = fopen($fileLoc, "r") or exit("Unable to open file!");
while(!feof($file)) {
echo fgets($file);
}
fclose($file);
}
if(isset($_GET['fileLoc'])){
echo readFiles($_GET['fileLoc']);
}
?>

I suggest the FILE API method (moderns browsers only)
See http://www.html5rocks.com/en/tutorials/file/dndfiles/
Example:
<input type="file" id="files" />
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
alert(e.target.result);
};
})(f);
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
Live example here

First move the file into the directory, then your rest function will work.
Here is a jquery plugin to upload file through ajax : jQuery Form Plugin
This plugin send you the parameter of $_FILES to your php file, then first move the file to your directory then use fopen() to read and display content.

It looks like you are making a malformed request. According to the documentation, it says the data option is appended directly onto the url for GET requests. I dont think this is likely because you are hitting the correct php script.
https://api.jquery.com/jQuery.ajax/
Try changing to
function readTheFile(file){
$.ajax(
{
url: 'readFile.php',
type: 'GET',
data: { fileLoc: file },
success: function(output)
{
document.getElementById("content").innerHTML = output ;
}
}
);
}
Also, I dont see where you are pulling the $fileLoc variable from the $_GET array. It might simply be excluded from your code.

Related

File upload through AJAX call, it's possible or not? I'm confused

I'm working on an application where I'm sending data from a form by serializing it and then sending it through AJAX. Everything works perfect but I've got the first headache is that when the form has a field of type FILE for upload any kind of file (should be restricted to images only but this is another topic) to my server-side (Symfony2 controller action) code does not get the image field and therefore can not perform any action on the same.
I've done some research (1,2,3,4 and many more docs found at Google) and in some cases it is said that it's possible and in some instance says it is not, others use the XHR object and then I'm confused and not know where to go from here, here I leave my code to throw him a look and tell me what's wrong and what should I do to make the upload if possible (I think it's):
$.ajax({
async: false,
type: "POST",
cache: false,
url: '{{ path('update-product', {'id': id}) }}',
data: $('.smart-form').serializeArray(),
success: function (data) {
// here goes a message if all was fine
}
});
This is the HTML field:
<input type="file" id="product_imageFile_file" name="product[imageFile][file]" class="valid">
Of course my form has enctype="multipart/form-data" and this is the request I got from Symfony2 controller action:
array(4)
[product_name]: string (10) "Producto-1"
[active]: string (1) "1"
[product_description]: string (21) "DescripcionProducto-1"
[_token]: string (43) "sjcpVT34_9-V7Z2doTZsvZsAewO-0Q5hD-a9C6VPNc4"
And as can see here there is not product[imageFile][file] on the request so something is wrong in my jQuery code, can any give me some help or point me to the right place?
NOTE: Since I'm using PHP and some of it's bundles to handle file upload and then manage the entities I don't know if will be a good practice to use any of the thousands of jQuery plugins to do that, that's the cause I don't mention here and I don't use them at all
Thanks in advance
Well, finally and after a lot of research I get it and without any external library as some users suggest here, maybe it's a ugly method but it works for me and does what I want. Here is the code:
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
// Display some alert or show the user the file is wrong
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function (theFile) {
return function (e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img id="product_image" class="thumb" src="', e.target.result, '" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('pImage').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('imageFile_file').addEventListener('change', handleFileSelect, false);
$.ajax({
async: false,
url: url, // the URL for process the whole form
type: 'POST',
data: $('#formID').serialize() + '&img=' + JSON.stringify($("#product_image").attr('src')),
cache: false,
success: function (data)
{
if (typeof data.error === 'undefined')
{
// Handle success here
}
else
{
// Handle errors here
}
},
error: function (jqXHR, textStatus, errorThrown)
{
// Handle errors here
},
complete: function ()
{
// STOP LOADING SPINNER
}
});
Hope helps someone else

Pass variable to PHP with JS

I have an HTML form which i populate from a database. On submit we load a page called "viewgame.php". Now what i want is here to run some scripts to populate some tables with data but how exactly can i pass the variable which i got from the form ex. $_POST['gameNo'] to the other php file though JavaScript?
Below is some of my code
JS function
function refreshGameinfo() {
var load = $.get('gameinfo_sc.php');
$(".gameinfo").html('Refreshing');
load.error(function() {
console.log("Mlkia kaneis");
$(".gameinfo").html('failed to load');
// do something here if request failed
});
load.success(function(res) {
console.log("Success");
$(".gameinfo").html(res);
});
load.done(function() {
console.log("Completed");
});
}
How can i pass the $POST_['gameNo'] to the gameinfo_sc.php file so that i can get the correct results?
Try this
var load = $.get('gameinfo_sc.php',{gameNo:"1212"});
In your php file you can access it using
$_GET['gameNo']
For post method use
var load = $.post('gameinfo_sc.php',{gameNo:"1212"});
In your php file you can access it using
$_POST['gameNo']
You are trying to post $POST_['gameNo'] to gameinfo_sc.php but $.get isn't the right method for post, its actually for http get. you can also do this by using $.post http://api.jquery.com/jquery.post/
function refreshGameinfo() {
$.ajax({
type: "POST",
url: "gameinfo_sc.php",
data: {gameNo: data},
cache: false,
success: function(html){
console.log( "Success" );
$(".gameinfo").html(res);
},
error:function(html){
console.log("Mlkia kaneis");
$(".gameinfo").html('failed to load');
}
});
}
try this
You can do it like this:
(in html layout):
<input type="hidden" id="gameNo" value="<?=$_POST['gameNo']?>" />
(in js file):
var gameNo = $('#gameNo').val();
var load = $.get('gameinfo_sc.php', {gameNo: gameNo});
....
UPDATE:
If your server doesn't support short open tags, you can write:
<input type="hidden" id="gameNo" value="<?php echo $_POST['gameNo'] ?>" />

trying to upload a file using HTML5 and ajax

I have been attempting to get a nice neat file upload using ajax, and from the many items on SO I have been able to get the framework done as follows:
My HTML:
<form enctype="multipart/form-data" method="post">
<input name="file" type="file" />
<input type="button" value="Upload" />
Pretty straight forward.
My PHP storeSales.php
if ($_FILES["file"]["name"] != NULL) {
if (file_exists("accounting/" . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists. ";
}else{
move_uploaded_file($_FILES["file"]["tmp_name"], "accounting/" . $_FILES["file"]["name"]);
}
}
$file = fopen($_FILES['myfile']['name'],'r') or die('cant open file');
and my .js:
$(":button").click(function(){
var formData = new FormData($('form')[0]); if (formData !=null) {
alert("Got the file");
} else {
alert("nothing Here");
}
$.ajax({
url: 'storeSales.php', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
success: function(result)
{
console.log($.ajaxSettings.xhr().upload);
alert(result);
},
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
When I try to upload a file, I get the alert in my .js file that says "Got the file" but in the php code I get the error that a file cannot be empty. From everything I have been able to find, I thought I was doing the php correctly. what is the correct way to handle this? Am I missing something else?
You can't use ajax to upload files - it's an illegal operation (via the dry Ajax route) without a third-party script. In short, you can't pass $_FILES data via Ajax. Only $_POST data. You need to find a plugin.
Try Uploadify:
http://www.uploadify.com/

How can I send the contents of a file to my server?

I'm trying to let users import an OPML file that I parse server (rails app) side. I'm having trouble as it seems that my server isn't getting the info (neither the success nor error functions run and even if I hardcode other data into the call, the call doesn't change).
Here's what I have embedded into the page:
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Print the contents of the file
var span = document.createElement('span');
span.innerHTML = ['<p>',e.target.result,'</p>'].join('');
document.getElementById('list').insertBefore(span, null);
};
$.ajax({
type: 'GET',
url: "/parse_opml",
data: {file: f},
success: function(details, response) {
console.log('woo!');
},
error: function(data, response) {
console.log('boooo');
}
});
})(f);
// Read in the file
reader.readAsText(f);
}
}
document.getElementById('the_o').addEventListener('change', handleFileSelect, false);
</script>
<input id="the_o" name="files[]" type="file">
Looking at chrome's network panel, I'm seeing the call: Request URL:blob:http%3A//localhost%3A3000/14e2be6b-059f-47f5-ba37-97eda06242b4 whose preview and response is the content of my .txt file. But like I said, the server never gets that text, so I'm puzzled.
Any help is greatly appreciated, thanks!
ANSWER
I ended up just using this: JavaScript: Upload file
Client code:
%form{:enctype => 'multipart/form-data', :action => '/parse_opml', :method => 'post'}
%input{:type => 'file', :name => 'file', :id => 'the_o'}
%input{:type => 'submit', :value => 'go'}
Server code:
f = File.open(params[:file].tempfile, 'r')
c = f.read
Works like a charm!
Javascript can't post uploaded files to the server as it is a limitation (for security reasons I assume).
Take a look at this other question regarding posting files posted through javascript:
JavaScript: Upload file
The answer on that questions says you can only do it using flash, but there are also iframe alternatives for upload and post.
Take a look at this as well for an alternative solution:
https://github.com/Widen/fine-uploader
Your ajax request isn't event sent as you return from your onload function before it.
You can send files via ajax on up to date browsers using XHR2
reader.onload = (function(theFile) {
var data = new FormData();
data.append('file',theFile);
$.ajax({
type: 'POST',
processData: false,
contentType: false,
url: "/parse_opml",
data: data,
success: function(details, response) {
console.log('woo!');
},
error: function(data, response) {
console.log('boooo');
}
});
return function(e) {
// Print the contents of the file
var span = document.createElement('span');
span.innerHTML = ['<p>',e.target.result,'</p>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);

using html5 for file upload with ajax and jquery

So i am trying to upload an image along with form data to server. I'm using FileReader API to convert image to data and upload to server. I'm following the code similar to HTML5 uploader using AJAX Jquery.
The data is converted in jquery, but nothing is being sent to server and there is no error generated.
$('#formupload').on('submit', function(e){
e.preventDefault();
var hasError = false;
var file = document.getElementById('file').files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = shipOff;
function shipOff(event) {
result = new Image();
result.src = event.target.result;
var fileName = document.getElementById('file').files[0].name;
$.post('test.php', { data: result, name: fileName });
}
PHP Code
<?php
$data = $_POST['data'];
$fileName = $_POST['name'];
echo $fileName;
$fp = fopen('/uploads/'.$fileName,'w'); //Prepends timestamp to prevent overwriting
fwrite($fp, $data);
fclose($fp);
$returnData = array( "serverFile" => $fileName );
echo json_encode($returnData);
?>
Is the problem due to large image file or FileReader API?
I'm not sure if file upload works with filereaders, but there is a different way to make it work:
var formData = new FormData($(".file_upload_form")[0]);
$.ajax({
url: "upload_file.php", // server script to process data (POST !!!)
type: 'POST',
xhr: function() { // custom xhr
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // check if upload property exists
// for handling the progress of the upload
myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
}
return myXhr;
},
success: function(result) {
console.log($.ajaxSettings.xhr().upload);
alert(result);
},
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: "application/octet-stream", // Helps recognize data as bytes
processData: false
});
function progressHandlingFunction(e) {
if (e.lengthComputable) {
$("#progress").text(e.loaded + " / " + e.total);
}
}
This way you send the data to the PHP file and you can use $_FILES to process it. Unfortunately, this does not work in IE as far as I know. There might be plugins available that make this possible in IE, but I don't know any of them.

Categories

Resources