how to insert an image to database using ajax jquery - javascript

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) {
}
});

Related

$.ajax not uploading files using data: object array method

Ive searched on Stack overflow all over the place and could not find a solution or a post that is close to my problem.
So if this has been posted before I do apologies.
I am posting some information using a different method rather than posting a form which I will explain after I show you the code :)
Jquery:
$("#submit-add-cpos").on('click',function(){
var checkHowManyInstallments = $('#installment-ammount').val();
var checkCpoNumber = $('#addcponumber').val();
var checkCpoTotalPrice = $('#addcpoprice').val();
var checkCpoContactName = $('#addcpocontactname').val();
var form_data = new FormData();
form_data.append("type", 'addcpo');
form_data.append("quoteid", '<?php echo $_GET['id']; ?>');
form_data.append("installmentamount", checkHowManyInstallments);
form_data.append("cponumber", checkCpoNumber);
form_data.append("costcode", '<?php echo $quotecostcode; ?>');
form_data.append("cpocontactname", checkCpoContactName);
form_data.append("cpotitle", '<?php echo $quotetitle; ?>');
var checkDynamicValues = '';
var checkDynamicValue1 = '';
var checkDynamicValue2 = '';
var checkmakename1 = '';
var checkmakename2 = '';
if(checkHowManyInstallments != 'undefined' && checkHowManyInstallments != '' && checkHowManyInstallments != 0){
for(var makingi = 1; makingi <= checkHowManyInstallments; makingi++){
checkDynamicValue1 = $('#cpo-adddate-' + makingi).val();
checkDynamicValue2 = $('#cpo-addprice-' + makingi).val();
form_data.append('cposadddate' + makingi, checkDynamicValue1);
form_data.append('cposaddvalue' + makingi, checkDynamicValue2);
}
}
$.ajax({
url: '/Applications/Controllers/Quotes/ajax-add-sin.php',
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with file_data
type: 'post',
success: function(data) {
$('body').html(data);
}
});
});
So from this script I get all the fields from within the form, including some dynamic ones.
The reason why I am doing it like this instead of the easier way of:
$("#formname").on('submit',function(){
$.ajax({
url: "xxxxxxxxxx/xxxxx/xxxx/xxxx.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
}
});
});
Is because for some reason it will not find the posted information no matter what I tried, so the only way I could do it is to find each id and get the value from it.
Now the issue is, uploading a file, you can not simply upload a file this way because nothing is posted.
How would I go about uploading a file if not posting a form?
Thanks
The reason why it was not posting the file is simply because I did not give it a file to post...
18 hours straight of work has not agreed with me here.
Basically I need to add the following code
var checkCpoFiles = $("#addcpofile").prop("files")[0];
form_data.append("cpofile", checkCpoFiles);
Now all works
:)
Please go through this page Ajax Upload image
Here's sample code, it might help
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>
<form enctype="multipart/form-data" action="uploadfile.php" method="POST" id="imageUploadForm">
<input type="file" name="upload" />
<input type="submit"/>
</form>
</body>
<script>
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
});
</script>
uploadfile.php
<?php
if(move_uploaded_file($_FILES['upload']['tmp_name'],$_FILES['upload']['name'])) {
echo "File uploaded successfully";
} else {
echo "Unable to upload the file";
}
?>
Hope it helps! All the best!

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

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.

Passing an image file is unsuccessful using AJAX [duplicate]

This question already has answers here:
Sending multipart/formdata with jQuery.ajax
(13 answers)
Closed 7 years ago.
I am facing an error where I am unable to pass the image file through AJAX when uploading a image file. Here are my codes
AJAX
var file = $("#thumbnail").get(0).files[0];
alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file", file);
alert (formdata);
$.ajax({
url: "php/post-check.php",
type: "POST",
data: {
title: title,
thumbnail: formdata
},
success: function (data) {
$("div#postresult").removeClass("alert alert-danger");
$("div#postresult").html(data);
}
});
PHP
<?php
$target_dir = "../thumbnail-pictures/";
$target_file = $target_dir . basename($_FILES["thumbnail"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (file_exists($target_file)) {
echo "Sorry, thumbnail file already exists. <br>";
$uploadOk = 0;
}
if ($_FILES["thumbnail"]["size"] > 1000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded, ";
} else {
if (move_uploaded_file($_FILES["thumbnail"]["tmp_name"], $target_file)) {
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
HTML
<form action="" method="post" enctype="multipart/form-data" id="newpost">
<div class="col-lg-12">
<div class="form-group">
<label>Title</label>
<input class="form-control" name="title" id="title" required>
</div>
<div class="form-group">
<label>Video Thumbnail **Only JPEG & PNG is accepted**</label>
<input type="file" name="thumbnail" id="thumbnail" accept="image/png, image/gif, image/jpeg" >
</div>
The PHP code itself is working fine so I assume that the problem lies within the AJAX section, however I am unsure of how to solve this. Thankful for any help given!
the problem should be on the parameter processData, please add the parameter processData: false,
to your ajax request and try to get your image on the php.
$.ajax({
url: formURL,
type: form.attr('method'),
dataType: 'json',
data: formData,//form.serialize(),
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
beforeSend: function(){},
success: function(data, textStatus, jqXHR) {},
error: function(jqXHR, textStatus, errorThrown)
{
alert(jqXHR+ textStatus+ errorThrown);
},
complete: function(){}
});
hope helps.good luck
Place your inputs properly in one form and use FormData() to send the form as a whole. I would suggest something like this :
<form method="post" enctype="multipart/formdata" id="myForm">
<input type="text" name="title" />
<input type="file" name="thumbnail" />
</form>
Build and send the data with js :
var form = document.getElementById('myForm');
var formData = new FormData(form);
alert (formdata);
$.ajax({
url: "php/post-check.php",
type: "POST",
data: formData,
success: function (data) {
$("div#postresult").removeClass("alert alert-danger");
$("div#postresult").html(data);
}
});
Now you can get the data in php like this way :
$title = $_POST['title'];
$thumb = $_FILES['thumbnail'];
$tmp_file_path = $thumb['tmp_name'];
You could just post the entire form in async using ajaxForm() like this:
$("#newpost").ajaxForm({
success: function(data) {
$("div#postresult").removeClass("alert alert-danger");
$("div#postresult").html(data);
},
error: function(a, textStatus, exception) {
}
});
AjaxForm is not part of core JQuery but you can find the source here and the documentation here

post binary code not working from Jquery ajax

I made this code to make image upload function but the variable is not getting posted by ajax please help me !!
Jquery()
<script type="text/JavaScript">
$(document).ready(function() {
$("#btn").click(function() {
$.get("i.png", function(response) {
var img = response;
});
$.ajax({
type: "POST",
url: 'lol.php',
data: {r: img},
success: function(data){
$("#ol").html(data)
}
});
return false;
});
});
</script>
PHP Code
<?php
$conn = mysqli_connect("localhost","root","","image");
$r = $_POST['r'];
echo $r;
?>
If you only want to make an image upload (and not exactly match "binary upload")
I suggest you to use the proper functional and native input type file.
In a html form, put an :
<input type="file" id="upload">
<img src="blank.png" title="upload-preview">
and in you javascript:
this will load the preview thumbnail selected
fileInput.addEventListener("change", function(event)
{
var file = $("#upload")[0].files[0];
$(".upload-preview").attr('src', window.URL.createObjectURL(file));
});
and when you click the button, that will send the image
with a "multipart/form-data" Content-Type
$("#btn").on("click", function()
{
var inputs = new FormData();
inputs.append("upload", $("#upload")[0].files[0]);
$.ajax
({
url:"your.php",
type:"POST",
data: inputs,
cache: false, // don't cache the image
processData: false, // Don't process the files
contentType: false,
success: function(response)
{
// next instructions
}
});
});

How do I add additional POST parameters to ajax file upload?

I'm using ajax file upload javascript and php script to upload an image. It works satisfactorily with $_FILES but I need to send some additional data to the processing script. The form HTML looks like:
<form id="image1" action="" method="post" enctype="multipart/form-data">
<label>image 1?</label>
<p><input type="file" class="saveImage" name="image1" value="<?php echo $something; ?>" id="<?php echo $id; ?>" additional_info="some data" /></p>
<p> <input type="submit" value="Upload" class="submit" /></p>
</form>
I need to be able to pass a variable id and some other data, call it "additional_data" to the php script, then process it in my php script using $additional_data = $_POST['additional_data']. The javascript I'm using is:
<script>
$(document).ready(function (e) {
$("#image1").on('submit',(function(e) {
e.preventDefault();
$("#message").empty();
$('#loading').show();
var DATA=$(this).val();
var ID=$(this).attr('id');
var ADDL=$(this).attr('additional_data');
var dataString = 'image1='+DATA+'&id='+ID+'&additional_info='+ADDL;
$.ajax({
url: "uploadFile.php",
type: "POST",
// data: new FormData(this),
data: new FormData(this,dataString),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$('#loading').hide();
$("#message").html(data);
}
});
}));
});
</script>
It doesn't send the dataString, only the FILES array.
I also wanted to do the same thing.
Here's my solution :
The JS part :
var file_data = this.files[0];
file_data.name = idaviz +'.pdf';
var form_data = new FormData();
form_data.append("file", file_data);
form_data.append('extraParam','value231');
console.log(file_data);
console.log('here');
var oReq = new XMLHttpRequest();
oReq.open("POST", "ajax_page.php", true);
oReq.onload = function (oEvent) {
if (oReq.status === 200) {
console.log('upload succes',oReq.responseText);
} else {
console.log("Error " + oReq.status + " occurred when trying to upload your file.<br \/>");
}
};
oReq.send(form_data);
});
The PHP part:
echo $_REQUEST['extraParam']; //this will display "value231"
var_dump($_FILES['file']); //this will display the file object
Hope it helps.
Addition info about extra parameters on formData can be found
here!
I hope I understand you right. Maybe this snippet helps you:
var formData = new FormData();
formData.append("image1", fileInputElement.files[0]);
formData.append("ID", ID);
formData.append("ADDL", ADDL);
And then set this formData variable as data:
type: "POST",
data: formData,
contentType: false,

Categories

Resources