Problem while inserting data to mysql database - php

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.

Related

vPopulate textbox field with selection from dropdown list on Web

Hi I am trying to display my address field when I select my authority code but the address field does not appear nor does the text is filled. My knowledge is pretty limited as I just started learning not long ago.
Main page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.hide{
display: none;
}
.show{
display: block;
}
</style>
</head>
<body>
<div class="wrapper">
<div>
<select name="auth" id="auth">
<option value = "">Select</option>
<?php
$connection = new mysqli("localhost", "null", "null", "null");
$stmt = $connection->prepare("SELECT AuthorityId FROM AuthorityList");
$stmt->execute();
$stmt->bind_result($authorityid);
while($stmt->fetch()){
echo "<option value = '$authorityid'>$authorityid</option>";
}
$stmt->close();
$connection->close();
?>
</select>
</div>
</div>
<div id="address" class="hide">
<label>Address</label>
<textarea id='add_text' name="address"></textarea>
</div>
</body>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#auth').change(function(){
$.ajax({
url:'getData.php',
type:'POST',
data:{
val: $('#auth').val()
},
success:function(result){
console.log(result);
if(result != ''){
$('#add_text').html(result);
$('#address').removeClass('hide');
$('#address').addClass('show');
} else {
$('#add_text').html('');
$('#address').removeClass('show');
$('#address').addClass('hide');
}
}
})
});
});
getData.php
<?php
$connection = new mysqli("localhost", "null", "null", "null");
$stmt = $connection->prepare("SELECT Address FROM AuthorityList WHERE AuthorityId = '$authorityid'");
$stmt->execute();
$stmt->bind_result($address);
$stmt ->fetch();
if($stmt -> num_rows != 0){
echo "<br><br> $address";
}
//echo "$address";
$stmt->close();
$connection->close();
?>
Main.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.hide{
display: none;
}
.show{
display: block;
}
</style>
</head>
<body>
<div class="wrapper">
<div>
<select name="auth" id="auth">
<option value="">Select Auth</option>
<option value="1">Auth_Code_1</option>
<option value="2">Auth_Code_2</option>
<option value="3">Auth_Code_3</option>
<option value="4">Auth_Code_4</option>
</select>
</div>
</div>
<div id="address" class="hide">
<label>Address</label>
<textarea id='add_text' name="address"></textarea>
</div>
</body>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#auth').change(function(){
$.ajax({
url:'getData.php',
type:'POST',
data:{
val: $('#auth').val()
},
success:function(result){
console.log(result);
if(result != ''){
$('#add_text').html(result);
$('#address').removeClass('hide');
$('#address').addClass('show');
} else {
$('#add_text').html('');
$('#address').removeClass('show');
$('#address').addClass('hide');
}
}
})
});
});
getData.php (Ajax Req. File)
<?php
//echo $_POST['val'];
echo "address";
?>
In getData.php file write query for get address into the database table and simply echo the address it's set in address textarea. try this.
Try to solve this using jquery
$(document).ready(function () {
$('#auth').click(function () {
if($('#auth').val() == '')
{
$('#address').removeClass('show');
$('#address').addClass('hide');
} else {
$('#address').removeClass('hide');
$('#address').addClass('show');
}
})
})
.hide{
display: none;
}
.show{
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div>
<label>Authorize Code</label>
<select name="auth" id="auth">
<option value=""></option>
<option value="1">Auth_Code_1</option>
<option value="2">Auth_Code_2</option>
<option value="3">Auth_Code_3</option>
<option value="4">Auth_Code_4</option>
</select>
</div>
<div id="address" class="hide">
<label>Address</label>
<textarea name="address"></textarea>
</div>
i hope it's works

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?

How to save the text box data in mysql table

I am using a map to obtain the co ordinates of the location, and get it on my text box named "add". When I try to insert the data obtained from the text box into the table it shows error.
This is my code below:
<html>
<head>
<link href="modal.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form action="" method="POST">
<table>
<tr><td>
</br>GIS Stamp</td>
<td><br><input type="text" name="add" id="add" size="31" value="" disabled="disabled"/><a href="#login_form" id="login_pop">
Select From MAP</a>
<div class="popup">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
add.value=[
latLng.lat(),
latLng.lng()
].join(', ');
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
function initialize() {
var latLng = new google.maps.LatLng(12.941320125683307, 74.86030859375);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 8,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Point A',
map: map,
draggable: true
});
// Update current position info.
updateMarkerPosition(latLng);
geocodePosition(latLng);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<style>
#mapCanvas {
width: 500px;
height: 400px;
float: left;
}
#infoPanel {
display:none;
float: left;
margin-left: 10px;
}
#infoPanel div {
margin-bottom: 5px;
}
</style>
<div id="mapCanvas"></div>
<div id="infoPanel">
<b>Marker status:</b>
<div id="markerStatus"><i>Click and drag the marker.</i></div>
<b>Current position:</b>
<div id="info"></div>
<b>Closest matching address:</b>
<div id="address"></div>
</div>
</body>
</html>
<a class="close" href="#close"></a>
</div><br></td>
</tr>
<!-- panel with buttons -->
<tr><td>
<input type="submit" name="submit" value="Insert"></td></tr></table>
</body>
</form>
</html>
<?php
if(isset($_POST['submit']))
{
$add=$_POST['add'];
$c=mysql_connect("localhost","root","");
mysql_select_db("hudadb");
$ins=mysql_query("INSERT INTO `death`
(GIS)
VALUES ('$add')",$c) or die(mysql_error());
}
?>
The error I'm getting is:
Notice: Undefined index: add in D:\XAMPP\htdocs\hudaf\mainproj\s\s.php
Elements with Disabled attribute are not submitted or you can say their values are not posted.
Replace this line of code
<input type="text" name="add" id="add" size="31" value="" disabled="disabled"/>
with
<input type="text" name="add" id="add" size="31" value="" readonly/>
NOTE: Remember disabled field is not submitted with form submit, you need to use readonly for that.

save data into mysql together with upload image using jquery and 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>

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