Form field input isn't received by JSON AJAX script - php

I am unable to catch the $productid from the form. Not sure what I'm doing wrong. Any ideas?
The selected files do upload, but not to the product folder specified, and nothing about the success is returned to index.php
It's strange but stackoverflow also mentions when trying to post "It looks like your post is mostly code; please add some more details", but I have no more info to add?
Thanks
index.php
<form method='post' action='' enctype="multipart/form-data">
<input type="hidden" id='productid' name="productid" value="<?=$productid?>">
<input type="file" id='files' name="files[]" multiple><br>
<input type="button" id='submitphotos' value='Upload'>
<!-- Preview -->
<div id='successupload'></div>
<div id='preview'></div>
<script>
$(document).ready(function(){
$('#submitphotos').click(function(){
var form_data = new FormData();
// Read selected files
var totalfiles = document.getElementById('files').files.length;
var productid= $("#productid").val();
for (var index = 0; index < totalfiles; index++) {
form_data.append("files[]", document.getElementById('files').files[index]);
}
// AJAX request
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: form_data,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
for(var index = 0; index < response.length; index++) {
var src = response[index];
// Add img element in <div id='preview'>
$('#preview').append('<img src="'+src+'" width="400px;">');
}
$('#successupload').append('<h6>Successfully uploaded</h6>back');
files.style.display = "none";
submitphotos.style.display = "none";
}
});
});
});
ajaxfile.php
// Count total files
$countfiles = count($_FILES['files']['name']);
// Get product id
$productid = $_POST['productid'];
//Create request id folder if doesn't exist
if (!file_exists($_SERVER['DOCUMENT_ROOT'].'/images/products/'.$productid.'/')) {
mkdir($_SERVER['DOCUMENT_ROOT'].'/images/products/'.$productid.'/', 0777, true);
}
// Upload directory
$upload_location = $_SERVER['DOCUMENT_ROOT']."/images/products/".$productid."/";
// To store uploaded files path
$files_arr = array();
// Loop all files
for($index = 0;$index < $countfiles;$index++){
if(isset($_FILES['files']['name'][$index]) && $_FILES['files']['name'][$index] != ''){
// File name
$filename = $_FILES['files']['name'][$index];
// Get extension
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
// Valid image extension
$valid_ext = array("png","jpeg","jpg","svg");
// Check extension
if(in_array($ext, $valid_ext)){
// File path
$path = $upload_location.$filename;
// Upload file
if(move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
$files_arr[] = $path;
}
}
}
}
echo json_encode($files_arr);
die;
</script>

You haven't passed the productid to the ajax call so just before ajax call add this:
form_data.append('productid', productid);
and your code should work fine.

Related

move_uploaded_file doesn't move image to permanent folder || PHP

I am building a PHP application where a new user has to upload an avatar.
I managed to save the uploaded file path into my database,
but now I have to move the uploaded image from the temporary to the permanent directory, which is the folder 'avatars'.
I have searched through many answers on the same problem but haven't managed to find a working one. Since I am really new to PHP I'm gonna need some help for a working solution.
I have also tried copy() instead of move_uploaded_file with no luck.
HTML:
<div class="input-form">
<label for="avatar">Kies een profielfoto</label>
<input type="file" id="avatar-input" name="avatar" accept="image/*" onchange="loadFile(event)">
<img id="output" width="150" />
<input type="submit" id="submit-btn" name="vervolledig-submit" value="START">
</div>
PHP:
if(!empty($_POST)){
$fileSize = $_FILES["avatar"]["size"];
if($fileSize < 2000000){
$fileSizeOk = true;
}else{
throw new Exception("Je profielfoto heeft een grotere file size dan is toegelaten (max 2MB)");
$imgSizeOk = false;
}
$img = $_FILES["avatar"]["name"];
if($imgSizeOk == true){
move_uploaded_file($_FILES["avatar"]["tmp_name"], "avatars/$img");
}
}
EDIT: was asked to share my JS code:
a function that shows a preview of the uploaded picture:
let loadFile = function(event) {
let image = document.getElementById('output');
image.src = URL.createObjectURL(event.target.files[0]);
};
Suggested solution with AJAX
$('#submit-btn').on('click', function() {
var file_data = $('#avatar-input').prop('files')[0];
var form_data = new FormData();
form_data.append('avatar', file_data);
alert(form_data);
$.ajax({
url: 'profielVervolledigen.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
with the following php code:
if(!empty($_POST)){
if ( 0 < $_FILES['avatar']['error'] ) {
echo 'Error: ' . $_FILES['avatar']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['avatar']['tmp_name'], 'avatars/' . $_FILES['avatar']['name']);
}
}
the alert gives [object FormData]
Thanks for any help

simple parse error with my form submit using ajax and file upload

I'm able to get the file uploaded and in to the directory I want so that part seems to work but I'm not sure why I'm getting a parse error in the js console in chrome. Because of this error my bottom javascript won't execute and I need it to do so.
Here's the ajax:
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;
}
$('form').on('submit', uploadFiles);
// Catch the form submit and upload the files
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'submit.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
alert(data);
script = $(data).text();
$.globalEval(script);
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
Here's the html:
<?php
echo '<span class="new_profile_save_upload_image_span"><img src="'.$url_root.'/images/615721406-612x612.jpg"/ class="new_profile_save_upload_image_img"></span>';
?>
<form action="" method="post" enctype="multipart/form-data" name="new_profile_save_upload_image_input_form" id="new_profile_save_upload_image_input_form">
<input type="file" id="new_profile_save_upload_image_input" name="new_profile_save_upload_image_input" multiple="" accept="image/x-png,image/gif,image/jpeg"/>
<input type="submit" value="Upload Image" name="submit">
</form>
And here is the php:
<?php
// get mysqli db connection string
$mysqli = new mysqli("localhost", "psych_admin", "asd123", "psych");
if($mysqli->connect_error){
exit('Error db');
}
// Get theme settings and theme colours and assign the theme colour to the
theme name
$stmt = $mysqli->prepare("SELECT name FROM user_profiles WHERE rowid=(SELECT
MAX(rowid) FROM user_profiles);");
$stmt->execute();
$result = $stmt->get_result();
while($row_1 = $result->fetch_assoc())
{
$arr_1[] = $row_1;
}
foreach($arr_1 as $arrs_1)
{
$username = $arrs_1['name'];
}
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
// Make dir for file uploads to be held
if (!file_exists(''.dirname(__FILE__) . '/content/profiles/'.$username.'/avatar'))
{
mkdir(''.dirname(__FILE__) . '/content/profiles/'.$username.'/avatar', 0777, true);
}
$uploaddir = './content/profiles/'.$username.'/avatar/';
foreach($_FILES as $file)
{
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
}
echo json_encode($data);
?>
<script>
var scope1 = '<?php echo $url_root;?>';
var scope2 = '<?php echo $username;?>';
var scope3 = '<?php echo $file['name'];?>';
var new_profile_save_upload_image_span_data = '<img src="' + scope1 + '/content/profiles/' + scope2 + '/avatar/' + scope3 + '" class="new_profile_save_upload_image_img">';
$('.new_profile_save_upload_image_span').empty();
$('.new_profile_save_upload_image_span').append(new_profile_save_upload_image_span_data);
</script>
alert(data) doesn't seem to be popping up, so there's something wrong previous to that execution.
I tried this code with simply 'submit.php' but it doesn't seem to work without the 'files' addition to it.
Also do I have the filename correct? Should the file's filename be $file['name'] in php? I'm trying to get the file name as a string and place it in when the default image is (as an image to be displayed), using an img html tag and inserting it via jquery, as you can see at the bottom under .
The ajax should execute this script at the bottom but it doesn't due to the error.
Also is there a nicer way of writing the bottom jquery scripts that I have written?
Error I'm getting:
ERRORS: Syntax Error: Unexpected Token < in JSON at position 103
Thanks in advance.
If you want to return JSON and HTML at the same time, you could put the HTML into an element of the $data array.
<?php
// get mysqli db connection string
$mysqli = new mysqli("localhost", "psych_admin", "asd123", "psych");
if($mysqli->connect_error){
exit('Error db');
}
// Get theme settings and theme colours and assign the theme colour to the
theme name
$stmt = $mysqli->prepare("SELECT name FROM user_profiles WHERE rowid=(SELECT
MAX(rowid) FROM user_profiles);");
$stmt->execute();
$result = $stmt->get_result();
while($row_1 = $result->fetch_assoc())
{
$arr_1[] = $row_1;
}
foreach($arr_1 as $arrs_1)
{
$username = $arrs_1['name'];
}
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
// Make dir for file uploads to be held
if (!file_exists(''.dirname(__FILE__) . '/content/profiles/'.$username.'/avatar'))
{
mkdir(''.dirname(__FILE__) . '/content/profiles/'.$username.'/avatar', 0777, true);
}
$uploaddir = './content/profiles/'.$username.'/avatar/';
foreach($_FILES as $file)
{
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
$data['html'] = <<<EOS
<script>
var scope1 = '$url_root';
var scope2 = '$username';
var scope3 = '{$file['name']}';
var new_profile_save_upload_image_span_data = '<img src="' + scope1 + '/content/profiles/' + scope2 + '/avatar/' + scope3 + '" class="new_profile_save_upload_image_img">';
\$('.new_profile_save_upload_image_span').empty();
\$('.new_profile_save_upload_image_span').append(new_profile_save_upload_image_span_data);
</script>
EOS;
}
echo json_encode($data);
?>
Then in the JavaScript you do:
script = $(data.html).text();
It's better to use try-catch block in your PHP code, and send status with the response set to true or false. Also, send the $url_root and $username variables within the JSON object.
See this beginner's guide on Image Uploading with PHP and AJAX to learn everything about creating AJAX handler, validating, saving and sending a response back to the client side.

How to keep track of and display uploaded images after uploading?

I made a little page where you can upload picture it is simple php upload. I want everyone to be able to upload images and view everyone else's uploads on the site. How can I display images after they're uploaded? I want to be able to globally track all uploaded images so that everyone can browse them.
I think I need to use "AJAX upload" to do that and maybe javascript to display image after upload... but how?
I tried this:
function GetFileName(){
var fileInput = document.getElementById('fileToUpload');
var fileName = fileInput.value.split(/(\\|\/)/g).pop();
var img = document.createElement('img');
img.src = 'uploads/' + fileName;
img.setAttribute('width', '100px');
img.setAttribute('height', '100px');
img.alt = fileName;
document.body.appendChild(img);
alert(fileName);
}
<form method="post" action="upload.php" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload" class="upload">
<input type="submit" onclick="GetFileName()" value="Upload Image" name="submit" id="submit">
</form>
This is almost work but the image only display few second and then it disappear.
Try some thing like this in Jquery:
$('#upload').on('click', function() {
var img_name = $('#pic').val();
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
if(output) // if success
{
$('#img_container').append('<img src="img_path/"'+ img_name +'>'); // It will display the uploaded image
}
}
});
$('#pic').val(''); /* Clear the file container */
});
Html:
<body>
<input id="pic" type="file" name="pic" />
<button id="upload">Upload</button>
<!-- To display image -->
<div id="img_container">
</div>
</body>
I think the key issue to your question here is in how to keep track of all the uploads. This is likely better solved by relying on a persistence store, like a database, to track of all uploaded files on a global level.
For example, when an upload occurs, you can insert a record into an uploads table in your database like so...
// prepare the statement
$stmt = $db->prepare("INSERT INTO uploads (userId, fileName) VALUES(:userId, :fileName)");
if ($_FILES['upload']['error'] == UPLOAD_ERR_OK) { // no errors
// move the file to a permanent location
$tmpName = $_FILES['upload']['tmp_name'];
move_uploaded_file($tmpName, $uploadDir . "/$tmp_name");
$result = $stmt->execute(
[
'userId' => $_SESSION['userId'], // or however you track the user
'fileName' => $_FILES['upload']['tmp_name'],
]
);
if ($result) {
// record added successfully!
} else {
// failed
}
}
Now you can display all uploaded files by looking at the uploads table in your database and display them to users like so...
// prepare the statement
$start = $_GET['start'] ?? 0;
$stmt = $db->prepare("SELECT userId, fileName FROM uploads LIMIT ?,20");
if ($stmt->execute([$start])) {
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $row) {
echo "<img src='$uploadDir/{$row['fileName']}'>";
}
}
Or you could show only those uploads made by a specific user by adding a WHERE userId = ? clause to that query, for example.

upload array of files with ajax

I have form that allow me to submit text + number of files. the form submitted with AJAX.
Because it's a number of files my upload function give me error:
Warning: move_uploaded_file(images/usersFiles/14367317720-101.JPG) [function.move-uploaded-file]: failed to open stream: No such file or
directory in C:\Program Files
(x86)\wamp\www\new-site\func\global.func.php on line 134
line 134 is:
if (move_uploaded_file($files['file']['tmp_name'][$i], USER_FILES.$files['file']['name'][$i]))
files' var should be array (because I can load number of files).
How can I fix the error?
HTML:
<form class="form-horizontal" action='#' method="post" id="addCommentForm" enctype="multipart/form-data">
<textarea class="form-control" name="post[text]"></textarea>
<input type='file' name='file[]' class='multi form-control' maxlength='1' accept='gif|jpg|png|bmp' id="files"/>
<a class="btn btn-primary" id="submit">submit</a>
</form>
JS:
$(function() {
$("#submit").click(function() {
var file_data = $('#files').prop('files')[0];
var form_data = new FormData();
form_data.append('file[]', file_data);
var files_data = form_data;
var act = 'add';
form_data.append('act', act);
form_data.append('post[text]', $("#addCommentForm").find("textarea").val());
$.ajax({
type: "POST",
url: "ajax/addPost.php",
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data)
{
$('#commentsBox').html(data);
$("#addCommentForm")[0].reset();
}
});
return false; // avoid to execute the actual submit of the form.
});
});
server:
function upload_files ($ownerID, $msg, $files, $type)
{
$dateLX = get_current_linuxTime();
///////// Upload files //////////////
if(!empty($files))
{
foreach($files['file']['name'] as $i => $fileName)
{
$fileSurffix = pathinfo ($_FILES['file']['name'][$i]);
$fileSurffix = $fileSurffix['extension'];
$files['file']['name'][$i] = str_replace(' ','',$files['file']['name'][$i]);
$files['file']['name'][$i] = $dateLX.$i."-".$ownerID.".".$fileSurffix;
$fileName = $files['file']['name'][$i];
if (move_uploaded_file($files['file']['tmp_name'][$i], USER_FILES.$files['file']['name'][$i]))
{
$uploadFilesQuery = "INSERT INTO `files` (ownerID, name, type)
VALUES('$ownerID', '$fileName', '$type')";
$res = mysql_query($uploadFilesQuery);
if (!$res)
$msg['error']['uploadFile'] = "error <br />".mysql_error();
}
elseif ($files['file']['error'][$i] != 4)
$msg['error']['uploadFile'] = "ERROR ";
}
}
return ($msg);
}
USER_FILES must be an absolute path like
"C:\Program Files (x86)\wamp\www\new-site\images\usersFiles\"

Not able to upload image via jquery, ajax and PHP

I have fair knowledge of JS, PHP and Ajax but this simple problem has driven me nuts.
I am trying to upload an image silently, without using a form. I am not using a form because that will lead to nested forms in my HTML, which I read, can cause additional issues.
I have been able to use oFReader, to preview the images.
To upload the image, I am attempting an AJAX call as given below:
HTML
<div id="loginButton2">
<div id="personalimg" >
<img src="photos/seller_photos/<?php echo $profile_pic; ?>" width="70" hight="70" />
</div>
</div>
<div id="loginBox2" style="display:none">
<div id="loginForm2" class="floatLeft" >
<fieldset>
<input id="file" type="file" name="profile_img" value="photos/seller_photos/<?php echo $profile_pic;?>"/>
<input id="file_submit" type="hidden" name="submit4" value="1" >
</fieldset>
</div>
</div>
JS
$('#file').change(function(){
var oFReader = new FileReader();
oFReader.readAsDataURL(this.files[0]);
var fd = new FormData();
var file = $("#file").prop("files")[0];
fd.append('profile_img', file);
fd.append('submit4', 1);
fd.append('filename', 1);
oFReader.onload = function (oFREvent) {
$.ajax({
url: "upload.php",
dataType: 'image',
cache: false,
contentType: false,
processData: false,
type: "POST",
data: fd,
success: function(data){
console.log(data);
},
error: function(){
console.log("image upload failed");
}
});
$('#loginForm2').toggle();
$('#personalimg').html('<img src="'+oFREvent.target.result+'" width="70" height="70">');
};
});
PHP
if(isset($_POST['submit4'])) {
$check_sql = "select profile_pic from profile where user_id=$user_id";
$check_rs = mysql_query($check_sql);
$check_num = mysql_num_rows($check_rs);
if($check_num==0) {
$sql = "insert into profile(user_id) values($user_id)";
$rs = mysql_query($sql);
}
$fName = $_FILES["profile_img"]["name"] ;
$data = explode(".", $fName);
$fileName = $user_id.'.'.$data[1];
if($fName!='')$user->update('profile_pic',$fileName);
$fileTmpLoc= $_FILES["profile_img"]["tmp_name"];
//image store path
$pathAndName = "photos/seller_photos/".$fileName;
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
if(move_uploaded_file) {
$response['status'] = '1';
header('Location: edit_profile_new.php');
} else {
$response['status'] = '0';
}
return $response;
}
But somehow, I have not been able to get this to work. I am using chrome. I get 302 Found status code and "image upload failed" in console.
Can someone please help me out?
ps: I know, mysql is deprecated and will migrate to pdo. This code is inherited and hence has old standards.

Categories