javascript file reader not working in chrome - javascript

I am using following code to upload and preview image using js, when i select the image from computer , it previews the image properly , but when i try to upload the image again and click 'cancel', it removes the previously selected image , but in firefox it does not. , what might be issue with chrome?
function readURL(input) {
jQuery("#image_view1").hide();
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
jQuery("#image_view").html("<img id='image_view' src='"+ e.target.result+"' alt='your image' style='width: 240px; height: 130px; '/></br>");
};
reader.readAsDataURL(input.files[0]);
}
}
Html :
<form action="" method="post" id="frmGallery" enctype="multipart/form-data" class="mediaSliderForm">
<div class="control-group clearfix"><h2>Add Image</h2></div>
<div class="control-group clearfix"><label>Title : </label><input type="text" name="title" class="required"></div>
<div class="control-group clearfix"><label>Category : </label>
<select class="required testimonialCategory" name="category">
<option value="">Select Category</option>
<?php foreach($categories as $category){
echo $cat_id == $category->term_id ? '<option value="'.$category->term_id.'" selected="true">'.$category->name.'</option>' : '<option value="'.$category->term_id.'">'.$category->name.'</option>';
}?>
</select>
</div>
<div class="control-group clearfix"><label>Image: </label> <input type="file" name="image" id="image" class="required" onchange="readURL(this);"></div>
<div class="control-group clearfix"><label> </label><div id="image_view" class="advImg"></div></div>
<input type="submit" class="btn btn-small btn-inverse" name="submit" value="Submit">
</form>

Related

Javascript Running 2 script toghether

I am new to Javascript, I am trying to run these 2 script toghether but one is canceling the other
I have a form and I would like to compute 2 tasks as soon as the user load the picture through the input file.
loading the the new picture in the thunbail
write the new picture path to the input text
Any tips to solve the issue will be appreciated. thank you
<form action="../handlers/processUpdatedProduct.php" method="post" enctype="multipart/form-data">
<div class="mb-3">
<input type="hidden" class="form-control" id="id" name="id" value="<?php echo $product->getId() ?>">
</div>
<div class="mb-3">
<label for="productname" class="form-label">Product Name</label>
<input type="text" class="form-control" id="productname" name="productname" value="<?php echo $product->getProductName() ?>">
</div>
<div class="mb-3">
<label for="description" class="form-label">Description</label>
<input type="text" class="form-control" id="description" name="description" value="<?php echo $product->getDescription() ?>">
</div>
<div class="mb-3">
<label for="listprice" class="form-label">Price</label>
<input type="text" class="form-control" id="listprice" name="listprice" value="<?php echo $product->getListPrice() ?>">
</div>
<div class="mb-3">
<label for="listprice" class="form-label">Picture path</label>
<input type="text" class="form-control" id="picturename" name="picturepath" value="<?php echo $product->getPhotoPath() ?>">
</div>
<div class="mb-3">
<label for="pricelist" class="form-label"> Picture </label><br>
<input type='file' id='thefile' name='fileToUpload' onchange="loadFile(event)">
<div id="rolehelp" class="form-text">Max 500 mb - (.jpg .jpeg .gif .png)</div>
</div>
<img src="../../product_images/<?php echo $product->getPhotoPath() ?>" class="img-thumbnail" alt="..." style="width:150px" id="output" />
<script>
var loadFile = function(event) {
var reader = new FileReader();
reader.onload = function() {
var output = document.getElementById('output');
output.src = reader.result;
};
reader.readAsDataURL(event.target.files[0]);
};
var filename;
document.getElementById('thefile').onchange = function() {
filename = this.value.split(String.fromCharCode(92));
document.getElementById("picturename").value = filename[filename.length - 1];
};
</script>

I can't add second image. first image input Only work

Why i cant access second file chooser. first file chooser work well.
This is HTML part
<form action="<?php url("image/uploadImg"); ?>" method="post" enctype="multipart/form-data">
<div class="imgLine">
<div class="line">
<img id="previewImg" src="<?php echo BURL.'assets/img/addImg.svg'; ?>" alt="Placeholder">
</div>
<div class="line">
<!-- <input type="file" name="file" onchange="previewFile(this);" required> -->
<label class="addFile"> Select File
<input type="file" name="file" size="60" onchange="previewFile(this);" required>
</label>
</div>
<div class="line">
<input class="submitBtn" type="submit" name="submit" value="Save">
</div>
</div>
</form>
<form action="<?php url("image/uploadImg"); ?>" method="post" enctype="multipart/form-data">
<div class="imgLine">
<div class="line">
<img id="previewImg" src="<?php echo BURL.'assets/img/addImg.svg'; ?>" alt="Placeholder">
</div>
<div class="line">
<!-- <input type="file" name="file" onchange="previewFile(this);" required> -->
<label class="addFile"> Select File
<input type="file" name="file" size="60" onchange="previewFile(this);" required>
</label>
</div>
<div class="line">
<input class="submitBtn" type="submit" name="submit" value="Save">
</div>
</div>
This is jquery part
<script>
function previewFile(input){
//console.log(input);
var file = $("input[type=file]").get(0).files[0];
//console.log(file);
if(file){
var reader = new FileReader();
reader.onload = function(){
$("#previewImg").attr("src", reader.result);
}
reader.readAsDataURL(file);
}
}
What I am getting is upon uploading the second file. The function call. parameter values also pass. but
var file = $("input[type=file]").get(0).files[0] this file varible does not create.Please help
Just change
<img id="previewImg"
To some classes in both form
<img class="previewImg"
Probably it's require changes in javascript code.
Change a way how you create a function. Do not run javascript function inside html code, remove it
onchange="previewFile(this);"
instead of this catch the action i.e
function previewFile() {
$('.previewImg').on('change', function() {
// use $(this) to catch clicked element only
... your code goes here
});
}
I will find some result. It works well. THankz who helps me
function previewFile(input) {
console.log(input);
var file = input.files[0];
console.log(file);
if(file){
var reader = new FileReader();
reader.onload = function(){
$(input).closest('.imgLine').find('#previewImg').attr("src", reader.result);
}
reader.readAsDataURL(file);
}
}

Ajax image preview before upload and form validation in codeigniter

I want to preview image in placeholder before uploading a image and form validation using ajax in codeigniter
what i have done is shown in the below code first i wrote image preview code in javascript then ajax to submit the form details and getting the response from the controller and showing in the view
view->
<?php echo form_open_multipart('items/itemsave', array('id' => 'uploadForm')) ?>
<?php if (!empty($msg)): ?>
<div class="alert <?php echo $msg_class ?>" role="alert">
<?php echo $msg; ?>
</div>
<?php endif; ?>
<div class="form-group text-center" style="position: relative;" >
<span class="img-div">
<div class="text-center img-placeholder" onClick="triggerClick()">
<h4>Update image</h4>
</div>
<img src="../uploads/2.png" name="profileDisplay" onClick="triggerClick()" id="profileDisplay" style="width: 200px; height: 200px">
</span>
<input type="file" name="profileImage" onChange="displayImage(this)" id="profileImage" class="form-control" style="display: none;">
<label>Profile Image</label>
</div>
<div class="form-group">
<input type="text" name="name" id="name" class="form-control" placeholder="Name" >
</div>
<div class="form-group">
<input type="text" name="location" id="location" class="form-control" placeholder="Location" >
</div>
<div class="form-group">
<input type="text" name="buyingprice" id="buyingprice" class="form-control" placeholder="Buying price" >
</div>
<div class="form-group">
<input type="text" name="sellingprice" id="sellingprice" class="form-control" placeholder="Selling Price" >
</div>
<div class="form-group">
<input type="text" name="category" id="category" class="form-control" placeholder="Category" >
</div>
<div class="form-group">
<input type="text" name="code" id="code" class="form-control" placeholder="Code" >
</div>
<div class="form-group">
<input type="text" name="description" id="description" class="form-control" placeholder="Description" >
</div>
<div class="form-group">
<button type="submit" name="save_profile" class="btn btn-primary btn-block">Save User</button>
</div>
<?php echo form_close() ?>```
javascript->
```<script type="text/javascript">
$(function() {
$("#uploadForm").on('submit', function(e) {
e.preventDefault();
//e.stopPropagation();
var contactForm = $(this);
$.ajax({
url: contactForm.attr('action'),
type: 'post',
data: contactForm.serialize(),
success: function(response){
console.log(response);
if(response.status == 'success') {
$("#uploadForm").show();
}
$("#message").html(response.message);
}
});
});
});
</script>
<script type="text/javascript">
function triggerClick(e) {
document.querySelector('#profileImage').click();
}
function displayImage(e) {
if (e.files[0]) {
var reader = new FileReader();
reader.onload = function(e){
document.querySelector('#profileDisplay').setAttribute('src', e.target.result);
}
reader.readAsDataURL(e.files[0]);
}
}
</script>
controller->
public function itemsave(){
$this->form_validation->set_rules('name','Name','required');
$this->form_validation->set_rules('location','Location','required');
$this->form_validation->set_rules('buyingprice','buyingprice','required');
$this->form_validation->set_rules('sellingprice','sellingprice','required');
$this->form_validation->set_rules('category','category','required');
$this->form_validation->set_rules('code','code','required');
$this->form_validation->set_rules('description','description','required');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = 2048;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if($this->form_validation->run()==true && $this->upload->do_upload('profileImage'))
{
$response = array(
'status' => 'success',
'message' => "<h3>Category Added successfully.</h3>"
);
}
else
{
if ( ! $this->upload->do_upload('profileImage')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('itemsadd', $error);
}
$response = array(
'status' => 'error',
'message' => validation_errors()
);
}
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
}
}

Not able to fetch value for Update Data from database using jQuery Ajax Bootstrap Model - json data

My main problem is that my modal is showing but alert is showing [object Object]. I have four tables like stud,country_master_academic, master_city and master_state.When i click on edit, modal appears but data fetched from database is not showing in it.
jQuery in home.php page
$(document).ready(function(){
$(document).on('click', '.edit_data', function(event){
var stud_no = $(this).attr("id");
$.ajax({
url:"update.php",
method:"POST",
data:{stud_no:stud_no},
dataType:"json",
success:function(data){
console.log(data);
$('#name').val(data.name);
$('#mob_no').val(data.mob_no);
$('#dob').val(data.dob);
$('#add').val(data.add);
$('#photo').val(data.photo);
$('#gender').val(data.gender);
$('#country').val(data.country);
$('#state').val(data.state);
$('#city').val(data.city);
$('#stud_no').val(data.stud_no);
$('#update_data_modal').modal('show');
},
});
});
});
Modal for update in home.php page
<div class="container">
<div class="modal fade" id="update_data_modal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-heading" style="margin-top:30px;text-align:center">
<button class="close" data-dismiss="modal" style="margin-right:20px;font-weight:bold;">x</button>
<h4 class="modal-title"><span class="glyphicon glyphicon-edit"></span>Update Student</h4>
</div>
<div class="modal-body">
<?php
$img = "images/".trim($vrow["photo"]);
echo '<img src='.$img.' class="image" style="margin-left:75%;margin-top:5%;width:120px;height:120px;border:2px solid #bbbbbb;border-radius:10px;">';
?>
<br/>
<input type="file" name="photo" style="margin-left:70%;">
<div class="form-group">
<form class="form-horizontal" name="form" id="form" method="post" action="<?php $_PHP_SELF?>" enctype="multipart/form-data">
<label for="name" id="name"><span class="glyphicon glyphicon-user"></span><b> Student Name: </b></label>
<input type="text" class="form-control" name="name" id="name" pattern="[a-zA-Z]{3,}" title="Name should only contain letters and atleast 3 letters" required />
</div>
<div class="form-group">
<label for="no"><span class="glyphicon glyphicon-phone"></span><b> Mobile No: </b></label>
<input type="text" class="form-control" name="mob_no" id="mob_no" pattern="[0-9]{10}" title="Mobile number should be of 10 digits" required />
</div>
<div class="form-group">
<label for="dob"><span class="glyphicon glyphicon-calendar"></span><b> Birth Date: </b></label>
<input type="date" class="form-control" name="dob" id="dob" required />
</div>
<div class="form-group">
<label for="add"><span class="glyphicon glyphicon-map-marker"></span><b> Address: </b></label>
<textarea rows="4" cols="33" class="form-control" name="add" id="add" required></textarea>
</div>
<div class="form-group">
<label for="photo"><span class="glyphicon glyphicon-camera"></span><b> Photo: </b></label>
<input type="file" name="photo" id="photo" required />
</div>
<div class="form-group">
<label for="gen"><b> Gender: </b></label>
<input type="radio" name="gender" id="gender" value="M" required="required">Male
<input type="radio" name="gender" id="gender" value="F" required="required">Female
</div>
<div class="form-group">
<label for="cntry"><span class="glyphicon glyphicon-map-marker"></span><b> Country: </b></label>
<select name="country" id="country" class="form-control">
<option value="0">Select</option>
<?php
$country="SELECT * from country_master_academic";
$res= $conn->query($country);
if($res->num_rows>0){
while($row=$res->fetch_assoc()){
if($row["country_name"]==$vcountry or $vrow['country'] == $row["country_code"] )
{
echo '<option value='.$row["country_code"].' selected>'.$row["country_name"].'</option>';
}
else
{
echo '<option value='.$row["country_code"].'>'.$row["country_name"].'</option>';
}
}
}
?>
</select>
</div>
<div class="form-group">
<label for="state"><span class="glyphicon glyphicon-map-marker"></span><b> State: </b></label>
<select name="state" id="state" class="form-control">
<option value="0">Select</option>
<?php
$state="SELECT * from master_state";
$res= $conn->query($state);
if($res->num_rows>0){
while($row=$res->fetch_assoc()){
if($row["state_name"]==$vstate or $vrow['state'] == $row["state_code"] )
{
echo '<option value='.$row["state_code"].' selected>'.$row["state_name"].'</option>';
}
else
{
echo '<option value='.$row["state_code"].'>'.$row["state_name"].'</option>';
}
}
}
?>
</select>
</div>
<div class="form-group">
<label for="city"><span class="glyphicon glyphicon-map-marker"></span><b> City: </b></label>
<select name="city" id="city" class="form-control">
<option value="0">Select</option>
<?php
$city="SELECT * from master_city";
$res= $conn->query($city);
if($res->num_rows>0){
while($row=$res->fetch_assoc()){
if($row["city_name"]==$vcity or $vrow['city'] == $row["city_code"] )
{
echo '<option value='.$row["city_code"].' selected>'.$row["city_name"].'</option>';
}
else
{
echo '<option value='.$row["city_code"].'>'.$row["city_name"].'</option>';
}
}
}
?>
</select>
</div>
<div class="form-group">
<input type="hidden" name="stud_no" id="stud_no" />
<button type="submit" name="update" id="update" class="btn btn-info">Update</button>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-danger" type="button" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
update.php page but still i am trying to fetch data, so only wrote code for selecting records from database.
My edit button which is kept in a loop
echo '<td><button name="edit" style="font-weight:bold;" type="submit" id='.$row["stud_no"].' class="btn btn-warning edit_data" data-target="#update_data_modal" data-toggle="modal"><span class="glyphicon glyphicon-edit"></span> Edit</button></td>';
Change in your html as below.
<div class="form-group">
<label for="gen"><b> Gender: </b></label>
<input type="radio" name="gender" id="genderMale" value="M" required="required">Male
<input type="radio" name="gender" id="genderFemale" value="F" required="required">Female
</div>
Add this code in your ajax success.
if(data[6] == 'M')
{
$("#genderMale").prop("checked", true);
} else if(data[6] == 'F') {
$("#genderFemale").prop("checked", true);
}
For image file you can use as below in your html
<div class="form-group">
<img id="resultedPhoto">
<label for="photo"><span class="glyphicon glyphicon-camera"></span><b> Photo: </b></label>
<input type="file" name="photo" id="photo" required />
</div>
Add below code in ajax success
$("#resultedPhoto").attr("src","/path-to-your-folder/" + data[5]);
As shown in the snapshot, your object has numeric indexes hence data.photo will not return anything as there is no index photo in your object.
You can access image name by using data[5].
Similarly you can get any index value.
Like for name instead of using data.name you need to use data[1]
So your code would be something like this:
$('#name').val(data[1]);
$('#mob_no').val(data[2]);
$('#dob').val(data[3]);
$('#add').val(data[4]);
$('#photo').val(data[5]);
Also you have given same ids for labels and inputs:
<label for="name" id="name">
You need to remove id from all labels:
<label for="name">
Now when i click on edit Modal is not opening and database value is getting empty
another jquery
$(document).ready(function(){
$("#form1").submit(function(event){
event.preventDefault();
var formData = new FormData(this);
$.ajax({
url:"upresult.php",
type:"POST",
data:{formData:formData},
async:false,
success:function(data) {
alert(data);
location.reload();
},
cache:false,
contentType:false,
processData:false
});
});
});
upresult.php
<?php
include("connection.php");
if(!empty($_POST)){
$no=$_POST['stud_no'];
$name=trim($_POST['name']);
$mob=trim($_POST['mob_no']);
$dob=trim($_POST['dob']);
$add=trim($_POST['add']);
$photo=trim($_FILES['photo']['name']);
$gen=trim($_POST['gender']);
$cn=trim($_POST['country']);
$st=trim($_POST['state']);
$ct=trim($_POST['city']);
$qry="update stud set stud_name='$name',mobile='$mob',dob='$dob',address='$add',gender='$gen',country='$cn',state='$st',city='$ct' where stud_no='$no'";
$data=mysqli_query($conn,$qry);
if($data)
{
echo '<script language="javascript">';
echo 'alert("Updated Successfully")';
echo '</script>';
}
else {
echo '<script language="javascript">';
echo 'alert("Cannot update record")';
echo '</script>';
}
if(!empty($_FILES['photo']['name'])){
$qry1= "update stud set photo='$photo' where stud_no='$no'";
$data1=mysqli_query($conn,$qry1);
if($data1){
$target_dir="images/";
$target_file=$target_dir.basename($_FILES["photo"]["name"]);
$imageFileType=pathinfo($target_file,PATHINFO_EXTENSION);
if(move_uploaded_file($_FILES["photo"]["tmp_name"],$target_file)){
echo '<script language="javascript">';
echo 'alert("Image upload successfully")';
echo '</script>';
} else {
echo '<script language="javascript">';
echo 'alert("Cannot Upload")';
echo '</script>';
}
}
}
}

Dynamically add dropdown and dropdown fields

EDIT 001:
added:
- event.preventDefault(); and anchors instead of buttons
<div class="edit-area">
<div class="controls">
+
-
</div>
</div>
Now the page +or -won't make the page send the form, but now it does nothing :s
I'm working on a contact form, but I have a few problems/questions.
I want to dynamically add fields when they press a button (+)
And off course they need to be able to delete this when needed... (-)
When I press the + button now, it tries to act like a submit button and sends the form...
Script
<script>
(function($) {
"use strict";
var itemTemplate = $('.example-template').detach(),
editArea = $('.edit-area'),
itemNumber = 1;
$(document).on('click', '.edit-area .add', function(event) {
var item = itemTemplate.clone();
item.find('[project]').attr('project', function() {
return $(this).attr('project') + '_' + itemNumber;
});
++itemNumber;
item.appendTo(editArea);
});
$(document).on('click', '.edit-area .rem', function(event) {
editArea.children('.example-template').last().remove();
});
$(document).on('click', '.edit-area .del', function(event) {
var target = $(event.target),
row = target.closest('.example-template');
row.remove();
});
}(jQuery));
</script>
HTML
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="POST" name="contact">
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
Your personal card number
<input type="text" name="card2" id="card" value="<?php echo $_SESSION['username']; ?>" placeholder="Card Number" readonly/>
</div>
<div class="6u 12u(mobilep)">
Your name
<input type="text" name="name2" id="name" value="<?php echo $_SESSION['realName']; ?>" placeholder="Your name" readonly/>
</div>
</div>
<div class="row uniform 50%">
<div class="6u 12u(narrower)">
Order tickets for a project.
</div>
</div>
<div class="example-template">
<div class="row uniform 50%" id="readroot">
<div class="4u 12u(narrower)">
<select name="project" id="ddl" onchange="configureDropDownLists(this,document.getElementById('ddl2'))">
<option disabled selected>Select a project</option>
<option value="Smile">Project Smile</option>
<option value="Sand">Project Sand</option>
<option value="Schmuck">Project Schmuck</option>
</select>
</div>
<div class="4u 12u(narrower)">
<select id="ddl2" name="date">
<option disabled selected>Select a date</option>
</select>
</div>
<div class="2u 12u(narrower)">
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57' name="amount" id="currentamount" value="" placeholder="Amount" />
</div>
</div>
<div class="edit-area">
<div class="controls">
<button class="add">+</button>
<button class="rem">-</button>
</div>
</div>
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
<input type="hidden" id="currentprice" value="10" />
</div>
</div>
<div class="6u 12u(mobilep)">
<input type="hidden" id="nextprice1" value="10" placeholder="" />
</div>
</div>
<div class="row uniform">
<div class="12u">
</div>
</div>
<div class="4u 12u(mobilep)">
Total price.(In EUR)
<input type="text" name="total2" id="total" value="" readonly/>
</div>
<div class="row uniform">
<div class="12u">
<ul class="actions align-center">
<li><input type="submit" name="submit"value="Place Order"/></li>
</ul>
</div>
</div>
</form>
Image of the form (id and name are not shown here)
Change your buttons to anchors:
+
-
And then in your javascript, when clicked, be sure to call preventDefault() to stop it from behaving like a standard link.
$(document).on('click', '.edit-area .rem', function(event) {
event.preventDefault();
editArea.children('.example-template').last().remove();
});
$(document).on('click', '.edit-area .del', function(event) {
event.preventDefault();
var target = $(event.target),
row = target.closest('.example-template');
row.remove();
});
I think alternatively, you can add a type to the button so it doesn't default to a submit type (but don't quote me on that):
<button type="button" class="add">+</button>

Categories

Resources