image not getting parsed in php from FormData - php

I have set up my code to pass formdata via Ajax to my php file. My code works until I actually select an image and then I get a parsing error in my php file. I get an undefined index error. I have a form named "AddItemForm". My image input line looks like this:
<input type="file" id="_ni_image_in" onchange="readURL(this);" name="ni_image" accept="image/png, image/jpeg">
My javascript/ajax code looks like this which gets called when submit button is selected on form:
function AddItem(){
var form = document.forms["AddItemForm"];
var name = document.forms["AddItemForm"]["ni_name"].value;
var tag = document.forms["AddItemForm"]["ni_tag"].value;
var description = document.forms["AddItemForm"]["ni_description"].value;
var weight = document.forms["AddItemForm"]["ni_weight"].value;
var date = document.forms["AddItemForm"]["ni__date"].value;
var color = document.forms["AddItemForm"]["ni_color"].value;
var itag2 = document.forms["AddItemForm"]["ni_tag2"].value;
var itag3 = document.forms["addcowform"]["ni_tag3"].value;
var useremail= "<?php echo $_SESSION['UserEmail']; ?>";
var itemdata = new FormData();
var filedata = document.getElementById("_nc_image_in").files[0];
itemdata.append('Item_Image', filedata);
itemdata.append('Name', name);
itemdata.append('Tag_Num', tag);
itemdata.append('Description', description);
itemdata.append('Weight', weight);
itemdata.append('Date', date);
itemdata.append('Color', color);
itemdata.append('Tag_Num2', itag2);
itemdata.append('Tag_Num3', itag3);
itemdata.append('User_Email', useremail);
var isValid = false;
$.ajax({
type: "POST",
url: "/AddNewItem.php",
data: itemdata,
processData: false,
contentType: false,
success: function(resp){
console.log(resp);
if(resp.reply == "Success")
{
isValid = true;
form.submit();
}
else
{
isValid = false;
}
},
error: function(data, status){
console.log(data, status);
alert("error")
}
}); //end Ajax
console.log(isValid);
return isValid;
};
In my php file, I am retrieving image like this:
$itemmage = $_REQUEST["Item_Image"];
It is working if I don't select an image, so something is wrong with how I am getting my image or retrieving it. Please help.

Use $_FILES instead of $_REQUEST
Edit
if(isset($_FILES['image']) && $_FILES['image']['name']!=""){
$image_name= $_FILES['image']['name'];
move_uploaded_file( $_FILES['image']['tmp_name'], "images/$image_name");
}
$_FILES has an array for each image:
[name] => MyFile.jpg
[type] => image/jpeg
[tmp_name] => /tmp/php/php6hst32
[error] => UPLOAD_ERR_OK
[size] => 98174
See http://php.net/manual/en/reserved.variables.files.php

Related

I'm trying to upload multiple images using AJAX and PHP but there is an error

In my form.php
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file_upload[]" id="file_upload" style="display:none;" required multiple accept="images/*" onchange="preview_image()">
</form>
And there is a submit button below.
In my jquery part
$('#submit').on('click', function(e) {
var files = $('#file_upload')[0].files;
var form_data = new FormData();
form_data.append("file_upload",files);
$.ajax({
url:"execute/Script.php?request=submit",
type: "POST",
data: form_data,
cache: false,
contentType: false,
processData: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode == 1){
alert("Success!");
}
}
});
});
And in my script.php
if($_GET['request']=="submit"){
$gallery_G = "";
foreach($_FILES['file_upload']['error'] as $key => $error){
if($error==UPLOAD_ERR_OK){
$tmp_name = $_FILES['file_upload']['tmp_name'][$key];
$PhotoName = $_FILES['file_upload']['name'][$key];
move_uploaded_file($tmp_name,"../img/properties/$name");
$gallery_G = $gallery_G.';'.$PhotoName;
}
}
$sql = mysqli_query($conn,"INSERT INTO property(photos) VALUES('$gallery_G')");
if($sql) {
echo json_encode(array("statusCode"=>1));
}
else{
echo json_encode(array("statusCode"=>2));
}
}
But it returns me this:
Notice: Undefined index: file_upload in G:\Xampp\htdocs\execute\Script.php on line 31
Warning: Invalid argument supplied for foreach() in G:\Xampp\htdocs\execute\Script.php on line 31
{"statusCode":2}
Is there any solution? I need to send those photos using 'append' method. And need to get those photos in 'Script.php' so that I can process or upload them from there.
Try passing the form element to FormData. No need to call the append method afterwards.
var files = $('form')[0];
var form_data = new FormData(files);
By using the append() method, you are putting a [object FileList] in the $_POST array under the file_upload key
If you just want the files from the form, you would need a loop:
var files = $('#file_upload')[0].files;
var form_data = new FormData();
for (var i = 0; i < files.length; i++) {
form_data.append("file_upload[]",files[i]);
}

Image Upload in PHP using AJAX Jquery not working

I have a form with 4 text fields and one image file. I have to upload it via AJAX call. After working for 2 days... I have made it working ..however there is an issue
<script type="text/javascript">
$(document).ready(function(){
// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
//alert(files);
}
$("#myProfileForm").submit(function(event){
event.preventDefault();
document.getElementById("messageBlock").style.display = 'none';
// Serialize the form data.
var form = $('#myProfileForm');
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
dataType: 'json',
processData: false,
contentType: false,
url: $(form).attr('action')+'?'+files,
data: formData
alert(url);
}).done(function(response) {
var formMessages = $('#form-messages');
if(response.error){
document.getElementById("messageBlock").style.display = 'block';
$(formMessages).html(response.message);
}else{
document.getElementById("messageBlock").style.display = 'block';
$(formMessages).html(response.message);
}
})
});
});
</script>
My PHP file code:
if (isset($_FILES['image_url'])){
$name = $_FILES['image_url']['name'];
$image_url = $name;
$temp_name = $_FILES['image_url']['tmp_name'];
if(isset($name)){
if(!empty($name)){
$location = 'uploads/';
if(move_uploaded_file($temp_name, $location.$name)){
//echo 'File uploaded successfully';
$image_url = UPLOADED_IMG_URL.''.$location.''.$name;
}
}
} else {
$image_url = DEFAULT_IMAGE;
}
}else {
$image_url = '../../API/v1/uploads/default.PNG';
}
The PHP code works well. The issue is with the AJAX call. When I comment the
//alert(url);
Things stop working as if (isset($_FILES['image_url'])) returns false. Not sure..what is causing the issue.
serialize() would not work with multipart data ,instead, you should use Formdata() method. check out this stack question; also remove that alert from $.ajax ; you cant do that.

How to send form string data and image data in a single Ajax call

How do you merge two Ajax calls so that they pass form input data as well as form image data using the formData API?
View Ajax Calls:
$("#submitbmsymptom").click(function(h){
h.preventDefault();
var radioValue;
$('#radio1, #radio2, #radio3, #radio4').each(function(){
if($(this).is(':checked')){
radioValue = $(this).val();
}
});
console.log(radioValue +
$("#bmdate").val() +
$("#bmtime").val() +
$("#bmscale").val() +
$("#bmpainlevel").val() +
$("#bmobs").val()
);
$.ajax({
url:'urllocation',
method: 'POST',
data:{
bmdate_data : $("#bmdate").val(),
bmtime_data : $("#bmtime").val(),
bmscale_data : $("#bmscale").val(),
bmcontents_data : radioValue,
bmpainlevel_data : $("#bmpainlevel").val(),
bmobs_data : $("#bmobs").val(),
},
}
).done(function(regresult){
});
})
$("#submitbmsymptom").click(function(h){
h.preventDefault();
var pooPicture = $('input[name=poopic]');
var fileUpload = pooPicture[0].files[0];
var formData = new FormData();
formData.append("file", fileUpload);
$.ajax({
url:'urllocation',
method: 'POST',
data: formData,
processData: false,
contentType: false,
success: function() {
alert("File uploaded");
}
});
})
Controller Method that receives data, saves the file to server and then inserts the string data and file name into a database using an associative array:
function bowelmovements(){
$bmuserid = $this->session->userdata('id');
$bmsymptomdate = $this->input->post('bmdate_data');
$bmsymptomtime = $this->input->post('bmtime_data');
$bmsymptomtype = $this->input->post('bmscale_data');
$bmsymptomlocation = $this->input->post('bmcontents_data');
$bmsymptompainlevel = $this->input->post('bmpainlevel_data');
$bmsymptomobs = $this->input->post('bmobs_data');
$config['upload_path'] = APPPATH.'/assets/uploads/';
$config['allowed_types'] = "gif|jpg|png|mp4";
$this->load->library('upload', $config);
if($this->upload->do_upload("file")){
$imageData = $this->upload->data();
$fileName = $imageData[file_name];
$bmdata = array(
'userid' => $bmuserid,
'bmdate' => $bmsymptomdate ,
'bmtime' => $bmsymptomtime,
'bmscale' => $bmsymptomtype,
'bmcontents' => $bmsymptomlocation ,
'bmpainlevel' => $bmsymptompainlevel,
'bmobs' => $bmsymptomobs,
'bmimage' => $fileName
);
$insertBM = $this->poomonitormodel->insertBM($bmdata);
}
else{
echo "File not uploaded";
}
}
Currently this only submits the second Ajax call, and inserts only the file name into the database however I require both sets of data to submit into the table.
Thanks.
Here, I condensed your 2 ajax calls into a single one:
$("#submitbmsymptom").click(function(h){
h.preventDefault();
var radioValue;
$('#radio1, #radio2, #radio3, #radio4').each(function(){
if($(this).is(':checked')){
radioValue = $(this).val();
}
});
var pooPicture = $('input[name=poopic]');
var fileUpload = pooPicture[0].files[0];
var formData = new FormData();
formData.append("file", fileUpload);
formData.append("bmdate_data", $("#bmdate").val());
formData.append("bmtime_data", $("#bmtime").val());
formData.append("bmscale_data", $("#bmscale").val());
formData.append("bmcontents_data", radioValue);
formData.append("bmpainlevel_data", $("#bmpainlevel").val());
formData.append("bmobs_data", $("#bmobs").val());
$.ajax({
url:'urllocation',
method: 'POST',
processData: false,
contentType: false,
data: formData,
}).done(function(regresult){
});
});

How can find inputs in php codes?

I get some inputs from database with $.ajax in jQuery and it will appear when user click on button:
HTML
<div id="div1"></div>
<input type="button" id="button1"/>
JQuery
$("#button1").click(function() {
$.ajax({
type: 'POST',
url: "get.php",
data: {vals: "send"},
success : function(response) {
$("#div1").append(response);
}});
})
After import elements to div, it will have one input type="file" like this:
EDIT:
My Form Code is here:
HTML
<input name="upload1" id="upload1" type="file"/>
<input type="button" value="submit" id="button2"/>
JQuery
$("#button2").click(function() {
$.ajax({
type: 'POST',
url: "uploadPhoto.php",
data: {filename: filename},
success : function(response) {
alert(response);
}
});
})
PHP
$filename = $_POST['filename '];
$target_dir = "image/";
$target_file = $target_dir . $filename;
var $src_temp = $_FILES["upload1"]["tmp_name"];
if (move_uploaded_file($src_temp, $target_file)) {
echo 'success';
}
END EDIT 1
When I want get $_FILES["upload1"]["tmp_name"] for this button to find temp folder of uploaded file in PHP code, it can't find the input that have upload1 name.
How can find a input name in PHP codes?
Try following code to get values in $_FIELS
$("#button1").on('click', function() {
var filename = document.getElementById('image id here').value.replace(/C:\\fakepath\\/i, '');
var image = document.getElementById('image id here').files[0];
Data = new FormData();
Data.append('upload1', image);
Data.append('file_name', filename); //pass file name
var xmlReq = new XMLHttpRequest(); //creating xml request
xmlReq.open("POST", 'enter your url', true); //send request
xmlReq.onload = function(answer) {
if (xmlReq.status == 200) {
var response = jQuery.parseJSON(xmlReq.responseText);
console.log(response);
} else {
console.log("Error " + xmlReq.status + " occurred uploading your file.<br \/>");
}
};
xmlReq.send(Data); //send form data
});

HTML5 + jQuery AJAX upload - No file sent to server

I'm trying to implement a HTML5 ajax file upload with the help of HTML5's File API. It is based on Afzaal Ahmad Zeeshan's answer to this question.
My main aim would be to be able to let users upload .xls and .xlsx spreadsheet for later use.
HTML
<form class="form-uploadXLS" method="post" action="php/uploadXLS.php" enctype="multipart/form-data">
<div class="form-group">
<div class="col-md-12">
<input type="file" name="xls" class="xls" />
</div>
</div>
<input type="button" value="Upload" class="btn-uploadXLS" />
</form>
<progress></progress>
And here are the jQuery event handlers, just like in the above mentioned answer:
File input onChange event:
$('.xls').on('change', function () {
var file = this.files[0];
var fileName = file.name;
var fileType = file.type;
var fileSize = file.size;
console.log("file name: " + fileName + ", type: " + fileType + ", size: " + fileSize);
});
This works correctly, the file's name, type and size gets logged to the server.
Upload button's onClick event:
$('.btn-uploadXLS').on('click', function (event) {
event.preventDefault();
console.log("Upload button clicked");
var formData = new FormData($('.form-uploadXLS')[0]);
$.ajax({
url: 'php/uploadXLS.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
beforeSend: function (stuff) {
console.log("BeforeSend");
console.log(stuff);
},
success: function (data) {
console.log("Success!");
console.log(data);
},
error: function (error) {
console.log("Error!");
console.log(error);
},
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
On server side, I'm using this PHP code to check if the file has been sent to the server
if(!empty($_FILES['xls'])) {
echo '<pre>',print_r($_FILES,1),'</pre>';
}
else {
die('no $_FILES variable');
}
And here's the result of print_r:
Array
(
[xls] => Array
(
[name] =>
[type] =>
[tmp_name] =>
[error] => 4
[size] => 0
)
)
According to the documentation, error code 4 means: UPLOAD_ERR_NO_FILE Value: 4; No file was uploaded.
What am I doing wrong?
Edit:
If I disable the click event listener and submit the form as normal, the file gets uploaded without problems.
I've noticed, that the formData variable doesn't have any value. This is the value of formData after it's been set: FormData { append=append()}
For some reason the problem was with the formData variable, previously defined as such:
var formData = new FormData($('.form-uploadXLS')[0]);
I've changed the index to 1 like this..
var formData = new FormData($('.form-uploadXLS')[1]);
.. and for some reason it works now.
Instead of:
if(!empty($_FILES['xls'])) {
try this:
if(!empty($_FILES['xls']['name'])) {
type = $_FILES['xls']['type'])
tmp = $_FILES['xls']['tmp_name'])

Categories