How can i submit this form like this tutorial? - php

I have seen this tutorial and tried Form submit with ajax without refresh
It was working fine when i had the php code in my index.php. But now when i added the js and copied the php code in reply.php . it's not working.
I am not even sure does the php works in same way with ajax or not .
someone please help me to submit this form in database .
index.php
begin snippet: js hide: false console: true babel: false -->
<div id="comment-box">
<div class="form-group">
<form method="post" id="reply" enctype="multipart/form-data" style="width: 85%;" >
<div class="input-group">
<input type="file" name="image2" class="file" id="imgInp"/>
<span class="input-group-btn">
<button class="browse btn btn-primary input-md" type="button" ><i class="glyphicon glyphicon-picture"></i>I</button>
</span>
<input type="text" placeholder="say something" class="form-control" name="comment"/><br/>
<span class="input-group-btn">
<button class="btn btn-info" >submit</button>
</span>
</div>
<div>
<img id="blah" src="/final/images/blank.jpg" style=" width:7%; float:left; " />
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
// submit form using $.ajax() method
$('#reply').submit(function(e){
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'reply.php',
type: 'POST',
data: $(this).serialize() // it will serialize the form data
})
.done(function(data){
$('#fcomment-box').fadeOut('slow', function(){
$('#comment-box').fadeIn('slow').html(data);
});
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
});
</script>
</div>
and here is php reply.php:
[note: this was working fine when it was in the same index.php. i just copied the whole php code in reply.php]
<?php
// these php variables are from index.php . will this work now like these are included ??
$user =$_SESSION['user_email'];
$get_user = "select * from users where user_email='$user' ";
$run_user = mysqli_query($con,$get_user);
$row = mysqli_fetch_array($run_user);
$user_id2 = $row['id'];
$user_name2 = $row['user_name'];
if( $_POST ){
global $con;
global $user_id2;
$comment = $_POST['comment'];
$post_image2 = $_FILES['image2']['name'];
$image_tmp2 = $_FILES['image2']['tmp_name'];
$fileType = $_FILES["image2"]["type"];
$fileSize = $_FILES["image2"]["size"];
$fileErrorMsg = $_FILES["image2"]["error"]; // 0 for false... and 1 for true
$kaboom = explode(".", $post_image2); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
$post_image2 = preg_replace('#[^a-z.0-9]#i', '', $post_image2);
$post_image2 = time().rand().".".$fileExt;
date_default_timezone_set("America/New_York");
$date = date('Y-m-d H:i:s');
if ( $_FILES['image2']['name']=='') {
$insert =" insert into comments (post_id,user_id,comment,author_name,date) values('$post_slug','$user_id2','$comment','$user_name2','$date' ) ";
$run = mysqli_query($con,$insert);
}
else if($fileSize > 1048576) { // if file size is larger than 5 Megabytes
echo "ERROR: Your file was larger than 1 Megabytes in size.";
// Remove the uploaded file from the PHP temp folder
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
echo "ERROR: An error occured while processing the file. Try again.";
}
else if (preg_match("/.(gif)$/i", $post_image2) ) {
// This condition is only if you wish to allow uploading of specific file types
$post_image2 = 'resized_'.$post_image2 ;
move_uploaded_file($image_tmp2,"images/$post_image2");
$insert =" insert into comments (post_id,post_image,user_id,comment,author_name,date) values('$post_slug','$post_image2','$user_id2','$comment','$user_name2','$date' ) ";
$run = mysqli_query($con,$insert);
}
else{
if (!preg_match("/.(gif|jpg|png)$/i", $post_image2) ) {
// This condition is only if you wish to allow uploading of specific file types
echo "ERROR: Your image was not .gif, .jpg, or .png.";
// Remove the uploaded file from the PHP temp folder
}
else{
move_uploaded_file($image_tmp2,"images/$post_image2");
// ---------- Include Universal Image Resizing Function --------
include_once("2ak_php_img_lib_1.0.php");
$target_file = "images/$post_image2";
$resized_file = "images/resized_$post_image2";
$wmax = 260;
$hmax = 380;
ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
// ----------- End Universal Image Resizing Function -----------
$insert =" insert into comments (post_id,post_image,user_id,comment,author_name,date) values('$post_slug','$post_image2','$user_id2','$comment','$user_name2','$date' ) ";
$run = mysqli_query($con,$insert);
}
}
}
?>

$(document).on("submit", "#reply", function(e){
e.preventDefault();
var fd = new FormData();
var file = $("#imgInp")[0];
fd.append("image2", file.files[0]);
fd.append("comment", $(this).find('input[name="comment"]').val());
$.ajax({
url: 'reply.php',
type: 'POST',
data: fd,
processData: false,
contentType: false,
}).done(function (data){
$('#fcomment-box').fadeOut('slow', function(){
$('#comment-box').fadeIn('slow').html(data);
});
}).fail(function(){
alert('Ajax Submit Failed ...');
});
});

Related

Upload Multiple images using AJAX (formdata), PHP, and Mysql

I have questions about Upload Multiple images using AJAX (formdata), PHP, and save them into Project Folder and Mysql Database.
I have made a sample and so far have not found a definite answer.
Form HTML :
<div class="form-group row">
<div class="col-xs-4">
<input type="file" class="form-control" id="foto">
<input type="file" class="form-control" id="foto">
<input type="file" class="form-control" id="foto">
</div>
</div>
<div class="form-group row">
<div class="col-xs-4">
<button type="button" class="btn btn-primary" onclick="addImages()">Submit</button>
<button type="reset" class="btn btn-warning" onclick="resetForm()">Reset</button>
</div>
</div>
Ajax Function :
function addImages() {
var formData = new FormData();
var foto = $('#foto').val();
if (foto !== '') {
var file = $('#foto').prop('files')[0];
var ext = foto.split('.').pop();
ext = ext.toLocaleString().toLocaleLowerCase();
if (ext !== 'png' && ext !== 'jpg' && ext !== 'jpeg') {
swal("File yang diupload harus png, jpg atau jpeg");
return false;
}
formData.append('file', file);
}
$.ajax({
type: "POST",
url: getUrl() + "/imageupload",
processData: false,
contentType: false,
data: formData,
success: function (response) {
if (jQuery.trim(response) == true) {
swal({title: "Succeed to upload images", type: "success", showCancelButton: false
}, function () {
location.reload();
});
} else {
swal({title: "Failed to upload images. ", type: "error", showCancelButton: false
}, function () {
location.reload();
});
}
}
});
}
MySQL Query:
function insert_image($db = NULL, $data = array()) {
$SQL = "INSERT INTO image_location (file) VALUES ('" . $data['foto'] . "')";
$db->exec($SQL);
$insert_id = $db->lastInsertId();
return ($insert_id ? TRUE : FALSE);
}
FYI
I wrote in 2 different Files. File AJAX functions and HTML Form in one file while the process database is in a separate file that I have created a function like:
foreach (glob('../model/*.php') as $filename) {
include_once $filename; }
Thank's

upload file and save filename failed using jquery ajax modal form

I try to upload file then save filename to mysql the method is same as upload & save file to mysql.
But my problem still happen. error message is uploadedfile is undefined.
HTML :
<form id="flowlist">
<div class="form-group">
<label for="idcar" class="control-label">ID CAR</label>
<input type="text" name="idcar" id="idcar" class="text_field form-control" required>
</div>
<div class="form-group">
<label for="upload">Upload Minute Of Meeting</label>
<input type="hidden" name="MAX_FILE_SIZE" value="20000000">
<input id="upload" name="uploadedfile" type="file">
<input type="hidden" id="filenm" name="filenm" required>
<input type="hidden" name="action" value="updateflow">
</div>
</form>
JS Script (cms.js):
dialog = $( "#flow" ).dialog({
buttons: {
"Update Data":function() {
var params=$('#flowlist').serialize();
$.ajax({
type:"post",
url:"doserver.php",
data:params,
cache :false,
async :false,
success : function() {
$('input').val("");
$('textarea').val("");
table.row('.selected').draw(false);
location.reload();
return this;
},
error : function() {
alert("Data failed to input.");
}
PHP code (doserver.php):
case 'updateflow':
/* catch variable parameter */
$idcar = mysqli_real_escape_string($dbc,$_POST['idcar']);
$file= mysqli_real_escape_string($dbc,$_POST['filenm']);
$target_path = "mom/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
/* UPDATE */
$sql ="UPDATE monitor SET Mom = '".$file."'";
$sql.=" WHERE id_car LIKE '".$idcar."'";
$res =mysqli_query($dbc,$sql) or die(_ERROR30.":".mysqli_error($dbc));
}
else { echo "There was an error uploading the file, please try again!"; }
break;
Edit
add enctype="multipart/form-data"
<form id="flowlist" enctype="multipart/form-data">
</form>
Then make some change to ajax function :
"Update Data":function() {
var formData = new FormData(this);
$.ajax({
type:"post",
url:"doserver.php",
processData:false,
contentType:false,
data:formData,
....
});
I have no error but the idcar wasn't updated and file wasn't uploaded.
if you are using jquery better using $('#flowlist')[0] instead of this. I have solved this using :
"Update Data":function() {
if(window.FormData !== undefined)
{
var formData = new FormData($('#flowlist')[0]);
$.ajax({
type:"post",
url:"doserver.php",
processData:false,
contentType:false,
mimeType:"multipart/form-data",
data:formData,
...
});
}
}

Need fix on stopping page reloading after file uploading

I'm trying to upload files to the server without page refresh. The uploading works but the page reloads after the uploading is done which is not what I wanted. I'm redirecting to an iframe ("myFrame") to stop the page reloading but it appears this doesn't work correctly. What did I do wrong?
HTML
<form id="upload" target="myFrame" action="sql/main-pix-upload.php" method="post" enctype="multipart/form-data">
<input id="main-pix" class="hidden" name="main_pix" type="file" onchange="uploadPix()" accept="image/*"/>
<label class="gi gi-camera mb-0 text-white" for="main-pix" type="button" title="Change Picture"></label>
</form>
<iframe class="hidden" name="myFrame"></iframe>
SCRIPT
function uploadPix(){
var form = document.getElementById('upload');
form.onsubmit = function(e){
e.preventDefault()
var formData = new FormData(this);
$.ajax({
url: 'sql/main-pix-upload.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false
})
});
};
PHP
$account = $_SESSION['account'];
$order = $_SESSION['order'];
$id = $_SESSION['id'];
$pathPix = ('../accounts/'.$account.'/'.$order.'/pix/'.$id.'/');
if(!is_dir($pathPix)){
mkdir($pathPix, 0777, true);
}
$file_name = $_FILES['main_pix']['name'];
$file_size = $_FILES['main_pix']['size'];
$extension = pathinfo($file_name, PATHINFO_EXTENSION);
$new_name = "main-pix.png";
$temp = ($_FILES["main_pix"]["tmp_name"]);
$target_file = ($pathPix.$new_name);
if(0 < $_FILES['main_pix']['error']){
echo 'Error: ' . $_FILES['main_pix']['error'] . '<br>';
}else{
move_uploaded_file($temp, $target_file);
}
Either use:
form.onsubmit = function(e) {
e.preventDefault()
};
or:
form.addEventListener("submit", function(e) {
e.preventDefault();
});
And then you have to make the HTTP-Call by yourself using AJAX.

Uploading file via ajax

i am trying to upload file using ajax.
form enctype="myltipart/form-data" id="pastTest-form" method="POST" action="upload.php">
<div class="feedback-form-inputs col-5">
<div class="input-field">
<select id="type" required>
<option value="quiz">Quiz</option>
<option value="midterm">Midterm</option>
<option value="final">Final</option>
</select>
</div>
<div class="input-field">
<input type="text" id="professor"/>
</div>
<div class="input-field">
<input type="text" id="name"/>
</div>
<div class="input-field">
<input type="file" id="uploaded_file" name="file" accept="" required />
</div>
</div><!-- END feedback-form-inputs -->
<div class="clear"></div>
<input type="submit" value="submit" onclick="submit() />
<div id="upload-status"> </div>
</form>
my function for opening ajax are in the external file.
function addPastTest1(cid){
// form variables
var type = _("type").value;
var professor = _("professor").value;
var name = _("name").value;
var fileSelect = _('uploaded_file');
var status = _('upload-status');
event.preventDefault();
// Update status text.
status.innerHTML = 'Uploading...';
// Get the selected files from the input.
var file = fileSelect.files[0];
var FileName = file.name;
var FileSize = file.size;
var allowed = ["msword", "pdf","pages"];
var found = false;
// check if the extension of the file match the allowed ones
allowed.forEach(function(extension) {
if (file.type.match('application/'+extension)) {
found = true;
}
})
if (FileSize >10204){
status.innerHtml = 'File must be less than 1mb in size';
}
if (found==true){
// Create a new FormData object.
var formData = new FormData();
// Add the file to the request.
formData.append('file', file, FileName);
// Set up the request.
var ajax = ajaxObj("POST", "ajaxResponse.php");
ajax.onreadystatechange = function(){
if (ajaxReturn(ajax)==true){
if (ajax.responseText=='failed'){
status.innerHtml = "failed to upload file";
}
else {
status.innerHtml = 'uploaded';
alert(ajax.responseText);
}
}
}
ajax.send(formData); //ajax.send("f="+formData+"&t="+type+"&p="+professor+"&n="+name+"&cid="+cid+"&fn="+FileName);
}
}
so i am sending formData to the php. but at this point i can not take the file from form data and upload it to the server.
here is my php
// Ajax calls this code to add a past test
if (isset($_FILES['file']){
$file = $_FILES['file'];
$path = 'files/'.$type.'/'.$fileName;
$moveResult = move_uploaded_file($file, $path);
if ($moveResult != true) {
echo "ERROR: File not uploaded. Try again.";
//unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
}
$path = 'files/'.$type.'/'.$fileName;
$sql = "INSERT into past_papers VALUES ('$name', '$type', '$cid', '$professor','$path')";
$query = mysqli_query($db_conx,$sql);
if (mysqli_affected_rows($db_conx)>0){
echo "success";
exit();
}
else {
echo "failed sql";
exit();
}
}
?>
Also i want to grab inputs with the file and process them together. Upload file, and insert inputs into database.
The simplest one I can find. :)
jQuery code
$("#form-id").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "file-to-call.php",
type: "POST",
data: new FormData(this),
cache: false,
processData: false,
success: function(data) {
//handle success
}
});
}));
HTML code
<form name='form1' method='post' enctype='multipart/form-data' id='form-id'>
<input type='submit' id='input' value='Upload' />
</form>

Form does not post data

i have the following html code:
<form class="dropzone" id="msform" enctype="multipart/form-data"> <!-- multistep form -->
<!-- progressbar -->
<ul id="progressbar">
<li class="active">Account Setup</li>
<li>Post an Image</li>
</ul>
<!-- fieldsets -->
<fieldset>
<h2 class="fs-title">Fill in Some General Details</h2>
<h3 class="fs-subtitle">As Simple As This</h3>
<input type="text" name="update" id="title" placeholder="Update Title" />
<textarea name="description" id="description" placeholder="Short Description/Add On"></textarea>
<input type="date" name="expire" id="expire" placeholder="Expire By" value="Expire By" />
<input type="button" name="next" class="next action-button" value="Next" />
</fieldset>
<fieldset>
<h2 class="fs-title">Upload Image</h2>
<h3 class="fs-subtitle">We currently only support images.</h3>
<div class="dropzone-previews dz-message" id="dropzonePreview">
</div>
<input type="button" name="previous" class="previous action-button" value="Previous" />
<input type="submit" name="submit" class="submit action-button" value="Submit"/>
</fieldset>
</form>
</div>
</div>
<script>
Dropzone.options.msform = { // The camelized version of the ID of the form element
// The configuration we've talked about above
url: "filepostupload.php",
autoProcessQueue: false,
autoDiscover: false,
addRemoveLinks: true,
uploadMultiple: false,
parallelUploads: 5,
maxFiles: 5,
paramName: "file",
previewsContainer: '.dropzone-previews',
clickable:'#dropzonePreview', //used for specifying the previews div
//used this but now i cannot click on previews div to showup the file select dialog box
// The setting up of the dropzone
init: function() {
var myDropzone = this;
this.element.querySelector("input[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
if (myDropzone.getQueuedFiles().length === 0) {
var update = $('#title').val();
var description = $('#description').val();
var expiry = $('#expire').val();
var groupid = <?php echo $groupid ?>;
var request = $.ajax({
url: "updatesnofile.php",
type: "POST",
data: { update:update, description:description, expiry:expiry, groupid:groupid},
dataType:"text",
success: function(data) {
if (data=="success") {
alert('success');
} else {
alert(data);
}
},
error: function(request, err){
alert(err);
}
});
}else {
myDropzone.processQueue();
}
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sending", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
});
this.on("success", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
alert(response);
});
this.on("error", function(files, response) {
alert("error");
});
}
}
</script>
And my php script that does the file upload is :
<?php
session_start();
require 'config.php';
//I'm using mysql_ as an example, it should be PDO
$ds = DIRECTORY_SEPARATOR;
$foldername = "updatefiles/";
if (isset($_POST['update']) && isset($_POST['description']) && isset($_POST['expiry']) && isset($_POST['groupid'])){
$title= mysqli_real_escape_string($mysqli,trim($_POST['update']));
$description= mysqli_real_escape_string($mysqli,trim($_POST['description']));
$expire= mysqli_real_escape_string($mysqli,trim($_POST['expiry']));
$groupid= mysqli_real_escape_string($mysqli,trim($_POST['groupid']));
$fileupload = basename($_FILES['file']['name']);
$fileType = $_FILES['file']['type'];
$fileSize = $_FILES['file']['size'];
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $foldername . $ds;
$targetFile = $targetPath. $fileupload;
move_uploaded_file($tempFile,$targetFile);
$fileupload = mysqli_real_escape_string($mysqli,basename($_FILES['file']['name']));
$fileType = mysqli_real_escape_string($mysqli,$_FILES['file']['type']);
$fileSize = mysqli_real_escape_string($mysqli,$_FILES['file']['size']);
mysqli_query($mysqli,"START TRANSACTION;");
$ins = mysqli_query($mysqli,"INSERT INTO posts (category, description, posttitle, userid, expire, group_id) VALUES ('updates','".$description."', '".$title."','{$_SESSION['userid']}', '".$expire."','".$groupid."' )");
if (!$ins) {
// fail
mysqli_query($mysqli,"ROLLBACK");
echo"error with first insert";
return FALSE;
}
$upd = mysqli_query($mysqli,"SET #post_id_in_posts = LAST_INSERT_ID()");
if (!$upd) {
// fail
mysqli_query($mysqli,"ROLLBACK");
echo"error with setting postid";
return FALSE;
}
$del = mysqli_query($mysqli, "INSERT INTO files (post_id,f_name, f_type, f_size) VALUES (#post_id_in_posts,'".$fileupload."', '".$fileType."', '".$fileSize."')");
if (!$del) {
// fail
mysqli_query($mysqli,"ROLLBACK");
echo "Error with Second Insert!";
return FALSE;
}
// All succeeded
mysqli_query($mysqli,"COMMIT");
echo"success";
return TRUE;
}else {
echo"formwasnotsubmitted";
}
?>
However, it keeps telling me that the form was not submitted (which means the posting of the form by drop zone fails, and therefore the data isn't posted over when there are files, the ajax works though when there are NO files), can anyone find out why? thanks!
I have managed to find the mistake, it is something to do with the way Dropzone sends the form data!

Categories