I am new to web development, and the latest problem I have been having is ajax file uploading...
Right now I have two HTML input fields; a file input and a button.
<input type="file" name="Frame" id="Frame_"/>
<input type="button" name="FrameButton" id="FrameButton_" value="UPLOAD"/>
After the button is clicked I then call a function that has the following code..
var frame = document.getElementById('Frame_');
var frameImg = frame.files[0];
var form_data = new FormData();
form_data.append('frame', frameImg);
jQuery.ajax({
url : './handler.php',
type : 'post',
data : form_data
contentType : false,
processData : false,
success : alert("Frame Uploaded")
});
When I var_dump() the $_POST and $_FILES array it shows both arrays as empty. This is despite the "Request Payload" in Chrome Dev reading
Content-Disposition: form-data; name="frame"; filename="GoldFrame.jpg"
Content-Type: image/jpeg
In which I am under the impression that this means the information of the file that I select on the front end is being successfully "post"ed to my handler.php file. Is this a wrong interpretation?
Either way, could someone please give me an answer to my problem? Or atleast point to a resource that might have my answer? There seem to be many similar questions along the same lines, but I haven't seen one that has a solid answer.
I have used iframes for this kind of thing in the past, but that seems like a really hacky method, and I would like to have the flexibility to use ajax for this kind of task in the future.
Help is appreciated.
Try this.
Form (index.html)
<form id="uploadForm">
<input type="file" name="frame" />
<input type="submit" value="UPLOAD" />
</form>
Script (script.js)
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "handler.php",
type: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data){
console.log(data);
}
});
}));
Server Side (handler.php)
<?php
var_dump($_FILES);
When posting a file and/or text, This set of codes is also useful for debugging purposes. You can use this to see if your post is too large as that too can cause empty $_POST & $_FILE arrays even though its posted.
print_r($_POST); /* Looks at the $_POST array. (Will be empty if $_SERVER['CONTENT_LENGTH']/1000000 is greater than ini_get('post_max_size') ) */
echo "<br>";
print_r($_FILES); /* Looks at the $_FILES array. It will also show you the file size in bytes: divide it by 1 million (1000000) to get the megabytes value. (Will be empty if $_SERVER['CONTENT_LENGTH']/1000000 is greater than ini_get('post_max_size') ) */
echo "<br>" . $_SERVER['CONTENT_LENGTH']/1000000 ; /* This will give you the size in megabytes of your $_POST */
echo "<br>" . ini_get('post_max_size'); /*This will show you the post_max_size in your php.ini file*/
echo "<br>" . ini_get('upload_max_filesize'); /*This will show you the upload_max_filesize in your php.ini file*/
// phpinfo(); // You might not need this function but you can use it for more information on your php.ini file. It can help you find its location (for maybe editing purposes) and view its data.
Are you var_dump()-ing your $_FILES/$_POST arrays in the handler.php file?
If you are trying to dump these variables in the file that has the ajax call, it won't work because AJAX is making the front-end call, and the files/post variables are server side variables ... which means only the handler.php file will have these variables available.
Try adding the var_dump() call in handler.php, and output that result in the ajax call, and I am hopeful you will see the results you are looking for.
Related
I'm developing a simple script to upload a file through AJAX but after form submission, the variable $_FILES is completely empty, although the file exists within php://input, but with no simple way to extract only the file. Anyone knows the reason and/or solution to this problem?
I've checked all the common solutions.
enctype="multipart/form-data"
rights to temp folder
form-tags closing
doublequotations
and the output of the file-input in JS
Nothing has solved my problem.
RED
This is NOT jquery, and I haven't found a duplicate in 24h. So please don't mark as duplicate unless you're sure it is one.
HTML
<form action="upload.php" method="POST" enctype="multipart/form-data" id="testf">
<input type="file" name="file" accept=".jpg">
<input type="submit" value="Skicka">
</form>
JavaScript
let data = document.querySelector("#testf");
data.onsubmit = function() {
var http = new XMLHttpRequest();
http.open("upload.php", data.action);
http.onreadystatechange = function () {
console.log(http.response);
}
http.setRequestHeader("Content-type", data.enctype);
http.send(new FormData(data));
event.preventDefault();
return false;
}
PHP
<?php
var_dump($_FILES);
?>
This should print the contents of my file, but
array(0) {}
is all I get.
Request payload is:
------WebKitFormBoundaryZVGq8suqFUUSFDtW
Content-Disposition: form-data; name="file"; filename="david.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryZVGq8suqFUUSFDtW--
You have a problem with your JavaScript method XMLHttpReqest. It takes at least two parameters: Method and url.
Full parameters are:method, url, async, user, password
Change your code from:
http.open("upload.php", data.action);
To:
http.open("post", data.action );
Update:
Also remove
http.setRequestHeader("content-type", "multipart/form-data")
Form data already sets its headers for content-type.
Did you checked if memory limit is set to -1 or high enough in php.
Sometime on Apache or iis server, there is also a block on high file uploads.
I have a php file (I will call ORIGINAL) which do some calculations (through db mysql). I want to read this php from javascript. For that operation I have used ajax function and my php uses echo $result to print the data I need.
Everything is perfect here.
What happends now, I am creating another php file which need to call the ORIGINAL php file. If I want to call it, I must change the echo to return which is normal. This causes that my javascript call doesnt work.
Do you have a solution which work for both situations?
Thanks in advance.
Do you mean something like this?
original_php_file.php:
<?php
require_once "other_php_file.php"; // include all of the other files contents
// all code contained within original_php_file
?>
You were being pretty broad with your request (not including file names or code), so this is all I can assume you need.
Tell me if it helps :-)
Just send one more parameter into your ajax request to tell that ORIGINAL php file what type of output it should return.
Into your ORIGINAL file check for that output so you can understand from where that request come and what output you should return.
$.ajax({
url: 'ORIGINAL.php',
data: 'data=test&output=1',
success: function(r){
// here you have your output
}
});
I would need to echo php variables (from the server and related to service behaviour) into javascript. For example, "ssl" => "true" and adapt accordingly in javascript. The thing is I'm doing this for some API files I'm writing and I want the client to have direct access to these files (<script src="... .js">) and this forces me to hardcode info that might change in the future across multiple file references. What I'd like to do was something like this, is it possible? (the content to fetch must remain completely private - from the server folders to the php script files - and so it is really not an option to fetch this info using javascript):
api.js
<? //PHP here. (I know...)
(...)
?>
//some javascript
var is_secure = <? echo "true"/"false" ?>
(...)
So that when doing <script src="api.js"/> the user only fetches:
var is_secure = "true";
(...)
or
var is_secure = "false";
(...)
Any idea on how I could do something similar? Thank you very much...
You could just create your PHP file with this line before everything :
header("Content-Type: application/javascript");
EDIT:
I did misunderstood the question. If you want js in an php file, you should do it like this:
header("Content-Type: application/javascript");
OLD ANSWER:
I don't know if you know, but client can't see your php code...
So if You'd:
echo "Something"
The client would only see Something.
It's not clear, what you're trying to do...
If you don't want to see Something when you go directly into your "secret" php page, then you should do it like this:
JS:
jQuery.ajax({
type: "POST",
url: 'secretfile.php',
dataType: 'html',
data: {apiRequest: 1},
success: function (response) {
yourVar = response;
}
});
PHP:
If ($_POST['apiRequest']==1){
echo "Something";
}
yourVar would be = "Something"
If you'd go to this page, it wouldn't display anything;
I want to use jquery ajax to change the content of my div elemnt by requiring different php files.
here is the ajax code :
$.ajax({
url:"/project/Functions/project_functions.php",
type:"POST",
data:{
functions:num
},
success:function(result){
$("#right_bot").html(result);
}
});
the project_functions.php would be something like :
$result = '<?php require "Panels/Project/Main/main.php" ?>';
echo $result;
I can see the value being outputted , but the html comment out the php part
<!--?php require "Panels/Project/Main/main.php" ?-->
It just comments out the php. Is there a way i load different php files into my div ?
In the main.php file , It has php code , html code , and some style tags. Can I use ajax to load all this into the div element ? or I have to echo all my html code ?
You can't do this like that. What you want is that all PHP is excecuted on the server and only the result has to be returned.
You can't send php-code back to javascript and try to run it there, PHP is a serverside language, it will only work on the server. Javascript is clientside, it will only run in the browser.
If you where to send <?php echo 123; ?> back to Javascript, you'll get exactly that as result, not 123.
The solution in your case is to make project_functions.php really require it. This will include the main.php, all it's functions and output.
require "Panels/Project/Main/main.php";
Some suggested reading:
http://www.codeconquest.com/website/client-side-vs-server-side/
A trick which might help you: Paste the link to your urlbar, and add the variables to it. The result you get in your screen is what Javascript will output. Note: This only works for method=get, not post.
In this case browse to /project/Functions/project_functions.php and do the simple require per my code above. That output will be send to Javascript.
Send a parameter in the ajax request 8for example type):
$.ajax({
url:"/project/Functions/project_functions.php",
type:"POST",
data:{
functions:num, type: "main"
},
success:function(result){
$("#right_bot").html(result);
}
});
And then in php-file get the type variable:
if($type == "main") {
require "Panels/Project/Main/main.php"
}
else {
require "Panels/Project/Main/sthelse.php"
}
You should also have some sort of same function name or something to output the results of the file;
<?php
function printResult() { }
echo printResult();
Try:
$result = file_get_contents('Panels/Project/Main/main.php');
I've read many articles in this site or other sites (Redirect with POST to application/csv without form, jQuery.post(), PHP and redirects, ... ) but without any valuable solutions.
My problem is the following :
in my site (html5, JQuery), there is a table. A feature of the site
is to export the table as a csv file which will be available for
download,
This feature is implemented as follow :
2.1 a javascript is called which extracts the data of the table,
2.2 this JS redirect to a php service and pass as arguments the datas. The code is the
following :
var url= jmcnet.request.getOrigin()+'/commons/php/dt_csv_export.php' ;
location.href = url+"?action=generate&csv_type=export_task&csv_data=" +encodeURIComponent(csv);
2.3 The php script format the input (csv_data parameter), write a temporay file and returns the content of the temporary file. The code is the following :
$h = #fopen($csv_file_name, 'w');
fputcsv($h, $csv_row, ',', '"');
fclose($h);
// export file content to JS
header('Content-Encoding: UTF-8');
header('Content-Type: text/ csv; charset =UTF-8');
header('Content-Disposition: attachment; filename=export-table.csv');
header(' Pragma: no-cache');
echo "\xEF\xBB\xBF"; // UTF-8 BOM
readfile($csv_file_name);
2.4 The php file delete (unlink) the temporary file and exit,
My problem is that when the table is long, the URL called is not valid and the JS call to Php is down.
So, I imagine the 3 following solutions but no one is evident and all leads to other problems :
S1 : dont do a GET but a POST in JS. So the size of the csv_data
doesn't matter anymore. The problem is that I will have the content
of the csv file in JS var after the call succeed and I don't know or
find how to redirect to a page which content is in a JS var ? I
guess I will lose all header information doing this.
S2 : compress in JS the csv_data parameter and decompress it in Php.
I just don't know how to do that and if it possible ....
S3 : call the php with a POST. Modify the Php to return the URL of
the temporary file, and do a redirect in JS to this temporay URL.
The problems are that my Php must generate a file into a dir
directly visible on the Internet, the file name must be unique and
there is no way to simply delete the file after it has been read by
browser (and I hate cron or what else).
I'm sure I'm not the first one to have this problem, so I need your help to see what is the best practice for this problem.
I think you may be over-complicating this just a bit. There is no need for all of the JS redirect stuff, you can just point your forms action attribute to your csv_export php code and use POST to send your data.
if needed, you can modify the max size of a post request by editing the post_max_size option in your php.ini. heres what mine looks like:
; Maximum size of POST data that PHP will accept.
; Its value may be 0 to disable the limit. It is ignored if POST data reading
; is disabled through enable_post_data_reading.
; http://php.net/post-max-size
post_max_size = 8M
as for writing to a temporary file, php has built in I/O streams to handle that. for your purposes you'll probably want to use php://memory or php://temp (more info on those here: http://www.php.net/manual/en/wrappers.php.php)
so you can do something like this:
SAMPLE HTML:
<html>
<head>
<!-- include jquery because you say you are using it -->
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
//just a dummy function to represent your js to extract csv data from a table
function extract_table_data(){
var csv = "field1,field2,field3\n\
value1,value2,value3\n\
value4,value5,value5";
return csv;
}
$( document ).ready(function() {
//export link click handler
$('#export_link').click(function() {
$('#csv_data').val(extract_table_data());
$('#theform').submit();
});
});
</script>
</head>
<body>
<a id='export_link'>Export CSV</a>
<form id='theform' method='post' action='dropcsv.php'>
<input type='hidden' name='csv_data' id='csv_data'/>
</form>
</body>
</html>
dropcsv.php
//filename for our csv attachment
$export_filename = 'thefile.csv';
//grab csv data
$csv_data = $_POST['csv_data'];
//open file in memory
$f = fopen('php://memory', 'w'); //use php://temp if you want a tmp file instead
//load up csv file
fwrite($f, $csv_data);
// go back to the beginning of the file
fseek($f, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="'.$export_filename.'"');
fpassthru($f);
fclose($f);
of course don't forget to add your error checking and sanitize the input.