save data into mysql together with upload image using jquery and php - php

this is my first time getting here.
I'm currently creating a form toinsert data string into mysql database and uploading an image together. Image name must be saved in mysql DB and the file must be moved to a folder, let's name it "image/" folder.
I use jquery for inserting the data. Below is piece of code I've tried:
Form:
<form enctype="multipart/form-data" method="post" action="" id="formBerita">
<div>
Title:
<div><input type="text" id="title" name="the_title" placeholder="Your title here..." autocomplete="off"></div>
</div>
<div>
Content :
<div><textarea id="content" name="the_content"></textarea></div>
</div>
<div>
<input type="hidden" name="max_size" value="300000">
Image:
<div><input id="img" name="the_img" type="file" /></div>
</div>
<div>
<input type="button" id="btnSave" value="Save">
</div>
jQuery for inserting:
<script>
$(document).ready(function(){
$('#btnSave').on('click', function(){
var title = $("#title").val();
var content = $("#content").val();
var img = $("#img").val();
var dataContent = 'title='+title+'&content='+content+"&img="+img;
if(!title){
alert("You must fill the title!");
$("#title").focus();
}
else {
$.ajax({
type: "post",
url: 'includes/saveContent.php',
data: dataContent,
beforeSend: function() {
respon.contentColumn.append(respon.loader); //just loader before saving the data
},
success: function(datas) {
respon.contentColumn.find(respon.loader).remove();
}
});
}
});
});
</script>
saveContent.php file:
<?php
$title = $_POST['title'];
$content = $_POST['content'];
$img = $_POST['img'];
$query = "INSERT INTO tbl_content VALUES('','$title','$content','$img')";
mysql_query($query);
?>
So far, the above code works well. But, I'm still confusing how to upload and move the image file to a certain directory or folder using jQuery and PHP.
As we all know, generally in php we use:
move_uploaded_file($tempNama=$_FILES['fileName']['tmp_name'], $fileDestination);
for moving the image file to a destination folder.
So, the question: what should I add to complete my code so the image file can be uploaded and moved to a destination directory?

use this.
$targetDir = "D:\image_uploads";
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['img']['tmp_name'])) {
if(move_uploaded_file($_FILES['img']['tmp_name'],"$targetDir/".$_FILES['img']['name']))
{
echo "File uploaded successfully";
}
}
}

how to save image in folder but path name save in database in php
<?php
include("config.php");
if(isset($_POST['submit'])){
$folder = "upload/";
$imagefile = $_FILES["image"]["name"];
$temp = $_FILES["image"]["tmp_name"] ;
$wer = move_uploaded_file($temp,"$folder".$imagefile );
$query1="INSERT INTO employee (image) VALUES ('".$imagefile."')";
mysqli_query($conn,$query1);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<style type="text/css">
input[type=file]
{
width: 50%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 2px;
box-sizing: border-box;
}
div {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
</style>
<form method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="password" class="form-group">upload Image</label>
<input id="image" type="file" name="image" required="required">
</div>
<input type="submit" class="btn btn-default" value="register" id="submit"
name="submit">
</form>
</body>
</html>

Related

Use the same gform twice on the same page

I'm working in a website that needs to have the same form displayed multiple times on the same page.
The plugin that builds the forms is Gravity Forms.
I have already research on the documentation provided and I couldn't find any action that does the job.
I think I'll need to create a function that store in an array the ID of every single form created and do a comparison for every new form, so then I can probably change the ID of the form element(???).
Any guesses?
Solved the problem by printing the GravityForm inside a noscript tag and removing from that when the form is required.
See the example:
var $formContainer = $(".formContainer");
function hide_form($container) {
$container.slideUp();
var add_noscript_tag = "<noscript>" + $container[0].innerHTML + "</noscript>";
$container.empty();
$container.append(add_noscript_tag);
}
function show_form($container) {
var remove_noscript_tag = $container[0].innerHTML
.replace("<noscript>", "")
.replace("</noscript>", "");
$container.empty();
$container.append(remove_noscript_tag);
$container.slideDown();
}
$("button").click(function() {
var $FormContainer = $(this).next();
if ($FormContainer.is(":visible")) {
hide_form($FormContainer);
} else {
var $otherForm = $(".formContainer:visible");
if ($otherForm.length > 0) {
hide_form($otherForm);
}
show_form($FormContainer);
}
});
button {
margin: 20px 0;
}
.formContainer {
display: none;
background: #eee;
}
.formContainer form {
padding: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button>open form 1</button>
<div class="formContainer">
<noscript>
<form>
<input type="text" value="Name"/>
<input type="text" value="Phone"/>
<input type="text" value="Email"/>
</form>
</noscript>
</div>
</div>
<div>
<button>open form 2</button>
<div class="formContainer">
<noscript>
<form>
<input type="text" value="Name"/>
<input type="text" value="Phone"/>
<input type="text" value="Email"/>
</form>
</noscript>
</div>
</div>

Problem while inserting data to mysql database

I'm creating a simple multi chat web application.i already created this system before that works well but later i made some changes in source code due to this
when i enter inputs it will store the same data more than once in the database at the same time the duplicates data are incremented themselves.please anyone help me to solve this problem
this is my index page
<?php include 'db.php';?>
<!DOCTYPE html>
<html>
<head>
<style>
#wraper{
height:550px;
width:100%;
}
#stage{
height:450px;
width:100%;
background-color:black;
color:white;
overflow:auto;
}
#pen
{
height:100px;
width:100%;
background-color:red;
}
</style>
<title>forum</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div id="wraper">
<div id="stage">message goes here</div>
<div id="pen">
<br>
<form id="image_form" method="post" enctype="multipart/form-data">
<input type="hidden" name="action" id="action" value="insert" />
<input type="hidden" name="image_id" id="image_id" />
<input type="hidden" name="user_id" id="user_id" value="<?php session_start(); echo $_SESSION['si']; ?>" />
<input type="text"
cols="40"
rows="5"
style="width:200px; height:50px;"
name="description"
id="description"
placeholder="say some thing"
autocomplete="off" required />
<input type="hidden" name="clock" id="clock" value="<?php echo date('Y-m-d H:i:s'); ?>" readonly="readonly" />
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-info" />
</form>
</div></div>
</body>
</html>
<script>
$(document).ready(function display_msg(){
var action = "fetch";
$.ajax({
url:"forum_action.php",
method:"POST",
data:{action:action},
success:function(data)
{
$('#stage').html(data);
var objDiv = document.getElementById("stage");
objDiv.scrollTop = objDiv.scrollHeight;
}
});
$('#image_form').submit(function(event){
event.preventDefault();
$.ajax({
url:"forum_action.php",
method:"POST",
data:new FormData(this),
contentType:false,
processData:false,
success:function(data)
{
//alert(data);
$('#image_form')[0].reset();
display_msg();
}
})
});
});
</script>
this is my action page
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
#container
{
height:70px;
width:50%;
color:white;
}
.usr_id
{
background-color:blue;
height:20px;
width:40%;
position:relative;
float:left;
border-radius: 15px 0 0 0;
}
.msg
{
background-color:green;
height:30px;
width:100%;
position:relative;
float:left;
border-radius:0 0 15px 15px;
}
.clock
{
background-color:purple;
height:20px;
width:60%;
position:relative;
float:left;
border-radius:0 15px 0 0;
text-align: right;
}
</style>
</head>
<body>
<?php
//action.php
if(isset($_POST["action"]))
{
$connect = mysqli_connect("localhost", "root", "", "flash");
//INSERTING MESSSA
if($_POST["action"] == "insert")
{
$name=$_POST['user_id'];
$des= $_POST['description'];
$clock=$_POST['clock'];
$query = "INSERT INTO forum(user_id,description,clock) VALUES ('$name','$des','$clock')";
if(mysqli_query($connect, $query))
{
echo 'Data Inserted into Database';
}
}
// FETCHING MESSAGES
if($_POST["action"] == "fetch")
{
$query = "SELECT * FROM forum ORDER BY id";
$result = mysqli_query($connect, $query);
$output = '
<div>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<div id="container">
<div class="usr_id">'.$row["user_id"].'</div>
<div class="clock">'.$row["clock"].'</div>
<div class="msg">'.$row["description"].'</div>
</div><br>
';
}
$output .= '</div>';
echo $output;
}
}
?>
</body>
</html>
You're facing this problem because, and without your knowledge, you just created recursive function, which is display_msg function. To avoid that behaviour, you should put the form submit event handler outside the document.ready event handler.
// implementation of the display_msg function
function display_msg(){
var action = "fetch";
$.ajax({
url:"forum_action.php",
method:"POST",
data:{action:action},
success:function(data)
{
$('#stage').html(data);
var objDiv = document.getElementById("stage");
objDiv.scrollTop = objDiv.scrollHeight;
}
}
// execute display_msg function when the document is loaded
$(document).ready(display_msg);
// attach submit event listener to #image_form
$('#image_form').submit(function(event){
event.preventDefault();
$.ajax({
url:"forum_action.php",
method:"POST",
data:new FormData(this),
contentType:false,
processData:false,
success:function(data)
{
//alert(data);
$('#image_form')[0].reset();
display_msg();
}
})
});
And now it should no longer insert the same data again and again, and you should insert that script before the body closing tag to ensure that all the elements in the page are loaded and accessible.
Ps: You're mixing pure JavaScript and jQuery and that's not a wise
choice, you should either use only one of them.
Hope I pushed you further.

I am submitting a form using php & jquery ajax using formdata but the url part seems to be not working

I am just trying to submit a form using jquery ajax and for that i m using the FormData but whenever i click on the submit button the page reloads without showing any kind of error or any kind of result.
This is the Form Part name is regpage.php
<!DOCTYPE html>
<html>
<head>
<title>reg form</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="jquery-1.11.3-jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<style type="text/css">
#d1
{
width: 400px;
height: auto;
border: 1px solid;
text-align: center;
margin: 0 auto;
}
</style>
</head>
</head>
<body>
<form id="form" method="post" enctype="multipart/form-data">
<div id="d1">
<h1>Regestration form</h1>
username:<input type="text" name="uname" id="username" placeholder="username"><br>
password:<input type="password" name="pass" id="password" placeholder="password"><br>
email:<input type="text" name="email" id="email" placeholder="email"><br>
<span>Hobby</span>
<input type="checkbox" name="cric[]" value="cricket">Cricket
<input type="checkbox" name="cric[]" value="kite">Kite
<input type="checkbox" name="cric[]" value="zym">ZYM<br>
<h2>Gender</h2>
<input type="radio" name="chack" id="d3" value="male">male
<input type="radio" name="chack" id="d3" value="female">female<br>
<input type="file" name="image" action="image/*" ><br>
<input type="submit" name="sub" value="sign up" ><br>
</div>
</form>
<div id="output" ></div>
<script >
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "aform.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#output").fadeOut();
},
success: function(data)
{
if(data=='invalid')
{
// invalid file format.
$("#output").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e)
{
$("#output").html(e).fadeIn();
}
});
}));
});
</script>
</body>
</html>
Now here is the page where i am trying to send the form
<?php
print_r($_POST);
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // valid extensions
$path = 'uploads/'; // upload directory
if(isset($_FILES['image']))
{
extract($_POST);
$hobby=implode(',','cric');
$img = $_FILES['iname']['name'];
$tmp = $_FILES['iname']['tmp_name'];
// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
// can upload same image using rand function
$final_image = rand(1000,1000000).$img;
// check's valid format
if(in_array($ext, $valid_extensions))
{
$path = $path.strtolower($final_image);
if(move_uploaded_file($tmp,$path))
{
$con=mysqli_connect("localhost","root","","users");
$qry="insert into abcd(username,password,email,hobby,gender,image)values('$uname','$pass','$email','$hobby','$chack','$image') ";
mysqli_query($con,$qry);
//print_r($run);
echo "<img src='$path' />";
}
}
else
{
echo 'invalid';
}
}
?>
What I am Doing Wrong can anyone Tell me about it?

PHP with jQuery simple upload with process bar

I am trying to put on דוגמנות website that Simple PHP Upload Progress Bar script
APC is already installed on your server and I have tweaked my php.ini as described on the instructions.
apc.rfc1867 = on
Now the problem is that I am getting a %NaN instead of the real number from the upload process.
I know that this script IS working on some other servers so I am going to assume that there is no bug on the script and it's just something related to the php.ini or to the APC.
This is my upload.php file:
<?php
//get unique id
$up_id = uniqid();
//process the forms and upload the files
if ($_POST) {
//specify folder for file upload
$folder = "tmp/";
//specify redirect URL
$redirect = "upload.php?success";
//upload the file
move_uploaded_file($_FILES["file"]["tmp_name"], "$folder" . $_FILES["file"]["name"]);
//do whatever else needs to be done (insert information into database, etc...)
//redirect user
header('Location: '.$redirect); die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Upload your file</title>
<!--Progress Bar and iframe Styling-->
<link href="style_progress.css" rel="stylesheet" type="text/css" />
<!--Get jQuery-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.js" type="text/javascript"></script>
<!--display bar only if file is chosen-->
<script>
$(document).ready(function() {
//show the progress bar only if a file field was clicked
var show_bar = 0;
$('input[type="file"]').click(function(){
show_bar = 1;
});
//show iframe on form submit
$("#form1").submit(function(){
if (show_bar === 1) {
$('#upload_frame').show();
function set () {
$('#upload_frame').attr('src','upload_frame.php?up_id=<?php echo $up_id; ?>');
}
setTimeout(set);
}
});
});
</script>
</head>
<body>
<h1>Upload your file </h1>
<div>
<?php if (isset($_GET['success'])) { ?>
<span class="notice">Your file has been uploaded.</span>
<?php } ?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
Name<br />
<input name="name" type="text" id="name"/>
<br />
<br />
Your email address <br />
<input name="email" type="text" id="email" size="35" />
<br />
<br />
Choose a file to upload
<br />
<!--APC hidden field-->
<input type="hidden" name="APC_UPLOAD_PROGRESS" id="progress_key" value="<?=$up_id?>"/>
<input name="file" type="file" id="file" size="30"/>
<!--Include the iframe-->
<br />
<iframe id="upload_frame" name="upload_frame" frameborder="0" border="0" src="" scrolling="no" scrollbar="no" > </iframe>
<br />
<input name="Submit" type="submit" id="submit" value="Submit" />
</form>
</div>
</body>
</html>
this is my upload_frame.php
<?php
$url = basename($_SERVER['SCRIPT_FILENAME']);
//Get file upload progress information.
if(isset($_GET['progress_key'])) {
$status = apc_fetch('upload_'.$_GET['progress_key']);
echo $status['current']/$status['total']*100;
die;
}
//
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.js" type="text/javascript"></script>
<link href="style_progress.css" rel="stylesheet" type="text/css" />
<script>
$(document).ready(function() {
//
setInterval(function()
{
$.get("<?php echo $url; ?>?progress_key=<?php echo $_GET['up_id']; ?>&randval="+ Math.random(), {
//get request to the current URL (upload_frame.php) which calls the code at the top of the page. It checks the file's progress based on the file id "progress_key=" and returns the value with the function below:
},
function(data) //return information back from jQuery's get request
{
$('#progress_container').fadeIn(100); //fade in progress bar
$('#progress_bar').width(data +"%"); //set width of progress bar based on the $status value (set at the top of this page)
$('#progress_completed').html(parseInt(data) +"%"); //display the % completed within the progress bar
}
)},500); //Interval is set at 500 milliseconds (the progress bar will refresh every .5 seconds)
});
</script>
<body style="margin:0px">
<!--Progress bar divs-->
<div id="progress_container">
<div id="progress_bar">
<div id="progress_completed"></div>
</div>
</div>
<!---->
</body>
and this is my style_progress.css
/*iframe*/
#upload_frame {
border:0px;
height:40px;
width:400px;
display:none;
}
#progress_container {
width: 300px;
height: 30px;
border: 1px solid #CCCCCC;
background-color:#EBEBEB;
display: block;
margin:5px 0px -15px 0px;
}
#progress_bar {
position: relative;
height: 30px;
background-color: #F3631C;
width: 0%;
z-index:10;
}
#progress_completed {
font-size:16px;
z-index:40;
line-height:30px;
padding-left:4px;
color:#FFFFFF;
}
Let me know if there is a quick fix for that.
Where did you call apc_store()? I'm pretty sure this needs to be done before you can fetch the value using apc_fetch().

Updating div on button click, when the button is generated by clicking on another button

On clicking the button magic1 or magic2, the div mybox will be updated with a text, button id and button (different for magic1 and magic2).
After clicking on the newly generated button it should display the button id of the newly generated button in the box div. When I click on the newly generated button, box div is not getting updated. Here is the code.
jquerycode.php is the initial file. On clicking the button magic1 or magic2, Ajax will call the page session.php.
jquerycode.php file
<!doctype html>
<?php
$first=$_POST['q'];
echo $first;
?>
<html>
<head>
<meta charset="utf-8" />
<title>My jQuery Ajax test</title>
<style type="text/css">
#mybox {
width: 300px;
height: 250px;
border: 1px solid #999;
}
#box {
width: 300px;
height: 250px;
border: 1px solid #999;
position: absolute;
right:210px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".magic_button").click(function() {
var data = $(this).attr('id');
//alert (data);
$.ajax({
type: "POST",
url: "session.php",
data: { 'id': data }
}).done(function(msg) {
$("#mybox").html(msg);
});
});
});
</script>
<script>
$(".fir").click(function() {
var dataa = $(this).attr('id');
alert ("hello");
$.ajax({
type: "POST",
url: "jquerycode.php",
data: { 'q': dataa }
}).done(function(msg) {
$("#box").html(msg);
return false;
});
});
</script>
</head>
<body>
The following div will be updated after the call:<br />
<div id="mybox">
</div>
<div id="box">
</div>
<form name="magic">
<!-- <label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label> -->
<input type="button" class="magic_button" name="magic_button" id="magic_button_1" value="magic1" />
<input type="button" class="magic_button" name="magic_button" id="magic_button_2" value="magic2" />
</form>
</body>
</html>
session.php file
<?php
$id = $_POST['id'];
$id = ucwords(implode(' ',explode('_',$id)));
if($id==="Magic Button 2")
{
echo "hey its button 2!!";
?>
<input type="button" name="butb" id="second" class="fir" value="second"/>
<?php
}
else
{
echo "hey its button 1!!";
?>
<input type="button" name="buta" id="first" class="fir" value="First"/>
<?php
}
echo $id;
?>
Best if you can use JQuery Live() for dynamic Generated Elements :
$("a.offsite").live("click", function(){ alert("Goodbye!"); }); // jQuery 1.3+
Beca JQuery Live() is deprecated you need to use JQuery on()
$("#elementid").on("click", function(event){
alert($(this).text());
});

Categories