Upload/resize image via Ajax on button click, not submit - javascript

I have this HTML form that works currently. It lets you choose an image and it uploads to my server (changing it to have a max height or width of 200) and then displays the image back on the form to show the user...
<div id="preview"><img id="image" src="no-image.jpg" /></div>
<form id="form" action="" method="post" enctype="multipart/form-data">
<input id="uploadImage" type="file" accept="image/*" name="image" />
<input id="button" type="submit" value="Upload">
</form>
<div id="err"></div>
Here is the Jquery...
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload-image-ajax.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data) {
if(data=='invalid file') {
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
} else {
// view uploaded file.
$("#image").attr('src', data);
/* $("#preview").html(data).fadeIn();*/
$("#form")[0].reset();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
});
And here is the PHP the Jquery calls...
<?php
require_once("includes/session.php");
$poolid=strtolower($_SESSION['poolid']); //lowercase it first so we get exact matches
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$path = 'uploads/'; // upload directory
if(isset($_FILES['image']))
{
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
//checking if image exists
if(file_exists("uploads/".$poolid.".png")) {
unlink("uploads/".$poolid.".png");
}
// check's valid format
if(in_array($ext, $valid_extensions)) {
//re-size the image and make it a PNG before sending to server
$final_image = $poolid. ".png";
$path = $path.strtolower($final_image);
$size = getimagesize($tmp);
$ratio = $size[0]/$size[1]; // width/height
if( $ratio > 1) {
$width = 200;
$height = 200/$ratio;
}
else {
$width = 200*$ratio;
$height = 200;
}
$src = imagecreatefromstring(file_get_contents($tmp));
$dst = imagecreatetruecolor($width,$height);
imagecopyresampled($dst,$src,0,0,0,0,$width,$height,$size[0],$size[1]);
imagedestroy($src);
imagepng($dst, $path); // adjust format as needed
imagedestroy($dst);
echo $path ."?".rand(1,32000);
} else {
echo 'invalid file';
}
}
?>
Again this all works fine when this form is by itself on a page. However, I now want this Image Upload area to be part of a much larger form. I tried adding the exact HTML inside another larger form and as you might have guessed, when I click "upload" to upload the image, it tries to submit the larger form.
I would like it to simply upload/resize the image without submitting the larger form, display the image back to the user and let them continue filling out other form inputs.
I tried removing the form elements (so there was no more nesting of form tags), so the HTML was reduced to this (notice I changed the input type of "submit" to now be "button")...
<div id="preview"><img id="image" src="no-image.jpg" /></div>
<input id="uploadImage" type="file" accept="image/*" name="image" />
<input id="button" type="submit" value="Upload">
<div id="err"></div>
Then in the Jquery, I removed the .on submit stuff and replaced it with .click, since I just want this image stuff to happen on click, not on any type of submit.
$(document).ready(function () {
$("#button").click(function(){
var imageData = new FormData();
imageData.append('image', $('#uploadImage')[0].files[0]);
//Make ajax call here:
$.ajax({
url: 'upload-image-ajax.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: imageData,
beforeSend : function() {
$("#err").fadeOut();
alert('hi');
},
success: function(result) {
alert('succ');
if(result=='invalid file') {
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
} else {
// view uploaded file.
$("#image").attr('src', result);
/* $("#preview").html(data).fadeIn();*/
$("#form")[0].reset();
}
},
error: function(result) {
alert(result.responseText);
$("#err").html(result).fadeIn();
}
});
});
});
Again, I am reading about the data and dataType settings at http://api.jquery.com/jquery.ajax/, but I cannot grasp it for the life of me (no experience with JSON probably isn't helping me).
Can someone please speak towards the var imageData and .append part of my new Jquery, as I assume that must be where things are going off the rails. As is often the case, this seems like it should be super easy to accomplish since I have it working fine on its own, but it's driving me insane.

Related

upload a form's file and text data to PHP using jQuery and AJAX

Good morning. I'm trying to make the form submission of a message more fluid avoiding the reload of the page for the sending of it. Since the message may be text or image, I need to send both of them to a PHP page for upload. I'm using this code in the html page:
<form id="newmessage" enctype="multipart/form-data">
<textarea form="newmessage" id="messagetext" name="messagetext" ></textarea>
<input type="submit" name="submit" value="send" onclick="return newMessage();">
<input type="file" accept="image/*" id="image" name="image">
</form>
<script>
function newMessage(){
var messagetext = document.getElementById("messagetext").value;
var image = document.getElementById("image").value;
$.ajax({
type:"post",
url:"new_message.php",
data:
{
"messagetext" :messagetext,
"image" :image,
},
cache:false,
success: function(html) {
document.getElementById("messagetext").value = "";
}
});
return false;
}
</script>
As you can see, I'm allowing users to type in the textarea or upload a file. When they submit the form, the newMessage() method is invoked and sends image and messagetext to new_message.php, which process them:
// new_message.php
$messagetext = $_POST["messagetext"];
$image = $_FILES["image"]["tmp_name"];
if((!empty($messagetext) || isset($image))) {
if(!empty($messagetext)) {
// create text message
} else if(isset($image)) {
// create image message
}
}
When I write a text message it works perfectly, but it doesn't send anything if it's image. Maybe the image variable in AJAX is not taking the file properly. I excuse if this question is unclear, but I'm a beginner in StackOverlow and I'm open to edits. Thanks for all replies.
can you try this. you don't need to worry about the file and message in textarea. Make sure you have added jQuery.
$("#newmessage").on("submit", function(ev) {
ev.preventDefault(); // Prevent browser default submit.
var formData = new FormData(this);
$.ajax({
url: "new_message.php",
type: "POST",
data: formData,
success: function (msg) {
document.getElementById("messagetext").value = "";
},
cache: false,
contentType: false,
processData: false
});
return false;
});

How to work with filepond plugin, ajax and php, file name not detected on the server

I am trying to upload file to an xammp server. I'm unable to access the file it uploaded. I doubt on this link server: 'http://localhost/', because when I change it to the name of PHP file that process data on the server side it works.
But also I added another field called username on the form, look below on the code, and I want to combine them on single submit event with Ajax, but I have no idea for this combination.
//initialize file pond with jquery plugin
$('#file').filepond({
allowMultiple: false,
server: 'http://localhost/'
});
//ajax
$("form").on('submit', function(e) {
$.ajax({
url: 'send.php',
type: 'POST',
data: new FormData(this),
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
}).done(function(data) {
if (data.success == false) {
if (data.errors.username) {
$('#username').append('<span class="text-danger">' + data.errors.username + '</span>');
}
if (data.errors.file) {
$('#file').append('<span class="text-danger">' + data.errors.file + '</span>');
}
}
});
e.preventDefault();
});
//my form field between form tag
<form method="POST" enctype="multipart/form-data">
<input type="text" name="username" id="username">
<input type="file" name="file" id="file">
</form>
//php code validate file and name
$errors = [];
if(empty($_FILES['username'])) {
$errors['username'] = 'Enter your name!';
}
//other validation goes here...
if(empty($_FILES['file']['name'])) {
$errors['file'] = 'upload file!';
}
//other validation goes here...
echo json_encode($errors);
EDIT:
I notice that the name attribute in the input type file is not available/removed by the plugin and the input ID is also overwritten every time i load the page,
//example the input look like where the id="filepond--browser-men6qus3m" change every time i load new file
<input class="filepond--browser" type="file" id="filepond--browser-men6qus3m" aria-controls="filepond--assistant-men6qus3m" aria-labelledby="filepond--drop-label-men6qus3m" accept="image/png">
Thus why i get undefine typoerror and the file not attached
You are going to send a FormData with Ajax request. The problem you've mentioned here is that you want to include the file which is attached using FilePond library. Here is my solution to append FilePond files to a FormData:
$(document).ready(function () {
pond = FilePond.create(
document.querySelector('#file'), {
allowMultiple: true,
instantUpload: false,
allowProcess: false
});
$("#upload_form").submit(function (e) {
e.preventDefault();
var fd = new FormData(this);
// append files array into the form data
pondFiles = pond.getFiles();
for (var i = 0; i < pondFiles.length; i++) {
fd.append('file[]', pondFiles[i].file);
}
$.ajax({
url: 'fileupload2.php',
type: 'POST',
data: fd,
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
success: function (data) {
// todo the logic
// remove the files from filepond, etc
},
error: function (data) {
// todo the logic
}
}
);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script src="https://unpkg.com/filepond/dist/filepond.min.js"></script>
<script src="https://unpkg.com/jquery-filepond/filepond.jquery.js"></script>
<link href="https://unpkg.com/filepond/dist/filepond.css" rel="stylesheet"/>
<script src="https://unpkg.com/filepond/dist/filepond.js"></script>
<form id="upload_form" method="POST" enctype="multipart/form-data">
<input type="text" name="username" id="username">
<input type="file" name="file" id="file" class="filepond">
<input type="submit" value="Upload"/>
</form>
And on your PHP side, you need can get the files like this:
$errors = [];
if (empty($_POST["username"])) {
$errors['username'] = 'Enter your name!';
}
// check if file is set and uploaded.
if (!isset($_FILES['file']) || $_FILES['file']['error'] == UPLOAD_ERR_NO_FILE) {
$errors['file'] = 'upload file!';
} else {
$filesNum = count($_FILES['file']['name']);
// Looping all files
for ($i = 0; $i < $filesNum; $i++) {
// same the file
move_uploaded_file($_FILES['file']['tmp_name'][$i], $_FILES['file']['name'][$i]);
}
}
// Other validation goes here...
// Return the proper response to the client
// I'll leave this to you
And note that:
I've disabled instantUpload and allowProcess on FilePond to prevent auto uploading and processing.
Your PHP side needs more validation and also it should return proper response to the Ajax.

Passing one image through ajax and another through form

Onclick button i am and trying to save 2 different images.
I am passing One image through ajax & another through form, but i can able to download only one image at a time. Will it create any conflicts ?
Do i need to have correct Content-Length header for both image ?
Html
<div id="target">
<div id="container" class="container"></div>
</div>
<input type="submit" value="Save" onclick="capture();" />
<form method="POST" enctype="multipart/form-data" action="save.php" id="myForm">
<input type="hidden" name="img_val" id="img_val" value="" />
</form>
Script
function capture()
{
// one image
var canvas = document.getElementById("1");
var dataURL = canvas.toDataURL(); // THE BASE 64 DATA
var dataFileName = document.getElementById('fileup').value.replace(/.*(\/|\\)/, ''); // GET THE FILE NAME THAT USER CHOSE
var dataFileType = dataFileName.split('.').pop();
data = new FormData();
data.append('imgBase64', file, file.name);
$.ajax({
type: "POST",
url: "save.php",
cache:false,
contentType: false,
processData: false,
data: data
}).done(function(o) {
var response = JSON.parse(o);
$('body').prepend('<img src="/var/www/html/ecom1/site/test/final/' + response.data[0].fileName + '" style="height: 200px; width: auto;">');
});
//another image
$('#target').html2canvas({
onrendered: function (canvas) {
//Set hidden field's value to image data (base-64 string)
$('#img_val').val(canvas.toDataURL("image/png"));
//Submit the form manually
document.getElementById("myForm").submit();
}
});
}
php
<?php
// One image code :
if (isset($_FILES['imgBase64']))
{
$fname = $_FILES["imgBase64"]["name"]; // THE FILENAME THE USER CHOSE IS RECEIVED VIA POST
$img = filter_input(INPUT_POST, 'imgBase64'); // THE BASE64 ENCODING RECEIVED VIA POST
$imgtype = $_FILES["imgBase64"]["type"]; // THE FILE TYPE / EXTENSION IS RECEIVED VIA POST
if(move_uploaded_file($_FILES["imgBase64"]["tmp_name"], "/var/www/html/ecom1/site/test/final/".$fname))
{
echo '{"error":false, "message":null,"data":[{"msg": "Image has been saved successfully!", "fileName": "' . $fname . '"}]}';
}
else
{
echo '{"error":true, "message":"File not uploaded"}';
}
}
// another image code :
//Show the image
echo '<img src="'.$_POST['img_val'].'" />';
//Get the base-64 string from data
$filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);
//Decode the string
$unencodedData=base64_decode($filteredData);
//Save the image
file_put_contents('/var/www/html/ecom1/site/test/final/img.png', $unencodedData);
?>
Here is Full html & php code

how to insert an image to database using ajax jquery

so i have a form update but my problem is i cant save my image into my database only the file path..
here is my code.
<form action="" id="update_profile" method="POST" enctype="multipart/form-data">
<div class="col-md-4">
<img class="img-responsive" id="profile_image" name="profile_image" src=""/>
<input class="btn-success" type="file" name="image" id="image" onchange="loadFile(event)">
</div>
<input type="text" id="users_lastname" name="users_lastname" class="form-control" value="">
</form>
from the form update i use ajax to display the data from my database to the form fields..
$.ajax({
url:'../ajax/getprofile.php',
type:'POST',
data:{userid:user},
dataType:'JSON',
success: function(result){
$('#profile_image').attr('src',result.profile_image);
$('#users_lastname').val(result.users_firstname);
},
error:function(status){
}
});
$('#update_profile').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '../ajax/update_profile.php',
type:'POST',
data: formData,
dataType: 'JSON',
contentType: false,
cache: false,
processData:false,
success:function(result){
console.log(result);
},
error:function(status){
// console.log(status.responseText);
}
});
});
and use another ajax for submitting the form so basically what happens is from the <img src="../assets/img/faces/avatar.jpg"> this is where i display my image from my db. and when i click the <input class="btn-success" type="file" name="image" id="image" onchange="loadFile(event)"> <img src="../assets/img/faces/koala.jpg"> will change its value...
if (isset($_POST)) {
$users_lastname = $_POST['users_lastname'];
$profile_image = $_POST['profile_image'];
$imgFile = $_FILES['image']['name'];
$tmp_dir = $_FILES['image']['tmp_name'];
$imgSize = $_FILES['image']['size'];
}
if($imgFile)
{
$upload_dir = '../assets/img/faces/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$userpic = rand(1000,1000000).".".$imgExt;
if(in_array($imgExt, $valid_extensions))
{
if($imgSize < 2000000)
{
// unlink($upload_dir.$_SESSION['image']);
move_uploaded_file($tmp_dir,$upload_dir.$userpic);
}
else
{
echo '<script>
alert("Sorry, your file is too large it should be less then 2MB");
</script>';
}
}
else
{
echo '<script>
alert("Sorry, only JPG, JPEG, PNG & GIF files are allowed.");
</script>';
}
}
else
{
$userpic = $imgs; // old image from database
$userpic = substr($userpic,20);
}
if(!isset($errMSG))
{
$path = '../assets/img/faces/'. $userpic;
$action= 'Updated his/her information';
$logs= $log->insertLogs($usernm,$action);
$res = $users->Userupdated($user,$users_firstname,$users_lastname,$users_email);
$data = $users->updateUserdetail($user,$path,$profile_contact,$profile_address,$profile_department,$profile_specialization,$profile_aboutme);
}
else{
$errMSG = "Sorry Data Could Not Updated !";
}
but when i tried to upload without replacing the image from the src. what happens is it only uploads the location path not the exact image. also when i replace the image it only uploads the location path.. i dont know if this is the correct approach for getting the src image any idea for this?
Try this, I used this in one of my proect:
var form = $("#update_profile").get(0);
e.preventDefault(); //keeps the form from behaving like a normal (non-ajax) html form
$.ajax({
url: '../ajax/update_profile.php',
type: 'POST',
data: new FormData(form),
dataType: 'json',
mimeType: 'multipart/form-data',
processData: false,
contentType: false,
success: function (response) {
},
error: function (data) {
}
});

Isset does not work with ajax call

I am making a simple page where user can upload a image without refreshing the whole page. But if(isset($_post[oneimgtxt])) is not working..
here is my serverSide Code that upload image :
<?php
$maxmum_size = 3145728; //3mb
$image_type_allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST["oneimgtxt"])){//<!------------------ this line is not working
if((!empty($_FILES[$_FILES['upimage']['tmp_name']])) && ($_FILES["upimage"]['error'] == 0)){
$file=$_FILES['upimage']['tmp_name'];
$image_count = count($_FILES['upimage']['tmp_name']);
if($image_count == 1){
$image_name = $_FILES["upimage"]["name"];
$image_type = $_FILES["upimage"]["type"];
$image_size = $_FILES["upimage"]["size"];
$image_error = $_FILES["upimage"]["error"];
if(file_exists($file)){//if file is uploaded on server in tmp folder (xampp) depends !!
$filetype =exif_imagetype($file); // 1st method to check if it is image, this read first binary data of image..
if (in_array($filetype, $image_type_allowed)) {
// second method to check valid image
if(verifyImage($filename)){// verifyImage is function created in fucrenzione file.. using getimagesize
if($ImageSizes < $maxmum_size){//3mb
$usr_dir = "folder/". $image_name;
move_uploaded_file($file, $usr_dir);
}else{
$error_container["1006"]=true;
}
}else{
$error_container["1005"]=true;
}
}else{
$error_container["1004"]=true;
}
}else{
$error_container["1003"]=true;
}
}else{
$error_container["1002"]=true;
}
}else{
$error_container["1007"]=true;
}
}else{//this else of image issset isset($_POST["oneimgtxt"])
$error_container["1001"]=true;//"Error during uploading image";
}
echo json_encode($error_container);
}
?>
in chrome inspect element i got this..
image
and this is my js code with ajax...
$(".sndbtn").click( function(e){
var form = $("#f12le")[0];
var formdata = new FormData(form)
$.ajax({
type:'POST',
//method:'post',
url: "pstrum/onphotx.php",
cache:false,
data: {oneimgtxt : formdata},
processData: false,
contentType: false,
success:function (e){console.log(e);}
});
});
Here is html code:
<form method="post" id="f12le" enctype="multipart/form-data">
<input type="file" name="upimage"/>
<label for="imgr">Choose an Image..</label>
<textarea placeholder="Write something about photo"></textarea>
<input type="button" name="addimagedata" value="Post" class="sndbtn"/>
</form>
Thanks for any help.
You should send your FormData as a whole data object not a part of another data object. So, it should be like this -
$(".sndbtn").click( function(e){
var form = $("#f12le")[0];
var formdata = new FormData(form)
$.ajax({
type:'POST',
//method:'post',
url: "pstrum/onphotx.php",
cache:false,
data: formdata,
processData: false,
contentType: false,
success:function (e){console.log(e);}
});
});
Now, you should be able to access the form as it is. For example if you have any input with name inputxt inside the form, you should be able to access it with $_POST['inputxt']. And if you have any input type="file" with the name upimage, you need to access through $_FILES['upimage']. So, if you want to do isset() for that. You can do like this :
if(isset($_FILES['upimage'])){
add enctype on form any time using file inputs
<form enctype="multipart/form-data" >
<input type=file />
...
</form>
and make sure it's always a POST request.
Good luck...!
I had headaches for this thing! you should use $_FILES['name_of_dom_element']; in your php code.

Categories

Resources