How to set null image file after ajax success in PHP? - javascript

I am working on ajax and PHP.
When I click on the post button the message value removes by $("#message").val(""); after ajax success (data inserted into the database by PHP and ajax ) but the file(browse ), the image doesn't remove after success. The file should be empty after AJAX success and the ajax code is not run if I leave the image. I want to leave an image and the message should be inserted without an image and with the image is working.
$(document).on("click", "#save", function (e) {
e.preventDefault();
var form_data = new FormData();
form_data.append('message', message)
var property = document.getElementById('photo').files;
property = property[0];
if(property){//you have to check if the files exists or it will fail trying to access properties from an undefined object
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
form_data.append("file",property);
}
//Ajax call to send data to the insert.php
$.ajax({
type: "POST",
url: "insert_posts.php",
data: form_data,
contentType:false,
cache:false,
processData:false,
success: function (data) {
//Insert data before the message wrap div
$(data).insertBefore(".message-wrap:first");
//Clear the textarea message
$("#message").val("");
$("#form")[0].reset();
$('#preview').attr('src', "#");
$("#photo").val("");
}
});
});
The post button doesn't work when I leave the image file.
but when I leave the text blank and select the image from the computer then the post button works.
I want the post button should be work when I leave the browse file.
And After ajax success, the file browse should be empty.
<div class="c-header">
<div class="c-h-inner">
<ul>
<li><input type="file" onchange="readURL(this);" style="display:none;" name="photo" id="photo"></li>
<li><img src="assets/icon/icon1.png"></img>Add Photo</li>
</ul>
</div>
</div>
<div class="c-body">
<div class="body-left">
<div class="img-box">
<img src="<?php echo 'assets/images/'.$image;?>"></img>
</div>
</div>
<div class="body-right">
<textarea class="text-type" name="message" id="message"
placeholder="What's on your mind?"></textarea>
</div>
<div id="body-bottom">
<img src="#" id="preview"/>
</div>
</div>
<div class="c-footer">
<div class="right-box">
<ul>
<li><input type="submit" name="save" id="save" value="Post" class="btn2"/></li>
</ul>
<br>
</div>
I am using js to show image preview.
ew
<script type="text/javascript">
//Image Preview Function
$("#uploadTrigger").click(function(){
$("#photo").click();
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#body-bottom').show();
$('#preview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
The image preview should be clear or remove after ajax success and post button should be work when i leave image to browse .

The file input should reset however you need to remove the preview image like:
var form_data = new FormData();
form_data.append('message', message)
var property = document.getElementById('photo').files;
property = property[0];
if(property){//you have to check if the files exists or it will fail trying to access properties from an undefined object
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
form_data.append("file",property);
}
success: function (data) {
//Insert data before the message wrap div
$(data).insertBefore(".message-wrap:first");
//Clear the textarea message
$("#message").val("");
$("#form")[0].reset();
$('#preview').attr('src', "#");//Reset the preview to the original state
}
If the file input is not resetting try to add $("#photo").val(""); inside the success function.

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 load data to a particular section of the page without refreshing the whole page in php-codeigniter

Sorry if you find this question wrong.
In my website, I have two divs, one div contains the image selected by the user, I have previewed it by Jquery. Then in controller I fetch this image and applied flip operation of Codeigniter, now my question is How to load the second div with flipped image (which will come from controller) without refreshing the whole page?
I have three div's, how to load data in only a particular div without reloading the complete page in php-codeigniter?
I know about this link but here data is coming from database, which is not in my case.
So how to call data in a particular div without loading the whole page?
As I have to upload an image from controller
This is my controller code:
$filedata = $this->upload->data();
$data['img2'] = base_url().'/assets/images/'.$filedata['file_name'];
$this->load->view('pages/flipped',$data);
This is view code:
<div class="invert-grid-item invert">
<label>Upload Image</label>
<input type='file' name="userfile" size="20">
<img id="blah" src="#" alt="" />
</div>
<div class="invert-grid-item invert" id="result"></div>
<button id="uploaded_images" type="submit">Invert</button>
JS code
<script>
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(200)
.height(200); };
reader.readAsDataURL(input.files[0]);
}
}
$('#files').on('click',function(){
var files = $('#files')[0].files;
$.ajax({
url:"<?php echo base_url(); ?>pages/flip",
method:"POST",
success:function(data)
{
$('#uploaded_images').html(data);
$('#result').val('');
}
})
});
</script>
Solved my problem, made an ajax call with JQuery:
$(document).ready(function(){
$('#upload_form').on('submit', function(e){
e.preventDefault();
if($('#userfile').val() == '')
{
alert("Please Select the File");
}
else
{
$.ajax({
url:"<?php echo base_url(); ?>pages/flip",
method:"POST",
data:new FormData(this),
contentType: false,
cache: false,
processData:false,
success:function(data)
{
$('#result').html(data);
}
});
}
});
});
#ClaudiusDan and #saddam thanks for helping!
Edited answer to edited question.
Show the same image with jQuery in another div and look at this question for rotating the second div.
Rotate a div using javascript

get all form data by jquery/js input fields ajax

Meanwhile I'm getting stuck on this issue. Normally, it's pretty simple but somehow it doesn't work for what I'm trying to do. I want to get all data from my form input fields by either Jquery or JS and then send them through AJAX to the server sided script (PHP). Even by using append or do it by serialize, I only obtain the object from input field with ID #file. I'm not using a submit button to confirm the uploaded image - only select the file and send it off.
I already tried too add
formdata.append("_token", document.getElementById('_token').val());
but whenever I try to append another element to the formdata the entire script stops working
By using $('#picUploadForm').serialize(); I do not get the any result from the input element with ID #file.
HTML:
<form enctype="multipart/form-data" id="picUploadForm">
<input type="file" name="file" id="file" style="display:none;" >
<input type="hidden" name="_token" id="_token" value="<?php echo $_SESSION['_token']; ?>" />
</form>
<!-- Default Avatar Image -->
<div class="click-slide overlay">
<!-- Profile Image-->
<img src="<?php if(isset($avatar['filelink']) && $avatar['filelink'] !='') { echo $avatar['filelink']; } else { echo "assets/images/avatars/default_avatar_large.png"; }?>" alt="" class="img-full-width-tight" id="imagePreview" />
<!-- Image update link -->
<div id="editLink" >
<span>
<a href="javascript:void(0);" class="pop-inline ti ti-image" ></a>
</span>
</div>
</div><!--/ click-slide-->
JS:
//On select file to upload
$('#file').on('change', function(e){
e.preventDefault();
var formdata = new FormData();
// any other code here....
} else {
// Upload Image to backend
formdata.append("file", document.getElementById('file').files[0]);
// formdata.append("_token", document.getElementById('_token').val()); // does not work!!!
// $('#picUploadForm').serialize(); // only returns data from input #_token
$.ajax({
url: "./serversided.php",
type: "POST",
data: formdata,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
beforeSend: function(){
$("#statusav").removeClass().html('');
$('.overlay').LoadingOverlay("show");
HideLoadingOverlay();
},
success: function(data){
if(data.status === true){
// alert(data.imgURL);
setTimeout(function(){$("#statusav").removeClass('alert alert-danger').addClass('alert alert-success').html(data.reply)}, 2000);
$("#imagePreview").attr('src', data.imgURL);
} else {
// alert(data.error);
setTimeout(function(){$("#statusav").removeClass('alert alert-success').addClass('alert alert-danger').html(data.error)}, 2000);
}
}
});
}
});
.val() is a jQuery method - it is not a vanilla JS method, so it doesn't work when called on a plain element. document.getElementById will return an element (or null); $('selectors here') will return a jQuery object, on which you can use jQuery functions.
Try this instead, with vanilla JS:
formdata.append("_token", document.querySelector('#_token').value);
Or select the element with jQuery and use the jQuery method:
formdata.append("_token", $('#_token').val());

Upload Image with input file button or drag and drop the file

now I am learning to upload file with HTML5 and JavaScript (JQuery). and I got a problem with it. so, bellow here is the preview of my app.
and from this app, I want to upload file either you choose file from input button or drag and drop the file in the drop zone.
here is the code :
<div class="row">
<div id="blah" class="col-lg-4 dropzone" ondrop="drag_drop(event)" ondragover="return false">
<p>Drop Your Image Here</p>
</div>
<div class="col-lg-3">
<?php echo form_open_multipart('umum/uploadFile', ['id' => 'form_upload']);?>
<div class="form-group">
<label for="userfile">File input</label>
<input type="file" id="userfile" name="userfile">
<p class="help-block">Only image file allowed to upload here.</p>
</div>
<button class="btn btn-primary" onclick="uploadFile()">Upload</button>
<?php echo form_close(); ?>
</div>
</div>
and then my script :
<script>
// preview the file that will be uploaded
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(event) {
$('#blah').html('<img src="'+event.target.result+'" alt="your image">');
}
reader.readAsDataURL(input.files[0]);
}
}
// manual select file from input file button
$("#userfile").change(function(){
readURL(this);
});
// drag and drop file image
$(function() {
$('#blah').bind('dragover', function() {
$(this).addClass('dropzone-active');
});
$('#blah').bind('dragleave', function() {
$(this).removeClass('dropzone-active');
});
});
function drag_drop(event) {
event.preventDefault();
// parsing data to preview the file before upload
readURL(event.dataTransfer);
// alert(event.dataTransfer.files[0]);
// alert(event.dataTransfer.files[0].name);
// alert(event.dataTransfer.files[0].size+" bytes");
}
</script>
and the problem is I cannot change the value of the input file button when I drag and drop the image in the drop zone. and of course, I cannot upload the file because the input file remains empty. Btw, I have tried to write $('#userfile').val(event.dataTransfer.files[0]); in drag_drop function up there and the result in my console is :
Uncaught DOMException: Failed to set the 'value' property on
'HTMLInputElement': This input element accepts a filename, which may
only be programmatically set to the empty string.
NB: Note that There is no cross-browser way to upload dragged & dropped files without Ajax. Also note (and this could be the reason for the limitation) the security implications of trying to assign a value to a file upload input field: if it were possible to programmatically assign values thus, imagine something like:
$("input[type=file]").val("passwords.txt");
So we have to use AJAX. That said, you just have to create a new FormData instance and append to it the dataTransfer.files property from your drop event:
function drag_drop(event) {
event.preventDefault();
$.each(dataTransfer.files, function(i, file) {
uploadData.append( "userfile", file);
});
}
var $form = document.querySelector('form'),
ajaxData = new FormData($form);
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: ajaxData,
dataType: 'json',
cache: false,
contentType: false,
processData: false // Important for file uploads
});
If your reason for preferring manual uploads is to have all your files uploaded alongside your form when submitted, consider creating a hidden input field and setting its value to the location of the uploaded files when AJAX successfully returns.
You might also want to set the multiple attribute in your file input field, given from your code, I see you processing several files.
Full tutorial

Send a hidden ID input field with AJAX

With this AJAX script, I'm trying to send the content of contentText and contentID.
Just sending contentTEXT works, but I want to send the ID as well, so I can comment on the original post.
But it doesn't work!
myData looks like this when it semi works:
> var myData = '?content_txt='+$("#contentText").val(),
> '&content_id='+$("#contentId").val(); //build a post data structure
But i want it to be something like this, i think
<script type="text/javascript"> $(document).ready(function() {
//##### send add record Ajax request to response.php ######### $("#FormSubmit").click(function (e) { e.preventDefault(); if($("#contentText").val()==='') {
alert("Please enter some text!");
return false; }
$("#FormSubmit").hide(); //hide submit button $("#LoadingImage").show(); //show loading image
var myData = '?content_txt='+$("#contentText").val(), '&content_id='+$("#contentId").val(); //build a post data structure
jQuery.ajax({ type: "POST", // HTTP method POST or GET url: "response.php", //Where to make Ajax calls contentType: "application/x-www-form-urlencoded;charset=UTF-8", dataType:"text", // Data type, HTML, json etc. data:myData, //Form variables success:function(response){
$("#responds").append(response);
$("#contentText").val(''); //empty text field on successful
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
}, error:function (xhr, ajaxOptions, thrownError){
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
alert(thrownError); } }); });
//##### Send delete Ajax request to response.php ######### $("body").on("click", "#responds .del_button", function(e) { e.preventDefault(); var clickedID = this.id.split('-'); //Split ID string (Split works as PHP explode) var DbNumberID = clickedID[1]; //and get number from array var myData = 'recordToDelete='+ DbNumberID; //build a post data structure
$('#item_'+DbNumberID).addClass( "sel" ); //change background of this element by adding class $(this).hide(); //hide currently clicked delete button
jQuery.ajax({ type: "POST", // HTTP method POST or GET url: "response.php", //Where to make Ajax calls dataType:"text", // Data type, HTML, json etc. data:myData, //Form variables success:function(response){
//on success, hide element user wants to delete.
$('#item_'+DbNumberID).fadeOut(); }, error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError); } }); });
}); </script>
My form I'm trying to use
<form class="form-horizontal" accept-charset="utf-8">
<fieldset>
<legend><?php echo WORDING_ADD_A_COMMENT; ?></legend>
<!-- Textarea -->
<div class="control-group">
<div class="controls">
<textarea name="content_txt" id="contentText" cols="45" rows="5" placeholder="<?php echo WORDING_COMMENT_PLACEHOLDER; ?>"></textarea>
<input type="hidden" name="content_id" id="contentId" value="<?php echo $_GET['topic_id']; ?>"/>
</div>
</div>
<!-- Button -->
<div class="control-group">
<label class="control-label" for="singlebutton"></label>
<div class="controls">
<button id="FormSubmit" class="btn btn-primary"><?php echo WORDING_BUTTON_COMMENT_BOX; ?></button>
<img src="images/loading.gif" id="LoadingImage" style="display:none" />
</div>
</div>
</fieldset>
</form>
var variable = {
'content_txt': $("#contentText").val(),
'content_id': $("#contentId").val()
};
try to use
var myData = '?content_txt='+$("#contentText").val()+'&content_id='+$("#contentId").val();
You only use ? and & when you manually build a query string and in that case you would need to encode your values as well.
When you send the data as a parameter, the easiest solution is to generate an object. That will be encoded automatically by jQuery:
//build a post data structure
var myData = { 'content_txt': $("#contentText").val(),
'content_id': $("#contentId").val() };
As you are using a form, you can also serialize the form:
var myData = $('.form-horizontal').serialize();
data:'content_id='+ $("#contentId").val()+ '&content_txt='+ $("#contentText").val() ,

Categories

Resources