hi guys i need your help im not very good with ajax im trying to upload a image using a form with php the image is not getting to the php i got error on
Notice: Undefined index: ImageFile in line 9
the line is this one
move_uploaded_file($_FILES['ImageFile']['tmp_name'], "$Destination/$NewImageName");
this is my jquery
$("#send_friend").click(function(e) {
e.preventDefault();
$("#message").empty();
$('#loading').show();
// getting the values that user typed
var add_friends = '1';
var friend_name = $("#friend_name").val();
var friend_url = $("#friend_url").val();
var ImageFile = $('#ImageFile').prop('files')[0];
// forming the queryString
var data=
'add_friends=' + add_friends +
'&clan_name=' + clan_name +
'&friend_name=' + friend_name +
'&friend_url=' + friend_url +
'&ImageFile=' + ImageFile;
// ajax call
$.ajax({
type: "POST",
url: "components/friends.php",
data: data,
success: function(data){ // this happen after we get result
$('#loading').hide();
$("#message").html(data);
}
});
return false;
});
this is my php
if(isset($_POST['add_friends'])){
include "../_database/database.php";
$Destination = '../imagenes/friends';
$friend_name = $database ->real_escape_string(htmlentities($_REQUEST['friend_name']));
$friend_url = $database ->real_escape_string(htmlentities($_REQUEST['friend_url']));
if(!isset($_FILES["ImageFile"]) || !is_uploaded_file($_FILES["ImageFile"]["tmp_name"])){
$NewImageName= 'default.png';
move_uploaded_file($_FILES["ImageFile"]["tmp_name"], "$Destination/$NewImageName");
}
else{
$RandomNum = rand(0, 999);
$ImageName = str_replace(' ','-',strtolower($_FILES['ImageFile']['name']));
$ImageType = $_FILES["ImageFile"]["type"];
$ImageExt = substr($ImageName, strrpos($ImageName, '.'));
$ImageExt = str_replace('.','',$ImageExt);
$ImageName = preg_replace("/\.[^.\s]{3,4}$/", "", $ImageName);
$NewImageName = $ImageName.'-'.$RandomNum.'.'.$ImageExt;
move_uploaded_file($_FILES["ImageFile"]["tmp_name"], "$Destination/$NewImageName");
}
$sql = "INSERT INTO family (name,url, shield)
VALUES ('".$friend_name."', '".$friend_url."', '".$NewImageName."')";
$r1 = mysqli_query($database,$sql);
$sqlResult = $r1;
/*** run the sql statement ***/
}
and my html
<div class="form-group">
<label for="exampleInputFile" class="supercell">Shield</label>
<input type="file" id="ImageFile" name="ImageFile"/>
only with the file i have some problems the database is been populated with all the other vars but can´t get the file to pass to the php any help will be really appreciated
You need to set the contentType to multipart/form-data because the form includes a file.
type: "post",
contentType: "multipart/form-data"
Related
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.
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.
I have two pages first page has a form which accepts information like name,mobile-no etc and an image from user.
I want to access the image using jquery and send it other page using $.post() method there i want to access the image and insert it into database
First File
<script>
$(function(){
$("#add_staff").click(function(){
event.preventDefault();
var regex_mobile=/^\d{10}$/;
var regex_email = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
var insti=$("#inst_id").val();
var name=$("#Staff_name").val();
var pwd=$("#Staff_pwd").val();
var add=$("#staff_address").val();
var dob=$("#Staff_dob").val();
var mail=$("#Staff_mail").val();
var role=$("#Staff_role").val();
var mobile=$("#Staff_mobile").val();
var img = $('#image').prop('files')[0];
if(name=="" || pwd=="" || add=="" || dob=="" || mail=="" || role=="" || mobile=="")
{
alert("All fields are compulsory");
}
else{
if(!regex_mobile.test(mobile)) {
alert("Mobile Number invalid");
}
else if(!regex_email.test(mail)){
alert("Email Invalid");
}
else{
$.post("add_faculty2.php",
{
insti: insti,
name:name,
pwd:pwd,
add:add,
dob:dob,
mail:mail,
role:role,
mobile:mobile,
img:img
},
function(data,status){
$("#msg").text(data);
alert(data);
alert(status);
});
}
});
});
</script>
In the above file all the information is accepted from the user and in the jquery i have tried to access all the information and image then i am trying to send the data to other page using $.post() method.
Second File
<?php
$insti =$_POST['insti'];
$name =$_POST['name'];
$pwd =$_POST['pwd'];
$add =$_POST['add'];
$dob =$_POST['dob'];
$mail =$_POST['mail'];
$role =$_POST['role'];
$mobile =$_POST['mobile'];
$img =$_POST['img'];
$today = date("Y-m-d H:i:s");
include_once 'conf.php';
$q="insert into tbl_staff_details(inst_id,name,pwd,email,phone,photo,address,dob,role,created_date) values('".$insti."','".$name."','".$pwd."','".$mail."','".$mobile."','".$img."','".$add."','".$dob."','".$role."','".$today."')";
echo $q;
$r=mysqli_query($con,$q);
if($r)
{
echo "Success";
}
else
{
echo "Fail";
}
?>
In the above file i am accessing all the information using $_POST[] sent by the $.post() method in the first file then i am trying to insert all the data in the database
Problem is that the data is not inserted in the database
But when i omit the image all the other data is inserted in the database
Ok first you need to use FormData() in your javascript
example
// formdata
var formdata = FormData();
var insti=$("#inst_id").val();
var name=$("#Staff_name").val();
var pwd=$("#Staff_pwd").val();
var add=$("#staff_address").val();
var dob=$("#Staff_dob").val();
var mail=$("#Staff_mail").val();
var role=$("#Staff_role").val();
var mobile=$("#Staff_mobile").val();
var img = $('#image').prop('files')[0];
formdata.append('upload[insti]', insti);
formdata.append('upload[name]', name);
formdata.append('upload[pwd]', pwd);
formdata.append('upload[add]', add);
formdata.append('upload[dob]', dob);
formdata.append('upload[mail]', mail);
formdata.append('upload[role]', role);
formdata.append('upload[mobile]', mobile);
formdata.append('upload[img]', img);
// now send
$.post("add_faculty2.php", formdata,
function(data,status){
$("#msg").text(data);
alert(data);
alert(status);
}
);
And in your php script you can access the image by calling
$img = $_FILES['upload']['img']['name'];
$img_tmp = $_FILES['upload']['img']['tmp_name'];
others
$insti = $_POST['upload']['insti'];
$name = $_POST['upload']['name'];
$pwd = $_POST['upload']['pwd'];
$add = $_POST['upload']['add'];
$dob = $_POST['upload']['dob'];
$mail = $_POST['upload']['mail'];
$role = $_POST['upload']['role'];
$mobile = $_POST['upload']['mobile'];
$today = date("Y-m-d H:i:s");
// you can see the image printed here..
var_export($img);
Hope this helps.
I wrote the code for changing the background image of a div. I am able to upload the image and image is visible in the folder. The image path is getting uploaded in mysql database. But the image is not displaying as background in the div. The php variable value(location) for the specified path of image is not passing to the div. Can any one please let me know my mistake?
<?php
session_start();
include_once ('dataconnect.php');
$db_conx = mysqli_connect("localhost", "root", "", "productiondata");
$uid = $_SESSION['user_id'];
$username = $_SESSION['user_name'];
if (isset($_FILES['file'])) {
global $location;
$imagename = $_FILES["file"]["name"];
$imagepath = "images/";
$location = $imagepath . $_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"], "$imagepath" . $_FILES["file"]["name"]);
$sql = "INSERT INTO image(user_id,imagepath,imagename) VALUES('$uid','$imagepath','$imagename')";
$query = mysqli_query($db_conx, $sql);
$sql1 = "SELECT * FROM image";
$query1 = mysqli_query($db_conx, $sql1);
while ($row = mysqli_fetch_array($query1)) {
$imagename = $row['imagename'];
$imagepath = $row['imagepath'];
echo $location;
}
}
jquery code
$('document').ready(function () {
$('.js_p-uploader').click(function () {
$('#file').click();
$('#file').change(function (e) {
e.preventDefault();
var blob = this.files[0];
var formData = new FormData();
formData.append('file', blob);
$.ajax({
url: "profile.php",
type: "POST",
data: formData,
mimeType: "multipart/form-data",
processData: false,
contentType: false,
success: function (location) {
}
});
});
});
});
div class="profile-cover-wrapper" style="background-image:url('?php echo
$location ;?');"input type="file" id="file" name ="file"
Returned data from an Ajax call cannot be used outside, or cannot be used as a PHP variable. What you can do is to change the src attribute of your <img> inside the success: function():
// AJAX CALL HERE
success: function(location) {
$('.profile-cover-wrapper').css("background-image", "url("+location+")");
}
I'm trying to upload a canvas.todataurl() image (getUserMedia) to server using jQuery post and php to handle the data, but I'm having some problems. All the images I'm uploading end up being corrupted, half of the image is missing. I also have a MySQL database where I'm storing data related to the image (title, text, date and the like). It seems that the more I have the related data the more the image get corrupted.
Therefore, I'm wondering is this a browser limitation or does this have something to do with jQuery post. I've also checked the PHP max_post_size and it's 16mb, so that shouldn't be a problem. I don't have access to the server settings. I'm quite puzzled with this, what can I do? Is it possible to divide the canvas.todataurl() to multiple parts and then post?
JavaScript
window.addEventListener('DOMContentLoaded', function() {
var video = document.getElementById('videoStream');
var canvas = document.getElementById('canvasImage');
var status = document.getElementById('status');
var button = document.getElementById('button');
//var others = document.getElementById('others');
var imageHolder;
document.getElementById('form').style.display = 'none';
var image = null; // kuvan datauri joka lähtee php:lle
window.URL || (window.URL = window.webkitURL || window.mozURL || window.msURL);
navigator.getUserMedia || (navigator.getUserMedia = navigator.mozGetUserMedia || navigator.webkitGetUserMedia || navigator.msGetUserMedia);
// toString : function() {return "video,audio";} canarya varten
if (navigator.getUserMedia) {
navigator.getUserMedia({video: true, audio: false, toString : function() {return "video,audio";}}, onSuccess, onError);
} else {
status.innerText = "getUserMedia is not supported in your browser, sorry :(";
}
function onSuccess(stream) {
var source;
if (window.webkitURL) {
source = window.webkitURL.createObjectURL(stream);
} else {
source = stream; // Opera ja Firefox
}
video.width = 500;
video.height = 375;
video.autoplay = true;
video.src = source;
}
function onError() {
status.innerText = "Please allow access to your webcam.";
}
button.addEventListener('mousedown', function() {
// Poistetaan aikaisempi kuva jos sellaista on
//document.body.removeChild(imageHolder);
// luodaan kuva uudestaan
imageHolder = document.createElement('figure');
imageHolder.id = 'imageHolder';
document.body.appendChild(imageHolder);
img = document.createElement('img');
imageHolder.appendChild(img);
// kuva on yhtäsuuri kuin video
canvas.width = video.width;
canvas.height = video.height;
img.width = 350;
img.height = 225;
// piirretään canvasille kuva videosta
var context = canvas.getContext('2d');
context.drawImage(video, 0, 0, canvas.width, canvas.height);
}, false);
button.addEventListener('mouseup', function() {
// Canvasilta kuvaksi levylle tallentamista varten
canvas.style.display = 'none';
video.style.display = 'none';
button.style.display = 'none';
others.style.display = 'none';
document.getElementById('form').style.display = 'block';
image = canvas.toDataURL('image/png');
img.src = image;
}, false);
// jquery post
$('#send').click(function(){
var image2 = image.replace('data:image/png;base64,', '');
$.post('upload.php',
{
title: $('#title').val(),
blog: $('#blog').val(),
category: $('#category').val(),
author: $('#author').val(),
imagename: image2
});
});
}, false);
PHP upload.php
define('UPLOAD_DIR', 'images/');
$img = $_POST['imagename'];
$img = str_replace(' ','+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Tiedoston tallennus ei sitten onnistu millään...';
$imagename = $file; // this is the file name for the MySQL database
My problem is (I think) image = canvas.toDataURL('image/png'); and the jQuery post.
The canvas.toDataUrl() string is about 700 000 letters long.
You might wanna try this:
<?php
$decoded = "";
for ($i=0; $i < ceil(strlen($encoded)/256); $i++)
$decoded = $decoded . base64_decode(substr($encoded,$i*256,256));
?>
I got it from here: http://www.php.net/manual/en/function.base64-decode.php#92980
The code basically tries to partially decodes the base64 string. I haven't tested this though. I've never dealt with base64 images as big as what you're working with.
Split it, use two, variables and merge in php, works fine. ;-)
var resourcelength_all = resource.length;
var resourcelength_split = resourcelength_all / 2;
var resource_part1 = resource.substr(0, resourcelength_split);
var resource_part2 = resource.substr(resourcelength_split, resourcelength_all);