I'm trying to upload a file in an iFrame, so far everything seems to work fine, but I can't process the image in the PHP end as it doesn't seem to receive it...
It does seem to upload though as my progress bar does work and show progress and completes. The responseText says: No image selected?
Here is my aJax:
function submitFile() {
//The file location
var theFile = document.getElementById("image").files[0];
var xhr = new XMLHttpRequest();
//Disable submit button whilst upload is active
doc("submit").disabled = true;
//Completed
xhr.onload = function(e) {
if (this.status == 200) {
document.getElementById("imageUpload").innerHTML = xhr.responseText;
doc("submit").disabled = false; //Unlock submit button
}
};
//Progress
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var currentPercentage = Math.round(e.loaded / e.total * 100);
document.getElementById("imageUpload").innerHTML = "UPLOAD IMAGE " + currentPercentage + "%";
document.getElementById("imageUpload").style.backgroundSize = currentPercentage + "% 100%";
}
};
//Send data
xhr.open("POST", "php/uploadImage.php", true);
xhr.send(theFile);
}
This is the form where I am submitting the image from, it uploads when I select the file however and not when I click submit see the onchange function.
<form action="php/submitMessage.php" onsubmit="validation(this)" method="post" id="submitMessage" enctype="multipart/form-data">
<div class="left half">
<input class="text" type="text" name="name" placeholder="First and Second Name"
rules="[A-Za-z]*\s[A-Za-z]*" />
<input class="text" type="text" name="email" placeholder="Email Address"
rules="^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$" />
<textarea name="message" placeholder="Enter your message here..." rows="5"></textarea>
</div>
<div class="right half">
<input class="text" type="text" name="reg" placeholder="Car Registration"/>
<input type="file" onchange="submitFile();" name="image" id="image" style="display:none;" />
<input type="hidden" name="image_location" id="image_location"/>
<label for="image" id="imageUpload" class="uploadBtn">Upload Image</label>
<p>Message will be regarded as a quote request if you provide an image.</p>
</div>
<input type="submit" id="submit" style="background-color:#fff;color:#000;" value="Submit Message/Quote" />
</form>
This is my PHP, I want to receive the file, resize it, and then set a session variable to its location which will be used when the rest of the form is submitted as the file location will need to be added to the database row.
<?php
session_start();
//Image was selected
if($_FILES['image']['tmp_name']) {
//any errors?
if(!$_FILES['image']['error']) {
//validate the file and setup future filename
$new_file = date("Ymdhisa");
//Can't be larger than 5MB
if ($_FILES['image']['size'] > 5000000) {
//Resize the file
$width = 500;
//Keep aspect ratio
$size = getimagesize($_FILES['image']['tmp_name']);
$height = round($width*$size[1]/$size[0]);
//Create object
if ($size[2] == 1) {
$images_orig = imagecreatefromgif($_FILES['image']['tmp_name']);
} else if ($size[2] == 2) {
$images_orig = imagecreatefromjpeg($_FILES['image']['tmp_name']);
} else if ($size[2] == 3) {
$images_orig = imagecreatefrompng($_FILES['image']['tmp_name']);
}
//Get image size to create object
$photoX = imagesx($images_orig);
$photoY = imagesy($images_orig);
//Create resized object
$images_fin = imagecreatetruecolor($width, $height);
imagecopyresampled($images_fin,$images_orig,0,0,0,0,$width+1,$height+1,$photoX,$photoY); //Resize the image
imagejpeg($images_fin,"images/".$new_images); //Save image to file
//Remove image from memory
imagedestroy($images_orig);
imagedestroy($images_fin);
//Set session key for file location
$_SESSION['tmp_image'] = "uploads/".$new_file; //Should be unset when message has been sent
$message = "File successfully uploaded!";
echo $message;
}
}
else
{
$message = "There was an error: ".$_FILES['image']['error'];
echo $message;
}
} else {
echo "No image selected?";
}
?>
This is my code and its work fine too me , Hope work for you too
function submitVisualMedia()
{
$(document).ready(function (e) {
var fd = new FormData($("#fileinfo")[0]);
$.ajax({
url:, //YOUR DESTINATION PAGE
type: "POST",
data: fd,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function ()
{
//some code if you want
}
});
});
return false;
}
<form method="post" id="fileinfo" onsubmit='return submitVisualMedia()' >
<input class="form-control" type="text" id="title" >
<input class="form-control" type="file" name="visualMedia" id="visualMedia" accept="image/*">
<button class="btn btn-success" type="submit">Upload</button>
</form>
and php side
public function uploadVisualMedia() {
ini_set('upload_max_filesize', '25M');
ini_set('post_max_size', '25M');
ini_set('max_input_time', 300);
ini_set('max_execution_time', 300);
$fname = date('l-j-m-Y').'-'.rand(1,1000000);
$size = $_FILES['visualMedia']['size'];
$ftype = $_FILES['visualMedia']['type'];
$temp = $_FILES['visualMedia']['tmp_name'];
$type = array();
$type = explode("/", $ftype);
$filename = "galleries/" . $type[0] . "_gallery/" . $fname . "." . $type[1];
$index = 0;
while (file_exists($filename)) {
$filename = "galleries/" . $type[0] . "_gallery/" . $fname . "($index)" . "." . $type[1];
$index++;
}
move_uploaded_file($temp, $filename);
}
You most change little in this code and it should work for you fine . with this you can upload video an audio too.
change $filename to some folder name you want..
Related
i am trying to make a system in which a user can choose a pic from his gallery and then apply a blur filter on it and then he can upload that pic to database now i am having success in applying filter to the pic but i cant upload that filtered pic in database when i see the uploaded pic it is normal not blured i am not sure whats going wrong in it
this is my code
<?php
$query = "SELECT * FROM users WHERE email='$email'or username = '$email'";
$fire = mysqli_query($con,$query) or die("can not fetch data from database ".mysqli_error($con));
if (mysqli_num_rows($fire)>0) {
$row = mysqli_fetch_assoc($fire);
$id = $row['id'];
$username = $row['fullname'];
$avatarpath = $row['avatar_path'];
if (isset($_POST['uploadpic'])) {
$avatar = $_FILES['avatar'];
$avatar_name = $_FILES['avatar']['name'];
$avatar_tmpname = $_FILES['avatar']['tmp_name'];
$avatar_size = $_FILES['avatar']['size'];
$avatar_type = $_FILES['avatar']['type'];
$avatar_ext = pathinfo($avatar_name, PATHINFO_EXTENSION);
if (!empty($avatar_name)) {
if ($avatar_size <= 25000000) {
if ($avatar_ext == "jpg" || $avatar_ext == "jpeg" ||$avatar_ext == "png" ) {
$chars= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$rand_dir_name=substr(str_shuffle($chars),0,15);
mkdir("userdata/user_photos/$rand_dir_name");
$final_file= "userdata/user_photos/$rand_dir_name/$avatar_name";
$upload = move_uploaded_file($avatar_tmpname, $final_file);
if ($upload) {
$msg = "file uploaded successfully ";
$query = "INSERT INTO photos(id,uid,image_url,email,date_posted,username,avatar_path) VALUES ('','$id','userdata/user_photos/$rand_dir_name/$avatar_name','$email',NOW(),'$username','$avatarpath')";
$fire = mysqli_query($con,$query) or die("can not insert file path into database".mysqli_error($con));
if ($fire) {
$msg .=" and also inserted into database";
header("Location:profile.php");
}
# code...
}else{ echo "only jpg,jpeg,png, type format allowed";}
}else{echo "file size is too large";}
}else{echo "please select an image to upload";}
}
}
}
?>
<center>
<form action="profile.php" method="POST" enctype="multipart/form-data">
<input type="file" onchange="previewImage(event)" id="file-feild" class="form-control" name="avatar" >
<button type="submit" name="uploadpic" > <a class="upload" href="profile.php"><i class="fas fa-upload"></i></a></button>
</form>
<div class="card">
<img src="img_avatar.png" alt="Avatar"id="image-field" style="width:100%">
<div class="container">
<input type="button" id="blur" name="button" value="button" data-filter="blur">
<input type="button" id="none" name="button" value="button" data-filter="blur">
</div>
</div>
</center>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).on('click','#blur',function(e){
$('#image-field').css({'filter':'blur(20px)'})
});
</script>
<script type="text/javascript">
$(document).on('click','#none',function(e){
$('#image-field').css({'filter':'blur(0px)'})
});
</script>
<script type="text/javascript">
function previewImage(event) {
var reader = new FileReader();
var imageField = document.getElementById("image-field")
reader.onload = function(){
if(reader.readyState == 2){
imageField.src = reader.result;
}
}
reader.readAsDataURL(event.target.files[0]);
}
</script>
any kind of help would be appreciated thanx
CSS blur is a client side manipulation, while you are looking for a server side manipulation (you want to save the manipulated image on the server). In other words, CSS requires the NON blurred image to stored on the server and sent to the browser, while you want the blurred image to be stored on the server. Therefore, you must forget about CSS. The blur manipulation should be done in a server side language, like PHP, using GD or ImageMagick.
Here is a post on blurring in PHP.
I have a website using the Kohana framework. I have a problem when I tried upload multiple image using AJAX. I tried with many methods but without success. I think the problem is in function _save_images($image) at line:
if ($file = Upload::save($image, NULL, $directory))
Because I tried echo this values but receive result like:
Website not support width less than 900px on Computer
A function to save image with parameter $image is array list image.
In ProductImage.php:
protected function _save_images($image)
{
$directory = DOCROOT.'uploads/';
if ($file = Upload::save($image, NULL, $directory))
{
$filename = strtolower(Text::random('alnum', 20)).'.jpg';
Image::factory($file)
->resize(200, 200, Image::AUTO)
->save($directory.$filename);
// Delete the temporary file
unlink($file);
return $filename;
}
}
And I have a function to upload multiple image.
public function action_create()
{
$user = Auth_Jelly::instance()->get_user();
$iduser = $user->id;
if($user->has_role('admin') || $user->check_permission($iduser,'CREATE_PRODUCT')==1){
$this->auto_render = false;
if(Request::$is_ajax)
{
$name_img = Security::xss_clean($_POST['name_img']);
$type_img = Security::xss_clean($_POST['type_img']);
$size_img = Security::xss_clean($_POST['size_img']);
$new_array = array();
foreach($name_img as $item){
$new_array['name'][] = $item;
}
foreach($type_img as $item){
$new_array['type'][] = $item;
}
foreach($size_img as $item){
$new_array['size'][] = $item;
}
$files = $new_array;
unset($new_array);
$ilosc = count($files['name'])-1;
for($i=0; $i<=$ilosc; $i++) {
$_FILES['image_list'.$i]['name'] = $files['name'][$i];
$_FILES['image_list'.$i]['type'] = $files['type'][$i];
$_FILES['image_list'.$i]['size'] = $files['size'][$i];
$array_new[] = array(
'name'=>$_FILES['image_list'.$i]['name'],
'type'=>$_FILES['image_list'.$i]['type'],
'error'=>0,
'size'=>$_FILES['image_list'.$i]['size'],
);
}
foreach ($array_new as $key => $value) {
$this->_save_images($value);
if($this->save_images($value)==FALSE){
echo "Faild Upload";
}else{
echo "Upload Success";
}
}
}
}else{
// Request::current()->redirect('admin/home/denied');
}
}
And in ProductImage.js:
$("#"+form).click(function(){
var image_list = Array();
var imageFiles = document.getElementById("image_list"),
filesLength = imageFiles.files.length;
for (var i = 0; i < filesLength; i++) {
image_list[i] = imageFiles.files[i].name;
}
var myFileList = document.getElementById('image_list').files;
var file ;
var name_img= Array();
var type_img= Array();
var size_img= Array();
// loop through files
for (var i = 0; i < myFileList.length; i++) {
// get item
file = myFileList.item(i);
//or
file = myFileList[i];
name_img[i]= file.name;
type_img[i]= file.type;
size_img[i]= file.size;
}
var local = window.location;
var val_content = tinyMCE.editors[0].getContent();
var language = $.trim($('#product-create-language option:selected').val());
var category = $.trim($('input[name=category]').val());
var status = $.trim($('input[name=createstatus]:checked').val());
var position = $.trim($('input[name=createposition]:checked').val());
var matches = [];
$(".addcheck:checked").each(function() {
matches.push(this.value);
});
if(matches.length>0)
matches=matches;
else
matches=null;
if(validateSpace(title,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",titleinfo) && validateSpace(image,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",imageinfo) && validateSpace(imagebig,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",imagebiginfo) && validateSpace(imagemobile,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",imagemobileinfo) && validateSpace(keywords,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",keywordsinfo) && validateSpace(description,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",descriptioninfo) && validateSpace(date,"<img src='"+base_url+"themes/admin/images/false.png' alt='false'>",dateinfo)){
var data = {name_img:name_img,type_img:type_img,size_img:size_img,category:category,mycolor: matches,language:language,title:$("#"+title).val(),image:$("#"+image).val(),imagebig:$("#"+imagebig).val(),imagemobile:$("#"+imagemobile).val(),fileupload:$("#"+fileupload).val(),price:$("#"+price).val(),pricesale:$("#"+pricesale).val(),idproduct:$("#"+idproduct).val(),color:$("#"+color).val(),packing:$("#"+packing).val(),cbmpsc:$("#"+cbmpsc).val(),size:$("#"+size).val(),container:$("#"+container).val(),excerpt:$("#"+excerpt).val(),content:val_content,keywords:$("#"+keywords).val(),description:$("#"+description).val(),date:$("#"+date).val(),status:status,position:position};
$(".product-content-create-total").fadeOut(); // hidden div content field register // children div of div class //register-form-center\\
$(".product-content-create").css("height","auto"); // set height/auto after hidden div class //register-form-center\\
$(".product-content-create-alert").html(""); // remove text div alert register // parent div of div id //register-form-content\\
$(".product-content-create-alert").css("margin-bottom","25px");
$(".product-content-create-alert").fadeIn("slow");
$(".product-content-create-alert").html('<img src="'+base_url+'themes/admin/images/loader.gif" alt="loader">');
$.ajax({
url: admin_url +"product/create",
type: "POST",
data: data,
cache: false,
success: function(html) {
console.log(html);
}
});
}else{
return false;
}
});
});
That seem many code, so, I hope anyone can be help me.
Updated:
Here my code of form include submit button:
<form enctype="multipart/form-data" name="form-product-create" method="post">
<input type="file" id="image_list" name="image_list[]" multiple>
<input type="button" name="btnproductcreateclick" value=" " id="btn-product-create-click" style="margin-left:119px;" class="form-btn-create-click" />
</form>
HTML
<form enctype="multipart/form-data" action="upload.php" method="post">
<input name="file[]" type="file" />
<button class="add_more">Add More Files</button>
<input type="button" value="Upload File" id="upload"/>
</form>
Javascript
$(document).ready(function(){
$('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file'/>");
});
});
PHP
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br />";
}
}
Ajax
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
alert("Data Uploaded: "+data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
})
Source : How to upload multiple files using PHP, jQuery and AJAX
In your code error looks like near,
foreach ($array_new as $key => $value) {
$this->_save_images($value);
if($this->save_images($value)==FALSE){
echo "Faild Upload";
}else{
echo "Upload Success";
}
}
when you call $this->_save_images($value); you don't save file name for uploaded image. $file_name = $this->_save_images($value); and than save this $file_name,
foreach ($array_new as $key => $value) {
$file_name= $this->_save_images($value);
if($this->save_images($file_name)==FALSE){
echo "Faild Upload";
}else{
echo "Upload Success";
}
}
HTML form must be have the “method” attribute with the “post” value. Because the file will only send to the server when the value of the method attribute of the form is post.
<form method="post" name="multiple_upload_form" id="multiple_upload_form" enctype="multipart/form-data" action="upload.php">
<input type="hidden" name="image_form_submit" value="1"/>
<label>Choose Image</label>
<input type="file" name="images[]" id="images" multiple >
<div class="uploading none">
<label> </label>
<img src="uploading.gif"/>
</div>
</form>
PHP
Demo
I have a modal that submit some information and an image through form to database. I am working with php and javascript...well i am not so good with js so i need some help.
Work i have done so far is that i can insert data from form to db without no errors but i don't know how to start and what to do with image upload. I am working now on localhost.
I want to upload image to local folder and to automatically rename it with title that someone entered through form. So the name of image saves into table and the image in folder.
I will past the code here so if anyone can help me with code i will appreciate it.
ajax:
$(document).ready(function(){
$('form.insert-movie').on('submit', function(e) {
e.preventDefault();
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: 'POST',
data: data,
success: function (msg) {
alert("YOUR SUCCESS MESSAGE HERE");
},
error: function (msg) {
alert("Error " + msg.d.toString());
}
});
return false;
});
});
queries:
<?php
include 'config.php';
$pdo = connect();
if(isset($_POST['InputTitle'], $_POST['InputYear'], $_POST['InputDuration'], $_POST['InputDescription'], $_POST['InputGender'])) {
$InputTitle = $_POST['InputTitle'];
$InputYear = $_POST['InputYear'];
$InputDuration = $_POST['InputDuration'];
$InputDescription = $_POST['InputDescription'];
$InputGender = $_POST['InputGender'];
$InputImage = $_POST['InputImage'];
$sql = $pdo->prepare("INSERT INTO filmovi(naslov,godina,trajanje,opis,id_zanr,slika)
VALUES(:field1,:field2,:field3,:field4,:field5,:field6)");
$sql->execute(array(':field1' => $InputTitle,
':field2' => $InputYear,
':field3' => $InputDuration,
':field4' => $InputDescription,
':field5' => $InputGender,
':field6' => $InputImage));
$affected_rows = $sql->rowCount();
}
modal:
<form action="inc/queries.php" method="post" class="insert-movie" enctype="multipart/form-data">
<div class="form-group"> <!-- TITLE -->
<label for="title">Title</label>
<input type="text" class="form-control" name="InputTitle" id="InputTitle" placeholder="Enter title" required>
</div>
<div class="form-group"> <!-- YEAR -->
<label for="year">Year</label>
<input type="date" class="form-control" name="InputYear" id="InputYear" placeholder="Year" required>
</div>
<div class="form-group"> <!-- DURATION -->
<label for="year">Duration</label>
<input type="time" class="form-control" name="InputDuration" id="InputDuration" placeholder="Duration" required>
</div>
<div class="form-group"> <!-- GENDER -->
<label for="year">Gender</label></br>
<select name="InputGender">
<option>select a genre</option>
<?php
$pdo = connect();
// display the list of all members in table view
$sql = "SELECT * FROM zanr";
$query = $pdo->prepare($sql);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
?>
echo'
<option name="InputGender" value="<?php echo $rs['id'] ?>"><?php echo $rs['naziv'] ?> </option>'
<?php } ?>
echo'
</select>
</div>
<div class="form-group"> <!-- DESCRIPTION -->
<label for="year">Description</label>
<textarea class="form-control" name="InputDescription" placeholder="Description" rows="3" required></textarea>
</div>
<div class="form-group"> <!-- IMAGE -->
<label for="image">Image upload</label>
<input type="file" name="InputImage" id="InputImage">
<p class="help-block">Select image of movie.</p>
</div>
Close
First, you must handle the file upload. Examples here: http://php.net/manual/en/features.file-upload.post-method.php Second you need to figure out what you want to store in your Database.
<?php
include 'config.php';
$pdo = connect();
if(isset($_POST['InputTitle'], $_POST['InputYear'], $_POST['InputDuration'], $_POST['InputDescription'], $_POST['InputGender'])) {
$InputTitle = $_POST['InputTitle'];
$InputYear = $_POST['InputYear'];
$InputDuration = $_POST['InputDuration'];
$InputDescription = $_POST['InputDescription'];
$InputGender = $_POST['InputGender'];
$uploaddir = '/var/www/uploads/'; // Change this to be a path on your server
$uploadfile = $uploaddir . basename($_FILES['InputImage']['name']);
if (move_uploaded_file($_FILES['InputImage']['tmp_name'], $uploadfile)) {
$InputImageStorePath = $uploadfile;
$InputImage = $_FILES['InputImage']['name'];
} else {
$InputImage = "";
}
$sql = $pdo->prepare("INSERT INTO filmovi(naslov,godina,trajanje,opis,id_zanr,slika)
VALUES(:field1,:field2,:field3,:field4,:field5,:field6)");
$sql->execute(array(':field1' => $InputTitle,
':field2' => $InputYear,
':field3' => $InputDuration,
':field4' => $InputDescription,
':field5' => $InputGender,
':field6' => $InputImage));
$affected_rows = $sql->rowCount();
}
?>
I would advise using FormData for your AJAX:
$('form.insert-movie').on('submit', function(e) {
e.preventDefault();
var formData = new FormData($('form.insert-movie')),
url = $(this).attr('action'),
method = $(this).attr('method');
$.ajax({
url: url,
type: 'POST',
data: formData,
success: function (msg) {
alert("YOUR SUCCESS MESSAGE HERE");
// Close Modal here with .hide() ?
},
error: function (msg) {
alert("Error " + msg.d.toString());
}
});
});
When I upload image and text by separate form, its work well. But Its not work when I add together.
My form text upload by js and image upload by a php file.
And I think my problem in my form.
If I upload together with js, What change in my js and submit.php, which also add below.
Here is my form code that not work together
<form action="" method="post" id="cmntfrm" enctype="multipart/form-data">
<fieldset id="cmntfs">
<legend class="pyct">
What's your mind
</legend>
<input type="hidden" name="username" size="22" tabindex="1" id="author" value="'.$pname.'"/>
<input type="hidden" name="email" size="22" tabindex="2" id="email" value="'.$email.'"/>
<p><textarea name="comment" rows="10" tabindex="4" id="comment"></textarea></p>
<div id="ajaxuploadfrm">
<form action="uploadpostimg.php" method="post" enctype="multipart/form-data">
<b>Select an image (Maximum 1mb)</b>
<input type="file" name="url" id="url" />
</form>
</div>
<p><input type="submit" name="submit" value="Post comment" tabindex="5" id="submit"/></span></p>
</fieldset>
<input type="hidden" name="parent_id" id="parent_id" value="0" />
<input type="hidden" name="tutid2" id="tutid" value="'.$tutid2.'" />
</form>
js
$(document).ready(function(){
var inputAuthor = $("#author");
var inputComment = $("#comment");
var inputEmail = $("#email");
var inputUrl = $("#url");
var inputTutid = $("#tutid");
var inputparent_id = $("#parent_id");
var commentList = $(".content > comment");
var commentCountList = $("#updatecommentNum");
var error = $("#error");
error.fadeOut();
function updateCommentbox(){
var tutid = inputTutid.attr("value");
//just for the fade effect
commentList.hide();
//send the post to submit.php
$.ajax({
type: "POST", url: "submit.php", data: "action=update&tutid="+ tutid,
complete: function(data){
commentList.prepend(data.responseText);
commentList.fadeIn(2000);
}
});
}
function updateCommentnum(){
var tutid = inputTutid.attr("value");
//just for the fade effect
commentList.hide();
//send the post to submit.php
$.ajax({
type: "POST", url: "submit.php", data: "action=updatenum&tutid="+ tutid,
complete: function(data){
commentCountList.html(data.responseText);
commentList.fadeIn(2000);
}
});
}
function error_message(){
error.fadeIn();
}
function checkForm(){
if(inputAuthor.attr("value") && inputComment.attr("value") && inputEmail.attr("value"))
return true;
else
return false;
}
//on submit event
$("#cmntfrm").submit(function(){
error.fadeOut();
if(checkForm()){
var author = inputAuthor.attr("value");
var url = inputUrl.attr("value");
var email = inputEmail.attr("value");
var comment = inputComment.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");
//we deactivate submit button while sending
$("#submit").attr({ disabled:true, value:"Sending..." });
$("#submit").blur();
//send the post to submit.php
$.ajax({
type: "POST", url: "submit.php", data: "action=insert&author="+ author + "&url="+ url + "&email="+ email + "&comment="+ comment + "&parent_id="+ parent_id + "&tutid="+ tutid,
complete: function(data){
error.fadeOut();
commentList.prepend(data.responseText);
updateCommentbox();
updateCommentnum();
//reactivate the send button
$("#submit").attr({ disabled:false, value:"Submit Comment!" });
$( '#cmntfrm' ).each(function(){
this.reset();
});
}
});
}
else //alert("Please fill all fields!");
error_message();
//we prevent the refresh of the page after submitting the form
return false;
});
});
Submit.php
<?php header('Content-Type: charset=utf-8'); ?>
<?php
include("db.php");
include_once("include/session.php");
switch($_POST['action']){
case "update":
echo updateComment($_POST['tutid']);
break;
case "updatenum":
echo updateNumComment($_POST['tutid']);
break;
case "insert":
date_default_timezone_set('Asia/Dhaka');
echo insertComment($_POST['author'], $_POST['comment'], $_FILES['url']['name'], $_POST['email'], $_POST['tutid'], $_POST['parent_id'], $date = date("M j, y; g:i a"));
break;
}
function updateNumComment($tutid) {
//Detail here
}
function updateComment($tutid) {
//Detail here
}
function insertComment($username, $description, $url, $email, $qazi_id, $parent_id, $date ){
global $dbh;
//Upload image script that not work here when i try together so i took it at separate file and then tried with above form
$output_dir = "comimage/";
$allowedExts = array("jpg", "jpeg", "gif", "png","JPG");
$extension = #end(explode(".", $_FILES["url"]["name"]));
if(isset($_FILES["url"]["name"]))
{
//Filter the file types , if you want.
if ((($_FILES["url"]["type"] == "image/gif")
|| ($_FILES["url"]["type"] == "image/jpeg")
|| ($_FILES["url"]["type"] == "image/JPG")
|| ($_FILES["url"]["type"] == "image/png")
|| ($_FILES["url"]["type"] == "image/pjpeg"))
&& ($_FILES["url"]["size"] < 504800)
&& in_array($extension, $allowedExts))
{
if ($_FILES["url"]["error"] > 0)
{
echo "Return Code: " . $_FILES["url"]["error"] . "<br>";
}
if (file_exists($output_dir. $_FILES["url"]["name"]))
{
unlink($output_dir. $_FILES["url"]["name"]);
}
else
{
$pic=$_FILES["url"]["name"];
$conv=explode(".",$pic);
$ext=$conv['1'];
$user = $_SESSION['username'];
//move the uploaded file to uploads folder;
move_uploaded_file($_FILES["url"] ["tmp_name"],$output_dir.$user.".".$ext);
$pic=$output_dir.$user.".".$ext;
$u_imgurl=$user.".".$ext;
}
}
else{echo '<strong>Warning !</strong> File not Uploaded, Check image' ;}
}
//Submit main comment
if ($parent_id == 0){
$username = mysqli_real_escape_string($dbh,$username);
$description = mysqli_real_escape_string($dbh,$description);
$sub = "Comment to";
$query = "INSERT INTO comments_lite VALUES('','$qazi_id','0','$username','$email','$description','','$parent_id','$date')";
mysqli_query($dbh,$query);
} else {
if ($parent_id >= 1){
global $dbh;
$username = mysqli_real_escape_string($dbh,$username);
$description = mysqli_real_escape_string($dbh,$description);
$sub2 = "Reply to";
$query = "INSERT INTO comments_reply VALUES('','$qazi_id','0','$username','$email','$description','','$parent_id','$date')";
mysqli_query($dbh,$query);
}
}
}
?>
on click of submit you can put the code in js you have to make change in the js file
$.post('phpapgename.php',data:jquerydata,function(){
})
in the .php page you can put your query to submit your data.
You cannot have nested form. Try to avoid it and separate out the forms as below. And while submitting any form if you data from other form, create a hidden fields in this form and submit it.
Another suggestion: Since you're working with javascript anyway, outsource the upload-form to an invisible div and make it pop up by clicking/hovering an upload-button or entering the last field of form1 or whatever.
I have an alert box that keeps prompting "Image uploaded", even though $imagename is empty.
Here's the script:
<script>
function ajax_post1(ca){
var cat = ca;
var name = document.getElementById("name").value;
var desc = document.getElementById("description").value;
var key = document.getElementById("keyword").value;
var image = document.getElementById("image").value;
if ($.isEmptyObject(image)) {
alert('pls upload your image')
} else {
alert(' image uploaded ')
}
var myData = 'content_ca='+ cat + '&content_desc='+desc+ '&content_key='+key+ '&content_name='+name;//build a post data structure
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "uploadsignuppackageresponse.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response){
//$("#imagebox").append(response);
//$("#contentText").val(''); //empty text field on successful
//alert("haha");
}, error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
};
</script>
This is the main page:
<?php
$sql1 = mysql_query ("SELECT * FROM dumimage WHERE email = '$user_signup' AND cat='company' ");
$row = mysql_fetch_array($sql1);
$imagename = $row['name'];
?>
Name:
<input id="name" type="text" ></input>
<input id="image" type="hidden" value="<?php echo $imagename ?> "></input>
Description
<textarea id="description" rows="7" cols="42"></textarea>
Keywords:
<input id="keyword" type="text" placeholder="3 Maximum Keywords" ></input>
<input type="submit" value="Upload" class="pre" style="float:left; onClick="ajax_post1('company')">
Try this to see if your objects empty
if (image.length < 1) {
alert('pls upload your image')
} else {
alert(' image uploaded ')
}
Try to replace this line:
if ($.isEmptyObject(image)) {
With this one:
if (image != '') {
You also have to correct your php code because you have closed the bracket in the wrong place and you are missing a semicolon:
<input id="image" type="hidden" value="<?php echo $imagename;?>"></input>