Data from displayed summary must submit to database using modal form - javascript

Sorry, english is not my Native Language. I've been really stuck since I've just use PHP to store data in my Database (I'm using mysql).
So in my html I have the main
function display() {
var canvas = document.getElementById('displaycanvas');
context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
if(document.getElementById('color1').checked){ context.strokeStyle="#FF0000"; } else if(document.getElementById('color2').checked){ context.strokeStyle="#0000FF"; }
if (document.getElementById('shape1').checked) {
context.beginPath(); context.arc(95,50,40,0,2*Math.PI); context.stroke(); }
if (document.getElementById('shape2').checked) {
context.beginPath(); context.rect(50, 27, 50, 100); context.stroke(); }
}
$('#review').click(function () {
$('#shape').html($('input[name="shape_design"]:checked').val());
$('#color').html($('input[name="color_design"]:checked').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="displaycanvas"></canvas>
<form role="form" id="showchoices" name="showchoices" method="post" onsubmit="return entry_check()" action="/user/ps/add/">
<div> <input type="radio" id="shape1" name="shape_design" value="CIRCLE" onchange="display()" /> O
<input type="radio" id="shape2" name="shape_design" value="RECTANGLE" onchange="display()" /> [] </div>
<div> <input type="radio" id="color1" name="color_design" value="RED" onchange="display()"/> RED
<input type="radio" id="color2" name="color_design" value="BLUE" onchange="display()" /> BLUE </div> </form>
<input type="button" name="btn" value="Review" id="review" data-toggle="modal" data-target="#con_rev" class="btn btn-primary" />
<!-- this modal displays the SUMMARY,working fine -->
<div class="modal fade" id="con_rev" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">Confirm Order</div>
<div class="modal-body">
<form action="#myModal1" role="form" method="POST"> <!-- display for the Order sent -->
<p> Shape: <span id="shape" name="shape" ></span> </p>
<p> Color: <span id="color" name="color" ></span> </p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<input type="submit" class="btn btn-success" name="order"/> </div>
</div> </form>
</div>
</div>
Everything above is working fine, I just would like to show how it looks like.
So this is how it works. Once the user will choose her/his choices, first it will display a modal that "Summarizes" the data its modal id="con_rev".
So here we have the data displayed based on user's choices.
Now I've made another modal when the user decides to "ORDER" or submit its choices.
Modal same in HTML page: (this one isn't working)
<div id="myModal1" class="modal modal-child" data-backdrop-limit="1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-modal-parent="#myModal">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">ORDER SENT</h4> </div>
<div class="modal-body">
<?php
include 'database.php';
$pdo = Database::connect();
$shape = $_POST['shape'];
$color = $_POST['color'];
$dbc = #mysql_connect('localhost' , 'root', '');
#mysql_select_db('order_db', $dbc);
$query = "INSERT INTO choice VALUES(NULL, '$shape','$color')";
if(#mysql_query($query,$dbc)){
print '<h1> Your order has been sent </h1>'; }
else{ print '<p> failed. '.mysql_error().'</p>'; }
?>
</div>
</div>
</div>
</div>
I've followed different sources of tutorial and combined them.
It won't display error, but if I'm going to check at my database its still empty. Hope you could really help me out.
In case you'll use Ajax, our class haven't tackled it so I'm not sure if I could advance but still if its the only way I'll take it!
Thank you in advance!

First of all, mysql_connect() is deprecated and has been removed in PHP 7.0.0
Now what is confusing me is that, you're taking the pdo instance (pressumably it's PDO extension) through:
include 'database.php';
$pdo = Database::connect();
but didn't use it at all:
Try this (I've adapted to your configuration by using PDO extension) :
<div id="myModal1" class="modal modal-child" data-backdrop-limit="1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-modal-parent="#myModal">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">ORDER SENT</h4> </div>
<div class="modal-body">
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$database = 'order_db';
$shape = $_POST['shape'];
$color = $_POST['color'];
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
);
try {
$pdo = new PDO("mysql:host=host;dbname=database", $user, $pass, $options);
}
catch (PDOException $e) {
echo "connection error : <br> :";
echo $e->getMessage();
}
$sql = "INSERT INTO 'choice' VALUES (:mynull, :shape, :color)";
$statement = $pdo->prepare($sql);
$statement->bindValue(':mynull', null, PDO::PARAM_INT);
$statement->bindValue(':shape', $shape, PDO::PARAM_STR);
$statement->bindValue(':color', $color, PDO::PARAM_STR);
$inserted = $statement->execute();
if($inserted){
echo 'Your order has been sent !<br>';
}
?>
</div>
</div>
</div>
</div>
also don't use # , it's intended to suppress the errors thus you cann't see it when the error thrown.

Related

Pass Value From URL Link To Form Field

I have a link in a table from results of an SQL query. Each row has a unique ID. I define this in my script as $id
What I am trying to do is have a link that opens up a form in a modal box where a user can insert a note about that row and save it. This then gets inserted into DB with ID, rowID, Note, Date
echo "<td class='agentid'>" . $id. "<br><a href='#notes' data-toggle='modal' data-row-id='".$id."'>Add Note</a></td>" ;
The modal:
<div class="modal" id="notes">
<div class="modal-dialog">
<div class="modal-content">
<form action="postnote.php" method="post">
<div class="modal-body">
<div class="modal-header">
<h4 class="modal-title">Add a Note</h4>
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
</div>
<p>Note will show when page is refreshed</p>
<label for="fname">Note: </label>
<input type="hidden" name="rowID" value=""/>
<input class="form-control" type="text" name="notes" value="<?php echo date('m/d/Y h:i'); ?> - "/>
<div class="modal-footer">
<button type="submit" value="Submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$('#notes').on('show.bs.modal', function(e) {
var row = $(e.relatedTarget).data('row-id');
$(e.currentTarget).find('input[name="rowID"]').val(row);
});
</script>
my postnote.php
$pdoOptions = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
);
$pdo = new PDO("mysql:host=" . MYSQL_HOST . ";dbname=" . MYSQL_DATABASE, MYSQL_USER,MYSQL_PASSWORD,$pdoOptions);
$data = [
'notes' => $_POST['notes'],
'id' => $_POST['rowID'],
];
$sql = "INSERT INTO act_recon_notes (note_id, note) Values(:id, :notes)";
$stmt= $pdo->prepare($sql);
$stmt->execute($data);
header('Location: ' . $_SERVER['HTTP_REFERER']);
I have this exact script on another page and it is working just fine. This does not post the $id into the form. So after submit it is a blank rowID value in the DB.
The issue was I had conflicting JS on the page. I removed the JS that was not needed for this page and the issue resolved.
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>

Showing bootstraps modal after redicted to page

So I have been making a website where settings.php and saveSettings.php page where it insert $_POST functions to database.
Here is part of settings.php
echo '
<form action="saveSettings.php" method="POST">
<div class="form-group">
<textarea class="form-control no-resize" rows="4" id="profilecomment" name="profilecomment"></textarea>
</div>
<input type="submit" class="btn btn-success" name="submit" style="margin-top:10px" value="Submit" />
</form>
';
and here part of saveSettings.php
$userComment = $_POST["profilecomment"];
$updateComment = "UPDATE users SET comment = '$userComment' WHERE steamid = '$steamID' ";
header('Location: settings.php');
This is what I have tried:
I added my modal load script to settings.php page
<script>
$(window).load(function(){
$('#settingsSave').modal('show');
});
</script>
And modal script:
<div class="modal fade" id="settingsSave" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p>You have successfully saved your settings!</p>
</div>
</div>
</div>
</div>
I am not sure if it does not popup because of that:
header('Location: settings.php');
I hope I can get some help.
First, please be aware of mysql Injection, I see you dont escape your POST parameters.
Do it like this:
$userComment = mysql_real_escape_string($_POST["profilecomment"]);
or use mysqli instead of mysql
To your question:
$(window).load(function(){
$('#settingsSave').modal('show');
});
is wrong, you must use something like:
$( document ).ready(function() {
<?
if(isset($_GET['save'])){
echo "$('#settingsSave').modal('show');";
}
?>
});
ans pass a parameter to your new location
header('Location: settings.php?save');

JavaScript Username authentication

The following represent my registration link which lead to open a modal:
Register Here
The following represents the code for my modal dialog:
<div class="modal fade" id="registermodal" role="dialog" style="overflow: scroll;">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal" name="f2" id="regisform" method="post" onsubmit="return false;" role="form">
<div class="modal-header">
<h4>Registration<button class="close" data-dismiss="modal">×</button></h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="inputusername3" class="col-sm-2 control-label">Username</label>
<div class="col-lg-8">
<input type="text" name="txtusername" class="form-control" id="inputusername3" placeholder="username">
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" name="submit" id="regisBtn" class="btn btn-primary" value="Registration">
<a class="btn btn-default" data-dismiss="modal">Cancel</a>
</div>
</form>
</div>
</div>
</div>
The below represent the JavaScript Code:
$(document).ready(function(){
$("#regisBtn").click(function(){
var username1=$("#inputusername3").val();
$.post("registercheck.php", {username:username1}, function(result){
if(result==='true')
alert("true");
else
alert("false");
});
});
});
The below represent my php code:
<?php
$username1=$_POST['username'];
$con= mysql_connect("localhost","root","");
mysql_select_db("onlineshop",$con);
$query1= mysql_query("select username from users where username=$username1",$con);
if(mysql_num_rows($query1)==1){
echo 'false';
}else{
mysql_query("insert into users(username)values ('".$username1."')",$con);
session_start();
$_SESSION['username']=$username1;
echo 'true';
}
There is error in mysqli_num_rows() shows that it expects parameter 1 to be resource, Boolean given in something like that
I dont knw why my code is not working. please help me with my code to check whether the username is exists or not?
You have 4 problems with your code. First, you are using mysql_* functions. Use mysqli_* instead, mysql_* is deprecated. Second, you are vulnerable to SQL injection. This is fixed below by using mysqli_real_escape_string. Consider using PDO instead. Third, your select query is malformed - any string in the query must be wrapped in single quotes. Fourth, in a couple of mysql_* function calls, your database link is the last parameter. It should always be the first parameter in the call.
<?php
$con = mysqli_connect("localhost","root","");
mysqli_select_db($con, "onlineshop");
$clean_username1 = mysqli_real_escape_string($con, $_POST['username']);
$query1 = mysqli_query($con, "select username from users where username = '".$clean_username1."'");
if (mysqli_num_rows($query1) == 1){
echo 'false';
} else {
mysqli_query($con, "insert into users (username) values ('".$clean_username1."')");
session_start();
$_SESSION['username'] = $_POST['username'];
echo 'true';
}

Ajax is not updating data

I've got a forum in which user is allowed to edit and delete only his comments, I've defined an "edit" button, that by a click of mouse brings down a modal, and in that modal user is allowed to get access to the data's he/she has been sent before, I've written an ajax to target these field and update them whenever the users clicks on "edit" button, code totally makes sense, but so far the functionality doesn't, to make it more clear, user clicks, modal comes down, whatever he/she has been posted will appear in fields, and there is an "edit" button at the bottom of modal, which is responsible for changing and updating data. here is the modal code :
<button id="btn-btnedit" class="btn btn-primary " data-toggle="modal" data-target="#myModal<?php echo $list['id']; ?>">
Edit <i class="fa fa-pencil-square-o"></i>
</button>
<!-- Modal -->
<div class="modal fade" id="myModal<?php echo $list['id']; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<div class="container">
<form style="width: 550px;" action="" method="post" id="signin-form<?php echo $list['id']; ?>" role="form">
<input type="hidden" name="commentID" value="<?php echo $list['id']; ?>">
<div class="from-group">
<label for="title">Title: </label>
<input class="form-control" type="text" name="title" id="txttitle" value="<?php echo $list['title']; ?>" placeholder="Page Title">
</div>
<div class="from-group">
<label for="label">Label: </label>
<input class="form-control" type="text" name="label" id="txtlabel" value="<?php echo $list['label']; ?>" placeholder="Page Label">
</div>
<br>
<div class="from-group">
<label for="body">Body: </label>
<textarea class="form-control editor" name="body" id="txtbody" row="8" placeholder="Page Body"><?php echo $list['body']; ?></textarea>
</div>
<br>
<input type="hidden" name="editted" value="1">
<br>
<br>
<input type="submit" id="btnupdate" value="Edit">
</form>
</div>
</div>
as you can see I've assigned "editted" to my "name" attribute, which is later on used to call the query in the database, sql code is as below :
case 'postupdate';
if(isset($_GET['editted'])){
$title = $_GET['title'];
$label = $_GET['label'];
$body = $_GET['body'];
$action = 'Updated';
$q = "UPDATE posts SET title ='".$title."', label = '".$label."', body = '".$body."' WHERE id = ".$_GET['commentID'];
$r = mysqli_query($dbc, $q);
$message = '<p class="alert alert-success"> Your Post Is Succesfully '.$action.'</p>' ;
}
and here is the ajax code snippet;
$('#btnupdate').click(function() {
var tempTitle = $('#txttitle').val();
var tempLabel = $('#txtlabel').val();
var tempBody = $('#txtbody').val();
var tempUrl = "index.php?page=postupdate"+"&title="+tempTitle+"&label="+tempLabel+"&body="+tempBody+"&commentID=30&editted=1";
$.get(tempUrl);
});
I assume there is nothing advance about this segment of code, and i'm missing something very simple, any consideration is highly appreciated :)
This (untested code) may be similar to what you should do:
$('#btnupdate').click(function() {
var tempTitle = $('#txttitle').val();
var tempLabel = $('#txtlabel').val();
var tempBody = $('#txtbody').val();
var tempParams = {"page":"postupdate","title":tempTitle,"label":tempLabel,"body":tempBody,"commentID":30,"editted":1};
$.post("index.php",tempParams,function(data) {
alert(data);
});
});
UPDATE
Try ajax instead of get to see if some error occurs in the loading
$.ajax( {url:"index.php",data:tempParams,type: "POST"} ).done(function() {
alert( "success" );
}).fail(function() {
alert( "error" );
}).always(function() {
alert( "complete" );
});`
UPDATE
Start testing if the click handler works then (just to be sure!):
$('#btnupdate').click(function() { alert("yes at least the button was pressed"); });
UPDATE
Start testing if the script gets executed then:
alert("yes at least the script gets executed");
$('#btnupdate').click(function() { alert("yes at least the button was pressed"); });
If not you must have a javascript error somewhere.
https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers
If yes, your button does not get caught by JQuery (no idea why)
anyway it's got nothing to do with ajax or get!

How to Upload a file and save to DB using PHP, JavaScript, Bootstrap

everyone..
i've problem using javascript.
i want to make CRUD using Modal(bootstrap), PHP and javascript. but unfortunatelly til now i can't upload a file and save them to database. i have 3 files (index, form, javascript, process) here is my code :
for modal (index) :
<div id="dialog-admin" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel"></h3>
</div>
<!-- tempat untuk menampilkan form admin -->
<div class="modal-body"></div>
<div class="modal-footer">
<button class="btn btn-danger" data-dismiss="modal" aria-hidden="true">Batal</button>
<button id="simpan-admin" class="btn btn-success">Simpan</button>
</div>
this code for form file :
<form class="form-horizontal" id="form-admin" enctype="multipart/form-data" >
<div> ... bla bla bla.. field.. </div>
<div class="control-group">
<label class="control-label" for="ava">Image</label>
<div class="controls">
<input type="file" id="ava" name="ava" value="<?php echo $ava ?>" required="required" />
</div>
</div>
this code for javascript :
$("#simpan-admin").bind("click", function(event) {
var url = "admin-proses.php";
// mengambil nilai dari inputbox, textbox dan select
var v_username = $('input:text[name=username]').val();
var v_email = $('input:text[name=email]').val();
var v_pass = $('input:text[name=pass]').val();
var v_ava = $('input:file[name=ava]').val();
// mengirimkan data ke berkas transaksi admin-proses.php untuk di proses
$.post(url, {username: v_username, email: v_email, pass: v_pass, ava:v_ava, id: id} ,function() {
// tampilkan data admin yang sudah di perbaharui
// ke dalam <div id="data-admin"></div>
$("#data-admin").load(main);
// sembunyikan modal dialog
$('#dialog-admin').modal('hide');
// kembalikan judul modal dialog
$("#myModalLabel").html("Tambah Data Admin");
});
});
and this code for file process :
require 'dbase.php';
$id = $_POST['id'];
$username = $_POST['username'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$imageName = $_FILES['ava']['name'];
$imageSize = $_FILES['ava']['size'];
$imageError = $_FILES['ava']['error'];
if ($imageSize > 0 || $imageError == 0){
$move = move_uploaded_file($_FILES['ava']['tmp_name'], '../uploads/ava/'.$imageName);
if ($move){
echo 'success';
} else {
echo 'failed';
}
} else {
echo 'failed to save file to DB : '.$imageError;
}
mysql_query("INSERT INTO tb_admin VALUES('','$username','$email','$pass','$imageName')") or die (mysql_error());
could you to help me ?
thank
Regard
check whether the post has been done properly in jquery. do step by step debugging.Be sure of getting all input field values.
I would suggest that you should go to this link by W3Schools:
http://www.w3schools.com/php/php_file_upload.asp
It covers all the basics of file uploading.
For Database, go through this:
http://www.php-mysql-tutorial.com/wikis/mysql-tutorials/uploading-files-to-mysql-database.aspx

Categories

Resources