Image upload with ajax and php after submit - javascript

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

Related

Jquery TypeError: data.errors is undefined

I'm currently developing a website for a gaming community but I've stumbled on some issues I can't fix. This is suppose to edit a user inserted in the database.
edituser.php
<form id="edituser" enctype="multipart/form-data">
<div class="col-sm-3">
<div class="form-group">
<img src="../../assets/images/users/<?=$row['users_image']; ?>.<?=$row['users_imagetype']; ?>" class="img-responsive img-circle">
</div>
<div class="form-group">
<input type="file" id="image">
</div>
</div>
<div class="col-sm-9">
<div id="usersidControl" class="form-group">
<label>User ID:</label>
<input id="usersid" class="form-control" value="<?=$row['usersid']; ?>" placeholder="<?=$row['usersid']; ?>" disabled>
</div>
<div id="nameControl" class="form-group">
<label>Name:</label>
<input id="name" class="form-control" value="<?=$row['name']; ?>" placeholder="<?=$row['name']; ?>">
</div>
<div id="usernameControl" class="form-group">
<label>Username:</label>
<input id="username" class="form-control" value="<?=$row['username']; ?>" placeholder="<?=$row['username']; ?>" disabled>
</div>
</div>
</form>
edituser.js
$(document).ready(function() {
$('form#edituser').submit(function(e) {
var edituser = {
'usersid' :$('input#usersid').val(),
'name' :$('input#name').val(),
'image' :$('input#image').attr('files'),
}
$.ajax({
type : 'POST',
url : 'processedituser.php',
data : edituser,
contentType : 'multipart/form-data',
enconde : true
})
.done(function(data) {
$('.form-group').removeClass('has-error');
$('.help-block').remove();
if (!data.success) {
if (data.errors.name) {
// empty name
$('#nameControl').addClass('has-error');
$('#nameControl').append('<div class="help-block">' + data.errors.name + '</div>');
}
if (data.errors.username) {
// empty username
$('#usernameControl').addClass('has-error');
$('#usernameControl').append('<div class="help-block">' + data.errors.username + '</div>');
}
} else if (data.success) {
if ($('#result').hasClass('alert-danger') || $('#result').hasClass('alert-warning') || $('#result').hasClass('alert-success') || $('#result').hasClass('alert-info') ||$('#result').hasClass('hidden')) {
$('#result').removeClass('alert-danger alert-info alert-success alert-warning hidden');
$('#result').addClass('alert-success fade in');
$('#result').html(data.message);
}
}
})
.fail(function(data) {
if ($('#result').hasClass('alert-danger') || $('#result').hasClass('alert-warning') || $('#result').hasClass('alert-success') || $('#result').hasClass('alert-info') ||$('#result').hasClass('hidden')) {
$('#result').removeClass('alert-danger alert-info alert-success alert-warning hidden');
$('#result').addClass('alert-danger fade in');
$('#result').html('An error has ocurred trying to edit this user, please try again in a few moments. If the problem persists, please contact the webmaster.');
}
});
e.preventDefault();
});
});
processedituser.php
include ("config.php");
global $conn;
$errors = array();
$data = array();
$editorid = $_COOKIE['backoffice_usersid'];
$editor = $_COOKIE['backoffice_username'];
$usersid = $_POST['usersid'];
$name = $_POST['name'];
$file = $_POST['image'];
if (empty($name)) {
$errors['name'] = "Please fill in the name.";
}
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder="../../assets/images/users/";
$new_size = $file_size/1024;
$new_file_name = strtolower($file);
$final_file = str_replace(' ','-',$new_file_name);
if (empty($image)) {
$errors['file'] = "Please choose an image to upload";
} else if (!move_uploaded_file($file_loc,$folder.$final_file)) {
$errors['file'] = "Couldn't upload the file, please try again later";
}
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
try {
// Update Users table
$sql_update = "UPDATE users SET .... ";
// Insert log
$sql_insert = "INSERT INTO logs (action, content, type, date, usersid) VALUES ('Edited', 'user $username by $editor', 'pencil-square-o', NOW(), '$editorid')";
$conn->exec($sql_insert);
$data['success'] = true;
$data['message'] = "You have successfully edited this user. You'll be redirected in 5 seconds.";
} catch(PDOException $e) {
$data['success'] = false;
$data['message'] = "Couldn't register you on our database!";
}
}
echo json_encode($data);
Ok, so this is my code, I've been working on this for like 2 months, I have a similar code, but it works with no problem whatsoever.
The real problem is that when I have no errors to trigger the !data.success, it simply gives me TypeError: data.errors is undefined, which I've checked over and over again, not knowing what can possibly be wrong.
The other problem is the file upload seems no to be working properly, it doesn't upload anything to the Db even though the code works outside the back office just like the rest of the code.
Can anyone please help me?

Codeigniter Ajax on insert function with validation

I have this form where i can insert data, on code igniter. it has validations, all i want to do is to make it ajax. how can I put ajax on it?
my codes,
controller
// CREATE /////////////////////////////////////////////////////////
public function create(){
$this->form_validation->set_rules('PROVINCE','Province Name','trim|required|max_length[30]|callback_if_exist');
if($this->form_validation->run($this) == FALSE){
$this->add_view();
}else{
if($query = $this->Provinces_Model->insert()){
redirect('Provinces/index');
}else{
$this->add_view();
}
}
}
/////////// Checking duplicates
public function if_exist(){
$available = $this->Provinces_Model->check_if_exist(); //change
if($available){
return TRUE;
}else{
$this->form_validation->set_message('if_exist','{field} already exist!');
return FALSE;
}
}
models
/// call back
public function check_if_exist(){
$sql = "SELECT * FROM $this->table WHERE PROVINCE = ?";
$data = array('PROVINCE' => $this->input->post('PROVINCE'));
$query = $this->db->query($sql, $data);
if($query->num_rows() == 0){
return TRUE;
}else{
return FALSE;
}
}
///// CREATE /////////////////////////////////////////////////////////
public function insert(){
$input = array(
'PROVINCE' => $this->input->post('PROVINCE')
);
$insert = $this->db->insert($this->table,$input);
return $insert;
}
and finally the view
<div class="box-body">
<div class="form-group">
<label for="PROVINCE" class="col-sm-2 control-label col-sm-offset-2">Province Name:</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="PROVINCE" name="PROVINCE" value = "<?= set_value("PROVINCE"); ?>">
</div>
</div>
<div class="form-group has-error col-sm-offset-7">
<label class="control-label" for="error"><?php echo form_error("PROVINCE"); ?></label>
</div>
</div>
notice that I have the error reporting so and value = "<?= set_value("PROVINCE"); ?>" for retaining the value i inserted if its values did not pass the validation.. now I want to make it ajax as a practice because the next part that I am going to do is after I submitted a form, it will go to another form.
Edit your code like below:
Controller:
public function create(){
$this->form_validation->set_rules('PROVINCE','Province Name','trim|required|max_length[30]|callback_if_exist');
if($this->form_validation->run() == FALSE){
echo 'ERR';
}else{
if($query = $this->Provinces_Model->insert()){
redirect('Provinces/index');
}else{
$this->add_view();
}
}
}
And the view's Javascript part:
<script type="text/javascript" >
$('#send').click(function(){ // you should add an id called "send" to your submit button
var province = $('#province').val();
$.ajax({
type:'POST',
url:'yourposturl',
data: province,
success:function(response){
if (response = 'ERR') {
$("#response").html('Some error text');
}
else {
$("#response").html('Some success text');
}
}
});
});
</script>
Also please change <label class="control-label" for="error"> part to <label class="control-label" id="response" for="error"> if you want to use this method.

Trying to send data with ajax to OOP class

Im trying to send a data containing username, password etc from a HTML form-> ajax -> instance -> oop class file.
But im not sure i have the right approach...
It starts with the form on index.php
<!-- Formular for signing up -->
<form method="post">
<div class="form-group">
<label> Username </label>
<input type="text" class="form-control" name="newusername">
</div>
<div class="form-group">
<label> Password </label>
<input type="password" class="form-control" name="newpassword">
</div>
<div class="form-group">
<label> Your club </label>
<input type="text" class="form-control" name="newclub">
</div>
<input type="button" id="btn-reg" class="btn btn-success" value="Sign up!">
</form>
And then it goes trough my script file and ajax
$(document).ready(function () {
console.log('Script loaded...');
$("#btn-reg").on("click", reg);
// Function for registrate of new users
function reg(newusername, newpassword, newclub) {
$.post('classCalling.php', {
newusername: 'newusername',
newpassword: 'newpassword',
newclub: 'newclub'
});
};
});
And then my data is going to a page, classCalling.php where i instance my class
?php
include("class/userClass.php");
include("class/pagesClass.php");
// Creating instance of the class userClass.php
$user = new User();
// Defining variables
$newusername = $_POST['newusername'];
$newpassword = $_POST['newpassword'];
$newname = $_POST['newclub'];
// Password hash
$hashpassword = sha1($newpassword);
$user->newUsers($newusername, $hashpassword, $newname);
?>
And finaly my OOP Class, but im not getting this far
public function newUsers($newusername, $newpassword, $newclub) {
// Using prepared statement to prevent mysql injections.
$stmt = $this->db->prepare("INSERT INTOusers(username,password, club)VALUES(?, ?, ?);");
$stmt->bind_param("sss", $newusername, $newpassword, $newclub);
if($stmt->execute()) {
echo "<h3 class='usercreated'>Användare skapad</h3>";
} else {
echo "<h3 class='usercreated'> Gick ej att skapa användare</h3>";
}
}
Im getting these errors Notice: Undefined index: newusername in /Applications/MAMP/htdocs/web 2.0/projektet/classCalling.php on line 13
I think the error is because ur not passing any arguments to reg.
Try passing the form values to reg function it ll be fine
problem with your code is that you are not fetching value from form..
You don't need to put the code in form tag.
Use this form and Script, hope it may help.....
<div class="form-group">
<label> Username </label>
<input type="text" class="form-control" name="newusername" id="username">
</div>
<div class="form-group">
<label> Password </label>
<input type="password" class="form-control" name="newpassword" id="password">
</div>
<div class="form-group">
<label> Your club </label>
<input type="text" class="form-control" name="newclub" id="club">
</div>
and script:
$(document).ready(function () {
console.log('Script loaded...');
$("#btn-reg").on("click", reg);
var newusername=$("#newusername").val();
var newpassword=$("#newpassword").val();
var newclub=$("#club").val();
function reg() {
$.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
});
};
});
Try out this
$(document).ready(function () {
console.log('Script loaded...');
$("#btn-reg").click(function(){
var newusername = $("#username").val();
var newpassword = $("#newpassword").val();
var newclub = $("#newclub").val();
$.ajax({
method: "POST",
url: "classCalling.php",
data: { newusername: newusername,newpassword: newpassword,newclub: newclub },
success:function(data){
alert(data);
}
});
});
});
And adjust your newUsers() method into
public function newUsers($newusername, $newpassword, $newclub) {
// Using prepared statement to prevent mysql injections.
$stmt = $this->db->prepare("INSERT INTO users(username,password, club)VALUES(?, ?, ?);");
$stmt->bind_param("sss", $newusername, $newpassword, $newclub);
if($stmt->execute()) {
echo "<h3 class='usercreated'>Användare skapad</h3>";
} else {
echo "<h3 class='usercreated'> Gick ej att skapa användare</h3>";
}
}
Try this function:
function reg() {
var newusername=$(this).val();
var newpassword=$(this).val();
var newclub=$(this).val();
$.post('classCalling.php', {
newusername: newusername,
newpassword: newpassword,
newclub: newclub
},function(data){
console.log(data);
});
}
To avoid error in your classCalling.php file always check if the POST value you are trying to get is set or not.
check below code
<?php
include("class/userClass.php");
include("class/pagesClass.php");
// Creating instance of the class userClass.php
$user = new User();
if(isset($_POST['username']) && isset($_POST['password']) && isset($_POST['newclub'])){
$username = $_POST['username'];
$password = $_POST['password'];
$newclub = $_POST['newclub'];
$hashpassword = sha1($newpassword);
$user->newUsers($newusername, $hashpassword, $newname);
}else{
// handle your request when POST parameters are missing.
}

Upload file in iFrame

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..

Upload image and text by same form

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.

Categories