I am having trouble uploading a picture file via AJAX.
Web:
<div>
<form id="birdi_image_form">
<input type="file" name="birdi_image" id="birdi_image" ></input>
</form>
<input type="text" name="species"></input>
<textarea name="comments"></textarea>
</div>
<div id="debug"></div>
<script type="text/javascript">
jQuery(function($){
$('#birdi_image').change(function(){
var ima = new FormData($('#birdi_image_form')[0]);
$.ajax({
url:"/bird/bird_scripts/fu.php",
type:"post",
data: ima,
processData: false,
dataType:"text",
success:function(data, textStatus, jqXHR) {
$('#debug').text(data);
}
});
});
});
</script>
/bird/bird_scripts/fu.php:
<?php
$imagedir = '/images';
$tmpfname = tempnam($imagedir, "b_");
echo var_dump($_POST);
if (move_uploaded_file($_FILES['birdi_image']['tmp_name'], $tmpfname)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
?>
From looking around online I was expecting to find contents in my $_FILES variable, but this is empty. Dumping out the $_POST var to the screen like in the example gives me the following. $_POST['birdi_image'] gives me NULL.
array(68) { ["------WebKitFormBoundaryYCAoI8shwgBavjJP
Content-Disposition:_form-data;_name"]=> string(339) ""birdi_image";
filename="test.jpg" Content-Type: image/jpeg ����JFIFdd��
ExifMMbj(1r2��i��B#'B#'Adobe Photoshop
CS2 Windows2008:06:24 11:11:48��b�g"
["?o��(�ci�\�R��Μꟑ���]T��z���"]=> string(82) "���
f�zߠ����i���/��v��E~��[,�Y
�s�������1l�G����-���߿�enu'=�v�z���=?Ҳ���"
["�{��<o��ӗ�M��ysnʨo87~;l���۔�"]=> string(172) "�<��t�2~���O�S
�����t���㵺C�}E������}��I�d]c���y}#�����C,�Z��־��V��ynʿ��?�g�*����o��ٌ�.}�y����}��z����w^�]�m�u������z>�37�_C긵��K𭪣�Y-{��뺷��M���ul��Y�"
["c�yhHp����"]=> string(152)
"��[-���1�]��|�����۽Q�\�e���o�~��g������u�.���A��t�]�3�W�ד��b���}>�����%��K���Ѳ�3���zX��qZ��}u��sc�
���N� ^-w�7���\r� ����c��=?δX�j" ["C�uw���-��"]=> string(57)
"���m��w��������ѩ���������k��r����m�t�62rIk���m�ߗV��}" ["�"]=>
string(384)
"!�<��B���6*�c��劷Q���uF*��U��������ď,�y{R���������E%���Q����5.��IE���N�����Ο�̿4~R��...............Upload failed.
I have uploaded files before by using a complete form submit. This is the first time I am trying to do it with AJAX. It looks like the data is getting to the server, but I can't seem to make any sense of it from the server side. As you can see in the code I expected $_FILES['birdi_image'] to exist but it doesn't. Am I doing something completely wrong?
Thanks
You have to set the content type to false, otherwise jQuery will set one(the wrong one) for you
$.ajax({
url:"/bird/bird_scripts/fu.php",
type:"post",
data: ima,
processData: false,
contentType: false,
dataType:"text",
success:function(data, textStatus, jqXHR) {
$('#debug').text(data);
}
});
I struggled with this also - it's just not as easy as it should be. I finally found a guy who did it right, and studied his code.
Ravi Kusuma's jQuery File Upload
In the end, because Kusuma wrote a plugin, I just used his code/plugin. Why re-invent the wheel? He's got everything solved, right down to sending extra data along with the uploaded file.
Related
I have a html page with jQuery and I used ajax to send data to the a php file to save the data.
I have seen other questions like this but none of them seemed to match my purpose.
The data is an iframe's srcdoc.
My html looks like this:
<iframe srcdoc="<h1>hello</h1>" id="iframe"></iframe>
<br />
<input type="text" placeholder="Filename to save as..." id="fn">
<input type="button" value="Save" onclick="saveDoc(document.querySelector('#fn').value)">
My jQuery and JS looks like this:
function saveDoc(e) {
let iframe = document.querySelector("#iframe");
let data = {"srcdoc": iframe.srcdoc, "lnk": e};
$.ajax({
type: "POST",
url: "saver.php",
dataType : "text",
contentType: "application/json",
data: data,
cache: false,
timeout: 3000,
success: function (data) {
alert("SUCCESS");
console.log(data);
},
error: function (e) {
alert(e);
}
});
}
And my php code looks like this:
<!doctype html>
<html>
<body>
<?php
if (isset($_POST["lnk"]) && isset($_POST["srcdoc"])) {
$myfile = fopen($_POST["link"], "w");
fwrite($myfile, $_POST["srcdoc"]);
fclose($myfile);
echo $_POST["lnk"];
echo "\n <br/>";
echo $_POST["srcdoc"];
} else {
echo "Error";
}
?>
</body>
</html>
When I run it, I get an alert message saying "SUCCESS". And the console.log gives me:
<!doctype html>
<html>
<body>
Error</body>
</html>
What is happening here, and what am I doing wrong?
contentType: "application/json"
You are explicitly sending this to the server as JSON - so you can not access it via $_POST. (PHP only populates $_POST for Content-Types application/x-www-form-urlencoded or multipart/form-data.)
Either remove contentType, so that it can fall back to the normal way of sending form data, or go read up on how to actually read POSTed JSON data in PHP. (That would involve reading the data from php://input first, see Receive JSON POST with PHP)
I have the following extremely simple PHP tester:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<button id="button">send request</button>
<script>
$("#button").click(function(){
$.ajax({
type: "POST",
url: "ajaxTest.php",
data: {userresponse: "hi"},
success: function(data){
alert(data)
analyse()
}
})
})
var analyse = function () {
<?php
if(isset($_POST["userresponse"])){
$variable = $_POST["userresponse"];
switch($variable){
case "hi":
echo 'alert("' . $variable . '")';
break;
default:
echo 'alert("LOGIC")';
}
}
?>
}
</script>
What's supposed to happen is that when I click the button, it sends the data userresponse: "hi" to the server, and then PHP receives it and alerts the value (i.e. "hi")
However, despite the fact that the file paths are correct, the AJAX send is OK in XHR, the PHP does not receive the value of the data, and the alert(data) returns the entire HTML document.
What is going on and how do I fix this?
Remove analyze() and put your php code in external file called ajaxTest.php, your code works perfect just remove your php code fron analyze and request for external this is bad practice having both in same file(header problems).
Proof:
I have a form that has multiple file uploads and each input is uniquely named, however, when attempting to get the uploaded file, my test if showing false.
Please find the code below. I am at a loss as to why this is happening.
<label class="label" for="uploadfile">Contract:</label>
<input name="'.$ICP.'_uploadedfile" id="'.$ICP.'_uploadedfile" type="file" />
The $ICP var is looped out, as there can be multiple instances, so this way each name is unique and on the server side, the POST is requested for each loop of the ICP.
while($icp_details = mysqli_fetch_array($ICP_exist_qry)){
$ICP_ID = stripslashes($icp_details['ICP_ID']);
if(!file_exists($_FILES[$ICP_ID."_uploadedfile"]['tmp_name']) || !is_uploaded_file($_FILES[$ICP_ID."_uploadedfile"]['tmp_name'])) {
echo false;
} else {
echo true;
}
}
I am not having any problems retrieving the values of the other posted inputs, just the files uploaded part.
Any help on this one is appreciated. :)
Note: Form is being submitted by Ajax.
To upload the file correctly using Ajax (and in this case JQuery) you need to use the FormData object. The code snippet below illustrates how it can be used. It is used instead of the .serialize() or .serializeArray() methods.
$('#file-form').submit(function(e) {
$.ajax({
url: 'http://example.com/upload/',
type: 'POST',
data: new FormData(this),
processData: false,
contentType: false
});
e.preventDefault();
});
I was wondering if i could get a bit of advice.
Im trying to upload a file using jquery while keeping the user on the same page.
Whatever i try isnt working. I was wondering if someone could have a look and tell me where im going wrong.
My HTML is
<form id="import" enctype="multipart/form-data" action="/ajax/postimport" method="POST">
<div class="form-group">
<input type="file" name="filename" id="filename" />
</div>
<button type="button" id="importSave">Import</button>
</form>
This is my jquery
$("#importSave").click(function()
{
$.ajax({
url: '/ajax/postimport',
type: 'POST',
dataType: 'json',
contentType: false,
processData: false,
data: {file: $(#filename).val()},
success: function(data)
{
alert(data.result)
},
error: function(textStatus, errorThrown)
{
}
});
});
and then my PHP, which is Laravel 4
if (Input::hasFile('filename')) {
$file = Input::file('filename');
$destPath = public_path() . '/uploads/';
$filename = str_random(10) . '_' . $file->getClientOriginalName();
$uploadSuccess = $file->move($destPath, $filename);
}
It is not possible to upload files by just using the jQuery ajax function. You will need to use a FormData object to do this. The problem with Formdata is that it is not supported in all browsers. If you do want to use it, you can always find plenty tutorials like this one.
You can also use a jQuery plugin that does the work for you. :)
It is not possible to do like this. you are just making post ajax request with only one field file: $(#filename).val().
So you need to use ajax upload library like.
There are several alternatives. But I like most are
http://www.plupload.com/
http://www.uploadify.com/
First of all I'd like to ask that you don't suggest I turn to a jQuery plugin to solve my issue. I'm just not willing to make my app work with a plugin (and it prevents me from learning!)
I have a form with a bunch of fields that I'm passing to my backend via the use of jQuery's $.post() This is what I have as my jQuery function:
$.post(
"/item/edit",
$("#form").serialize(),
function(responseJSON) {
console.log(responseJSON);
},
"html"
);
This is how I opened my form:
<form action="http://localhost/item/edit" method="post" accept-charset="utf-8" class="form-horizontal" enctype="multipart/form-data">
This was auto generated by codeigniter's form_open() method (hence why action="" has a value. Though this shouldn't matter because I don't have a submit button at the end of the form)
Within my #form I have this as my file input: <input type="file" name="pImage" />
When the appropriate button is hit and the $.post() method is called, I have my backend just print the variables like so: print_r($_POST) and within the printed variables the 'pImage' element is missing. I thought that maybe files wouldn't come up as an element in the array so I went ahead and just tried to upload the file using this codeigniter function: $this->upload->do_upload('pImage'); and I get an error: "You did not select a file to upload."
Any idea as to how I can overcome this problem?
You cannot post an image using AJAX, i had to find out here as well PHP jQuery .ajax() file upload server side understanding
Your best bet is to mimic an ajax call using a hidden iframe, the form has to have enctype set to multipart/formdata
Files wont be sent to server side using AJAX
One of the best and simplest JQuery Ajax uploaders from PHP LETTER
all you need is include js in your header normally and Jquery code will be like below
$.ajaxFileUpload({
url:'http://localhost/speedncruise/index.php/snc/upload/do_upload',
secureuri:false,
fileElementId:'file_upload',
dataType: 'json',
data : {
'user_email' : $('#email').val()
},
success: function (data, status) {
// alert(status);
// $('#avatar_img').attr('src','data');
}
,
error: function (data, status, e) {
console.log(e);
}
});
wish this can help you
I can't do this with codeigniter and Ajax, I pass the image to base64 and in the controller I convert into a file again
//the input file type
<input id="imagen" name="imagen" class="tooltip" type="file" value="<?php if(isset($imagen)) echo $imagen; ?>">
//the js
$(document).on('change', '#imagen', function(event) {
readImage(this);
});
function readImage(input) {
var resultado='';
if ( input.files && input.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
//console.log(e.target.result);
subirImagen(e.target.result);
};
FR.readAsDataURL( input.files[0] );
}
}
function subirImagen(base64){
console.log('inicia subir imagen');
$.ajax({
url: 'controller/sube_imagen',
type: 'POST',
data: {
imagen: base64,
}
})
.done(function(d) {
console.log(d);
})
.fail(function(f) {
console.log(f);
})
.always(function(a) {
console.log("complete");
});
}
//and the part of de controller
public function sube_imagen(){
$imagen=$this->input->post('imagen');
list($extension,$imagen)=explode(';',$imagen);
list(,$extension)=explode('/', $extension);
list(,$imagen)=explode(',', $imagen);
$imagen = base64_decode($imagen);
$archivo='archivo.'.$extension;
file_put_contents('imagenes/'.$archivo, $imagen);
chmod('imagenes/'.$archivo, 0777); //I use Linux and the permissions are another theme
echo $archivo; //or you can make another thing
}
ps.: sorry for my english n_nU