I have used dropzone js inside a small form with couple of fields. I want to submit both images and form data all at once to the database. No errors can be seen in the logs and was searching all over the internet for a solution. I'm a newbie to PHP, so a bit of help would much appreciated.
Form
<form action="index.php" method="POST" class="form-horizontal" role="form">
<div class="form-group"></div>
<label for="name">Name :</label>
<input type="text" name="name" id="input-title" class="form-control">
<br><br>
<label for="description">Email:</label>
<input type="text" name="description" id="input-description" class="form-control">
<br><br>
<label for="File">File: </label>
<br><br>
<div class="dropzone dropzone-previews" name="File" id="my-awesome-dropzone"></div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
PHP Query
<?php
if( isset($_POST['submit']) && isset($_POST['name']) && isset($_POST['email']) && !empty($_FILES)){
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'mystore';
//connect with the database
$conn = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if($mysqli->connect_errno){
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$name = $_POST['name'];
$email = $_POST['email'];
$targetDir = "upload/";
$fileName = $_FILES['file']['name'];
$targetFile = $targetDir.$fileName;
if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile)){
//insert file information into db table
$conn->query("INSERT INTO products (product_name,details,category, date_added) VALUES('".$name."','".$email."','".$fileName."','".date("Y-m-d H:i:s")."')");
}
}
else{
$error = "Fill All Details First !!";
if ( isset($_POST['submit']) && isset($error)) { echo $error; }
}
?>
Dropzone JS
<script type="text/javascript">
Dropzone.autoDiscover = false;
jQuery(document).ready(function() {
$("div#my-awesome-dropzone").dropzone({
url: "/file/post"
});
});
</script>
You must use something like this
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("div#my-awesome-dropzone", {
maxFiles: <?php echo $upload_file_number; ?>,
url: "remote/upload-file.php",
addRemoveLinks: true,
autoProcessQueue: false,
init: function() {
this.on("maxfilesexceeded", function(file){
//handle error for max file size
});
var submitButton = document.querySelector("#submit-button");
var id_import_xls;
var myDropzone = this;
submitButton.addEventListener("click", function(e){
/* HERE PUT THE AJAX FOR SUBMIT FORM AFTER SUBMIT UPLOAD THE FILE */
if (myDropzone.getUploadingFiles().length === 0 && myDropzone.getQueuedFiles().length === 0) {
//handle the error for no file selected if needed
}else{
//with this start upload
myDropzone.processQueue();
};
});//fine addEventListener
this.on("error", function(file, response) {
//handle the error
});
this.on("complete", function (file, response) {
//here can handle the success of upload
});
},
success: function(file, response){
//here can handle the success of upload
},
});
Related
Im trying to save the current timestamp of the video being played as soon as I click submit. But in the table only 0 is getting saved and Im unable to fetch & save the current timestamp of video. Although its getting displayed but not getting saved in SQL table.
NOTE : timestamp(tstamp) : Is a dynamic value, which is the timestamp of the video file being played in the browser( for example 1.935771),
fileUpload.php
<body>
<h1>VIDO LABELLING TOOL</h1>
<video id="my_video_1" class="video-js vjs-default-skin" controls preload="auto" width="640" height="268"
data-setup='{ "playbackRates": [0.5, 1, 1.5, 2, 4] }'>
<source src="project.m4v" type='video/mp4'>
<track src='br.srt' kind="subtitles" srclang="en" label="English" default>
</video>
<script>
// Get the audio element with id="my_video_1"
var aud = document.getElementById("my_video_1");
// Assign an ontimeupdate event to the audio element, and execute a function if the current playback position has changed
aud.ontimeupdate = function () {
myFunction()
};
</script>
<div class="container" style="max-width:800px;margin:0 auto;margin-top:50px;">
<form name="contact-form" action="" method="post" id="contact-form">
<label for="email">Comments about the frame</label>
<textarea name="message" class="form-control" id="message"></textarea>
<div class="error" id="error_message"></div>
<label>Vehicle Type:</label>
<input name="veh_type_1" id="veh_type_1" type="checkbox" value="lmv">lmv
<input name="veh_type_2" id="veh_type_2" type="checkbox" value="2w">2w
<p>TimeStamp: <span id="tstamp"></span></p>
</div>
<p class="submit">
<button type="submit" class="btn btn-primary" name="submit" value="Submit" id="submit_form">Submit</button>
</p>
<div class="display-content">
<div class="message-wrap dn"> </div>
</div>
</form>
</div>
<script>
function myFunction() {
document.getElementById("tstamp").innerHTML = aud.currentTime;
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#contact-form").on("submit", function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: "saveFile.php",
data: $(this).serialize(),
success: function () {
alert("form was submitted");
}
});
return false;
});
});
</script>
</body>
and the php file for db update as :-
saveFile.php
<?php
$servername = "localhost";
$database = "stackover";
$username = "root";
$password = "123456";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$tstamp = addslashes($_POST['tstamp']);
$message = addslashes($_POST['message']);
$veh_type_1 = addslashes($_POST['veh_type_1']);
$veh_type_2 = addslashes($_POST['veh_type_2']);
mysqli_query($conn, "insert into saveData(message,tstamp,veh_type_1, veh_type_2) values ('$message','$tstamp','$veh_type_1', '$veh_type_2')");
$sql = mysqli_query($conn, "SELECT message,tstamp,veh_type_1,veh_type_2 id FROM saveData order by id desc");
$result = mysqli_fetch_array($sql);
echo '<div class="message-wrap">' . $result['message'] . '</div>';
?>
Please add this into your form
<input name="tstamp" id="hidden-tstamp" type="hidden">
and inside your script add below code
function myFunction() {
document.getElementById("tstamp").innerHTML = aud.currentTime;
document.getElementById('hidden-tstamp').value = aud.currentTime;
}
I have this form
<form id="home" class="validate-form" method="post" enctype="multipart/form-data">
<!-- Form Item -->
<div class="form-group">
<label>How much money do you need? (Kenya Shillings)</label>
<div class="input-group">
<div class="input-group-addon">Ksh</div>
<input id="moneyAmount" type="number" id="amount" name="amount" class="form-control slider-control input-lg" value="100000" min="10000" max="1000000" data-slider="#moneySlider" required>
</div>
<div id="moneySlider" class="form-slider" data-input="#moneyAmount" data-min="10000" data-max="1000000" data-value="100000"></div>
</div>
<!-- Form Item -->
<div class="form-group">
<label>How long? (months)</label>
<div class="input-group">
<input id="monthNumber" type="number" id="duration" name="duration" class="form-control slider-control input-lg" value="10" min="6" max="12" data-slider="#monthSlider" required>
<div class="input-group-addon">months</div>
</div>
<div id="monthSlider" class="form-slider" data-input="#monthNumber" data-min="6" data-max="12" data-value="10"></div>
</div>
<div class="form-group">
<label>Telephone Number</label>
<!-- Radio -->
<input type="number" id="telephone" name="telephone" class="form-control" required/>
</div>
<!-- Form Item -->
<div class="form-group">
<label>3 Months Bank or Paypal or Mpesa Statements</label>
<!-- Radio -->
<input type="file" name="image" class="ml btn btn-primary btn-lg" /><span>Upload</span>
</div>
<!-- Form Item -->
<div class="form-group">
<label>Monthly repayment</label>
<span id="formResult" class="form-total">Ksh<span>262.99</span></span>
</div>
<div class="form-group form-submit">
<button type="submit" class="btn-submit btn-lg"><span>Send a request!
</span></button>
</div>
</form>
This is the Jquery Script.
$( "#home" ).on( "submit", function( event ) {
event.preventDefault();
alert('subsequent clicks');
function chek(fData) {
var reg = new RegExp("^[-]?[0-9]+[\.]?[0-9]+$");
return reg.test(fData)
}
var phone = $('#telephone').val();
var amount = $('#amount').val();
var duration = $('#duration').val();
var ch = chek(phone);
if(phone == ""){
alert('phone cannot be empty');
return;
}
if(amount == ""){
alert('amount cannot be empty');
return;
}
if(duration == ""){
alert('duration cannot be empty');
return;
}
if(ch == false){
alert("Phone number must be a number");
return;
}
if(phone.length < 10 || phone.length > 12 ){
alert("Phone number must have 10 digits");
return;
}
if(ch == true && phone !== "" && amount !== "" && duration !== "" && phone.length == 10){
var s = phone;
s = s.replace(/^0+/, '');
var cc = 254;
var p = cc+s;
var pn = p.toString();
$('#telephone').val(p.toString());
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://example.com/home.php', //<== just add it to the end of url ***
type: 'POST',
data: formData,
async: true,
success: function (data) {
console.log(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
}
});
This is my PHP code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
function random_str($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyz')
{
$str = '';
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$str .= $keyspace[random_int(0, $max)];
}
return $str;
}
$pass = random_str(4);
/**
Generic Customer Shown Interest
*/
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "algo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Posted Variables
$amount = $_POST['amount'];
$duration = $_POST['duration'];
$telephone = $_POST['telephone'];
$date = date('Y-m-d H:i:s');
//Check If User Exists
$result = $conn->query("select id from users where telephone=$telephone");
if($result->num_rows == 0) {
//Insert New User
$sql = "INSERT INTO users (telephone, password, service_name,date_submitted) VALUES ('$telephone', '$pass', 'loans','$date')";
if ($conn->query($sql) === TRUE) {
echo "User Is Inserted";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
//Insert New User
$sql2 = "INSERT INTO loans (amount, duration, telephone,documents,status,date)
VALUES ('$amount', '$duration','$telephone','logan2','on-hold','$date')";
if ($conn->query($sql2) === TRUE) {
echo "Loan Is Inserted";
} else {
echo "Error: " . $sql2 . "<br>" . $conn->error;
}
$conn->close();
}
?>
As you can tell the form is pretty basic and its only posting data to the server. When I load the page, I am able to insert data into the database but when I click the link again, nothing is inserted.
Is form data blocking me from posting duplicate data to the server?
change ajax part of your code and replace to this code shown below:
<script type="text/javascript">
$.ajax({
type:'POST',
url:'testing2.php',
data:new FormData($('#svf-form-4')[0]),
cache: false,
contentType: false,
processData: false,
success:function(msg){
$('#message').html(msg);
}
});
return false;
</script>
Hope it will work .
I cant explain what really worked but it seems clearing the form did allow for more post submission although i relied on this comment What does "async: false" do in jQuery.ajax()?
and this page What does "async: false" do in jQuery.ajax()? for inspiration.
This is the success callback
success: function (data) {
$("#home").trigger('reset');
console.log(data);
},
I'm trying to save some data into db using AJAX.It says it's successfully done but nothing happens.No data is being saved.Just keeps saying "Success".
index.php // form
<div id="cont">
<div id="kayit" style="display:none;">
Success
</div>
<div id="basarisiz" style="display:none;">
Empty or Fail
</div>
<form method="post" id="yaz" onsubmit="return false">
<input type="text" name="title" id="baslik" placeholder="Başlık" required><br/>
<textarea name="content" ></textarea><br/>
<input type="submit" name="gonder" value="Gönder" id="gonder" onclick="kayit()">
</form>
yaz.js
function kayit()
{
var baslik = $("input[name=title]").val();
var icerik = $("input[name=content]").val();
if (baslik =="" || icerik == "")
{
$('#basarisiz').show(1);
$('#kayit').hide(1);
}else
{
$.ajax ({
type: "POST",
url: "yazikaydet.php",
data: $("#yaz").serialize(),
success: function (sonuc) {
if (sonuc == "hata") {
alert ("unable to connect to db");
}else {
$('#kayit').show(1);
$('#basarisiz').hide(1);
$("input[name=title]").val("");
$("input[name=content]").val("");
}
}
}) }}
yazikaydet.php //the file which will save the data,not processing
<?php
include 'giris.php'; //sessions and connection strings
if(isset($_POST["gonder"]))
{
$baslik = $_POST["title"];
$icerik = $_POST["content"];
$tarih = date("d/m/20y");
$kull = $_SESSION["username"];
$kaydet = mysqli_query($connect,"INSERT INTO gonderiler (yazar,tarih,baslik,icerik) VALUES ('$kull','$tarih','$baslik','$icerik')");
if($kaydet)
{
echo "Yes";
}
else
{
echo "No";
}
}
?>
I had previously mentioned about my registration code. I now want to save the image name into the database.The image is to be uploaded using file upload. The validation is done using jquery and the form has to be submitted using ajax.Now i had read that file uploads cannot be performed using ajax.And that is the problem with my code.
Following is my code:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
function ValidateEmail(email) {
var expr = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)| (([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return expr.test(email);
};
$(document).ready(function(){
$('#submit').on('click', function() {
//e.preventDefault();
valid = true;
if ($('#name').val() == '') {
alert ("please enter your name");
//$('#errorMsg1').css('color','red');
//$('#errorMsg1').html('Please enter your name');
//document.getElementById("errorMsg1").innerHTML = "You must enter a name";
valid = false;
}
if ($('#email').val() == '') {
alert ("please enter your email");
//$('#errorMsg2').css('color','red');
//$('#errorMsg2').html('Please enter your emailid');
//document.getElementById("errorMsg2").innerHTML = "You must enter a email";
valid = false;
}
if (!ValidateEmail($("#email").val())) {
alert("Invalid email address.");
//document.getElementById("errorMsg2").innerHTML = "Invalid email address.";
}
if ($('#bday').val() == '') {
alert ("please enter your birth date");
//$('#errorMsg3').css('color','red');
//$('#errorMsg3').html('Please enter your birth date');
//document.getElementById("errorMsg3").innerHTML = "You must enter your birth-date";
valid = false;
}
if ($('#gender').val() == '') {
alert ("please select your gender");
//$('#errorMsg4').css('color','red');
//$('#errorMsg4').html('Please select your gender');
//document.getElementById("errorMsg4").innerHTML = "You must select your gender";
valid = false;
}
if ($('#image').val() == '') {
alert ("please select an image");
//$('#errorMsg5').css('color','red');
//$('#errorMsg5').html('Please select an image');
//document.getElementById("errorMsg5").innerHTML = "You must select an image";
valid = false;
}
});
return false;
$("#multiform").submit(function (e)
{
var formObj=$(this);
var formURL=formObj.attr("action");
var formData=new formData(this);
$ajax({
URL:formURL,
type:'POST',
data:formData,
mimeType:"multipart/form-data",
contentType:false,
cache:false,
processData:false,
success:function(data,textStatus,jqXHR){
},
error:function(jqXHR,textStatus,errorThrown){
}
});
e.preventDefault();
e.unbind();
}
);
return true;
$("#multiform").submit();
});
</script>
</head>
<body>
<form name="multiform" id="multiform" action="save_data.php" method="POST" enctype="multipart/form-data">
<h4>Name:</h4> <input type="text" name="name" id="name" autofocus>
<br><br>
<h4>E-mail:</h4> <input type="text" name="email" id="email" autofocus>
<br><br>
<h4>Birth-date:</h4> <input type="text" name="bday" id="bday" autofocus>
<br><br>
<h4>Gender:</h4>
<input type="radio" name="gender" id="gender" value="female" autofocus>Female
<input type="radio" name="gender" id="gender" value="male" autofocus>Male
<br><br>
Select Image:<input type="file" name="image" id="image"><br><br>
<input type="submit" id="submit" name="submit" value="Submit">
</form>
</body>
</html>
save_data.php:
<!DOCTYPE html>
<html>
<body>
<?php
error_reporting( E_ALL & ~E_NOTICE );
// define variables and set to empty values
$name = $email = $bday = $gender = $image="";
//$image=$_FILES["image"]["name"];
if(isset($_POST['submit'])){
$name = $_POST["name"];
$email = $_POST["email"];
$bday=$_POST["bday"];
$gender = $_POST["gender"];
$image =$_POST["image"];
$servername = "localhost";
$username = "mvs1";
$password = "";
$dbname="scootsy_categories";
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";
$sql = "INSERT INTO user_details(name,email,bday,gender,image) VALUES ('$name','$email','$bday','$gender','$image')";
if ($conn->query($sql) === TRUE) {
// echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
//if($name !="" || $email !="" || $bday !="" || $gender !="" || $image !="" )
//{
// $sql="DELETE FROM user_details where name='$name' || email='$email' || bday='$bday' || gender='$gender' || image='$image'";
//}
$conn->close();
}
echo "Successful";
?>
</body>
</html>
You can't save images into a database, but you can save the path url and before you save the image into a folder with php. For do this, you have to modify your ajax code and your php file because for do all this, we have to use $_FILES for extract the name, type, size and temp_folder for move it into a filder.
Rewrite your ajax code.
Get with $_FILES the properties of the file
<script type="text/javascript">
$('body').on('click','#submit', function() {
$.ajax({
type:'POST',
url:'save_data.php',
data: new FormData($('#your_id_form')[0]),
contentType:false,
cache:false,
processData:false,
success:function(upload) {
$('#multiform').html(upload):
}
});
});
</script>
<form id="your_id_form" method="POST" action="save_data.php">
<input type="name" placeholder="Your name">
<input type="file" name="file">
<input type="button" id="submit">
</form>
<div id="multiform"></div>
//save_data.php
$name = $_POST['name'];
$file_name = $_FILES['file'];
$file_size = $file_name['size'];
$file_type = $file_name['type'];
$file_tmp = $file_name['tmp_name'];
list($name,$type) = explode('/',$file_type);
$save_temp = $file_tmp;
//create a new folder named images into your root page
$new_path = 'images/'.$name.$type;
//we move the file from the temporal folder to a new folder
move_uploaded_file($save_temp, $new_path);
$file_url = 'images/'.$file_type;
$sql = "INSERT INTO database (name,file_url) VALUES ('$name', '$new_path')";
//do stuffs for connect your query to your database
echo 'Uploaded!';
?>
I have created a html form which sends certain variables to a php file, the file is saved in the database and returns the success through json back to the javascript. But the problem is am not able to save the data and get the response back to the javascript file. I donno what is the reason. So can some help me with this. Thank you
my form is
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"> </script>
<script src="scriptj.js"></script>
</head>
<body>
<form action="http://localhost/donotdel/process.php" method="POST">
<div id="name-group" class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" placeholder="name">
</div>
<div id="email-group" class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" name="email" placeholder="email">
</div>
<button type="submit" class="btn btn-success">Submit <span class="fa fa-arrow-right"></span></button>
</form>
</body>
</html>
my javascript file is
$(document).ready(function () {
$('form').submit(function (event) {
$('.form-group').removeClass('has-error');
$('.help-block').remove();
var formData = {
'name': $('input[name=name]').val(),
'email': $('input[name=email]').val(),
};
$.ajax({
type: 'POST',
url: 'http://localhost/donotdel/process.php',
data: formData,
dataType: 'json',
encode: true
}).done(function (data) {
console.log(data);
if (!data.success) {
if (data.errors.name) {
$('#name-group').addClass('has-error');
$('#name-group').append('<div class="help-block">' + data.errors.name + '</div>');
}
if (data.errors.email) {
$('#email-group').addClass('has-error');
$('#email-group').append('<div class="help-block">' + data.errors.email + '</div>');
}
}
else {
$('form').append('<div class="alert alert-success">' + data.message + '</div>');
}
}).fail(function (data) {
console.log(data);
});
event.preventDefault();
});
});
and my php file is
<?php
$errors = array();
$data = array();
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if ( ! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = 'Success!';
}
header ('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
echo json_encode($data);
?>
now from the above php file i want to enter the name and email into the database. but i donno how to do it. So can someone help me out with the code. and after entering i want to send the above json response back to the javascript
thank you
What you need to do is establish a database connection and use that database connection to insert a new row in the users table. If the sql errors out return the error, if it works return the json data. Make sure to close the connection to the database when you are done.
Start by building a dbconfig.php file
This is used to establish the connection to your database.
This is what a simple one looks like.
<?php
$servername = "localhost";
$username = "root";
$password = "temppass";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
Include the dbcong.php in your file
include ('dbconfig.php');
// Check connection
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}else{
//if it make a connection insert code here!
$qry = "INSERT ..."; //build your insert string here!
$conn->query($qry); // run your insert here!
//Don't forget to CLOSE YOUR CONNECTION!
$conn->close();
}