Submitted Information from a Modal Into mySQL - javascript

I was having some problems submitted information from a modal into mySQL, this is what I have tried.
<script>
var cells = document.querySelectorAll('.table-row > td');
var cellIndex = -1;
cells.forEach((e, index) => {
e.addEventListener("click", () => {
//show modal
$('.modal').modal("show");
//update grid
// This is the row number
console.log("Row number: ", index)
cellIndex = index
})
})
function updateTable(e) {
let name, email, phonenumber, tableRow, row;
name = document.getElementById("name").value;
console.log(name, email, phonenumber);
// Get the row that you want
row = cells[cellIndex];
$(row).html(name);
$('.modal').modal("hide");
}
document.getElementById("submit-btn").addEventListener("click", updateTable);
//store in database
$.ajax({
url:"insert.php",
method:"POST",
data:$('#insert_form').serialize(),
success:function(data)
{
alert('form was submitted');
}
})
</script>
This is my insert.php:
<?php
$conn = new
mysqli("127.0.0.1","root","password");
if($conn->connect_error){
die("Connection failed: " . $conn-
>connect_error);
}
if(!empty($_POST))
{
$output = '';
$name =
mysqli_real_escape_string($connect,$_POST["name"]);
$phonenumber =
mysqli_real_escape_string($connect,$_POST["phonenumber"]);
$email =
mysqli_real_escape_string($connect,$_POST["email"]);
$query = "INSERT INTO users(name,phonenumber,email) VALUES('$name',
'$phonenumber','$email' )";
}
echo "Connected successfully";
?>
My understanding of the problem is that I need to use ajax to send a request to the web server that would store the information from the modal to the mySQL database with the given query in php. Perhaps I don't have a good understanding of the problem. I am not sure how to get the values from the modal, and in conjuction use ajax to send a post to the server. Any help would be appreciated.
Here is my Modal:
<div class="row">
<div class="col-md-12">
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1>Reservation</h1>
</div>
<div class="modal-body">
<input type="text" name="field1" placeholder="Name" id="name">
<input type="text" name="field2" placeholder="Email" id="email">
<input type="text" name="field3" placeholder="PhoneNumber" id="phonenumber">
</div>
<div class="modal-footer">
<input id="submit-btn" name="submit" class="btn submit" value="Submit">
<input class="btn btn-default" data-dismiss="modal" value="Close">
</div>
</div>
</div>
</div>
</div>
</div>

Related

Why my succes-msg or error-msg are not display?

well, in my js files, i'm trying to display success-ms or error-msg. I don't understang why my div #error-msg or #success-msg doesn't appear.
Here my js code. If user clicks on confirm, data are sent to process.php to insert the keyword in my mysql table
$(function()
{
$('#alert-change').click(function(event){
$("#error-msg12").html('');
$("#success-msg12").html('');
event.preventDefault();
$.post('include/process.php',$('#alert-change-form').serialize(),function(resp)
{
if (resp['status'] == true)
{
$("#success-msg12").html(resp['msg']+"");
$("#success-msg12").show();
}
else
{
var htm = '<button data-dismiss="alert" class="close" type="button">×</button>';
$.each(resp['msg'],function(index,val){
htm += val+" <br>";
});
$("#error-msg12").html(htm);
$("#error-msg12").show();
}
},'json');
});
});
My form
<div id="myModal_alert" class="modal fade">
<div class="modal-dialog modal-login1">
<div class="modal-content">
<form name="alert-change-form" id="alert-change-form" method="post">
<div class="modal-header">
<h4 class="modal-title">Add a keyword.</h4>
<div class="alert" id="error-msg12">
</div>
<div class="alert alert-success" id="success-msg12">
</div>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<input type="hidden" id="process" name="process" value="4">
<input type="hidden" id="first_name" value ="<?= $_SESSION['name']?>" class="form-control" name="first_name" minlength="3" maxlength="10" placeholder="" class="login" />
<div class="form-group">
<div class="clearfix">
<label>add a keywordt.</label>
</div>
<input type="text" id="kw" class="form-control" name="alert" placeholder="" class="kw" required />
</div>
</div>
<div class="modal-footer">
<button class="button btn btn-primary btn-large" id="alert-change">Confirmer</button>
</div>
</form>
</div>
</div>
</div>
and my process.php file
if ($_POST['process'] == '4') {
$error = array();
$res = array();
$success = "";
$alert = mysql_real_escape_string($_POST['alert']);
echo $_POST['first_name'];
echo $alert;
// errors
if (!preg_match("#^[a-z0-9_]+$#", $alert))
{
$error[] = 'error 1';
}
if (strlen($alert) < 2)
{
$error[] = 'error 2';
}
$sql = "SELECT * FROM users_alert WHERE user = :user AND kw = :alert";
$req = $bdd->prepare($sql);
$req->bindParam(':user', $_POST['first_name'], PDO::PARAM_STR);
$req->bindParam(':alert', $alert, PDO::PARAM_STR);
$req->execute();
$resultat = $req->fetchAll();
if (count($resultat))
{
$error[] = 'error 3';
}
if(count($error)>0)
{
$resp['msg'] = $error;
$resp['status'] = false;
echo json_encode($resp);
exit;
}
// on exécute
$sqlQuery = "INSERT INTO users_alert (user,kw) VALUES (:user,:kw)";
$run = $bdd->prepare($sqlQuery);
$run->bindParam(':user', $_POST['first_name'], PDO::PARAM_STR);
$run->bindParam(':kw', $alert, PDO::PARAM_STR);
$run->execute();
$resp['msg'] = "success1";
$resp['status'] = true;
echo json_encode($resp);
exit;
}
I've tried 4/5 things, in vain.
Somebody has an idea ?
Can you delete them in the process.php file and try again?
echo $_POST['first_name'];
echo $alert;
If this is not working, you should capture the post values ​​you sent to the process.php file and go step by step.

I have an error when sending data by POST with javascript

I am trying to send data via post in Javascript, but I am new to this.
I leave my code, I want to know what I do wrong.
To begin with I have a file where I call a query in my mysql database as long as the code and the date are entered.
public function listusuerdate($date,$name) {
try {
$sql= "select * from markers where name_user = :p_user AND date_user = :p_dat";
$statement = $this->dblink->prepare($sql);
$statement->bindParam(":p_user", $name);
$statement->bindParam(":p_dat", $date);
$statement->execute();
$result= $statement->fetchAll(PDO::FETCH_ASSOC);
return $result;
} catch (Exception $exc) {
throw $exc;
}
}
I have another file where he passed the variables by means of POST in the following way:
<?php
require_once '../negocio/ShowMap.clase.php';
$date= $_POST["p_dat"];
$name= $_POST["p_user"];
$objUser = new ShowMap();
try {
$result = $objUser ->listusuerdate($date,$name);
} catch (Exception $exc) {
header("HTTP/1.1 500");
echo $exc->getMessage();
}
?>
When I use Postman works good
Here comes my problem I have created a form to send the date and the name of the user as follows:
<form>
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Título de la ventana</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xs-2">
<p>Code<input type="text" name="txtcode" id="txtcode" class="form-control input-sm text-center text-bold" placeholder="" readonly=""></p>
</div>
<div class="col-xs-4">
<p>Name <font color = "red">*</font>
<input type="text" name="txtname" id="txtname" class="form-control input-sm" placeholder="" required=""><p>
</div>
<div class="col-xs-3">
<p>Date
<input type="date" class="form-control input-sm" id="txtdate" name="txtdate" /></p>
</div>
<div class="modal-footer">
<a class="btn btn-primary btn-lg" value='Click' href='javascript:;' onclick="toshow();" role="button"></a>
</div>
</div>
</div>
</div>
</form>
Finally I am trying to send the date and the name of the user by means of javascript in the following way:
function toshow(){
var name = document.getElementById("txtname").value;
var date = document.getElementById("txtdate").value;
$.post(
"../controlador/ruta.controlador.php",
{
p_user : name,
p_dat : date
}
).done(function(){
alert( "exit" );
}).fail(function(error){
alert(error.responseText);
});
};
I could not make it work
You need to write a js function properly check its syntax
function toshow(){
var name = document.getElementById("txtname").value;
var date = document.getElementById("txtdate").value;
$.ajax(
method:'POST', // here you can spasify post or get
url:"../controlador/ruta.controlador.php",
data : {
p_user : name,
p_dat : date
},
).done(function(){
alert( "exit" );
}).fail(function(error){
alert(error.responseText);
});
};

keep the modal open after form submit in codeigniter and trying a bit of ajax

so this is my controller:
User_Authentication_Controller:
public function login_user(){
$username = $this->input->post('txt_login_username');
$password = md5($this->input->post('txt_login_password'));
$result=$this->LogIn_Model->login($username,$password);
redirect('Pages_Controller/homepage');
}
LogIn_Model:
public function LogIn($username,$password){
$data = array(
'username' => $username,
'password' => $password
);
$query = $this->db->get_where('user_account',$data);
return $query->result_array();
}
LOGIN MODAL:
<section id="login_modal" class="modal fade" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header"></div>
<div class="modal-body" id="forms">
<div class="loginmodal-container">
<h1>Login to Your Account</h1><br>
<form class="form-horizontal" id="form_login" action="" method="POST">
<div class='error_msg'></div>
<input autofocus="autofocus" type="text" id="txt_login_username" name="txt_login_username" class="form-control" />
<input type="password" id="txt_login_password" name="txt_login_password" class="form-control" />
<button class="btn btn-primary" type="submit" name="btnLogin">Login</button>
Forgot Password?
</div>
</form>
</div>
<div class="modal-footer">
<center><button type = "submit" id="login_user" class="btn btn-danger" data-dismiss="modal" >CLOSE</button></center>
</div>
</div>
</div>
</section>
VIEW:
Login
AJAX:
$(function(){
$('#login_user').submit(function(event){
var user = $('#txt_login_username').val();
var pass = $('#txt_login_password').val();
$.ajax({
type: 'POST',
url: 'User_Authentication_Controller/login_user',
data: {
'user': user,
'pass': pass
},
dataType: 'html',
success: function(results){
if(user != user){
$('.error_msg').html('error msg');
return false;
}
}
});
});
});
ALL I WANT IS IF THERE IS AN ERROR! THE will work and the modal will not close! how will I do that with CI? Is there any possible way that just put the LogIn_Model->login(); in AJAX? please help! I need this thing badly! And in addition I want that what the user inputs and if he got it wrong when he submitted the username will still be at the textbox! how will I do that also? THank you so much for help!

To display data in the fields in the modal retrieved from the mysql database

Friends I am submitting the form on clicking the submit button and simultaneously i am displaying the just submitted data in the modal.So as soon as i hit the submit button ,the data gets submitted and a modal appears with the data just submitted.Everything is working fine with my code but the only problem that the data does not gets displayed in the modal.
Here is the code for submitting the form-
$("#savep").click(function(e){
e.preventDefault();
formData = $('form.pform').serialize() + '&'
+ encodeURI($(this).attr('name'))
+ '='
+ encodeURI($(this).attr('value'));
$.ajax({
type: "POST",
url: "data1_post.php",
data: formData,
success: function(msg){
$('input[type="text"], textarea').val('');
$('#entrysavedmodal').modal('show');
},
error: function(){
alert("failure");
}
});
});
Here is modal which gets displayed when i click on submit button-
<div id="entrysavedmodal" class="modal fade" role="dialog">
<div class="modal-dialog" style="width:1000px;">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><span class="glyphicon glyphicon-plus"></span> Saved Entry</h4>
</div>
<div class="modal-body">
<form class="form-horizontal savedform" id="savedform">
<div class="form-group">
<label class="control-label col-xs-2">Date:</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="datepreview" name="datepreview"
value = "<?php
include('db.php');
$sql = "SELECT `date` FROM tran ORDER BY id DESC limit 1";
$result = mysqli_query($conn,$sql);
$rows = mysqli_fetch_assoc($result);
$date = $rows['date'];
echo $date;
?>" readonly /> //this field does not show anything and none of the fields show any data.
</div>
<label class="control-label col-xs-2">v_no:</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="v_nopreview" name="v_no" autocomplete="off" readonly /> //same problem
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-info" id="print" name="print" >Print</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
Date field does not show the date value from database and v_nopreview field also does not show anything.
I have tried to give as much details as possible but in case if you need anything then let me know.Please let me know why the data is not being displayed inside the input fields in modal.
Thanks in advance.
Edited part
Here is the data1_post.php code-
<?php
include('db.php');
$sql = "INSERT INTO `table1` (`date`, `v_no`, `name`,`narration`,`stk_y_n`)
VALUES ( '".$_POST['date']."','".$_POST['v_no']."', '".$_POST['user']."','".$_POST['narration']."', 'No')";
if ($conn->query($sql) === TRUE){
echo "saved";
}
else
{
echo "not saved";
}
?>
As I understand, you expect execution of php code each time after js event. But PHP is a server-side language, it interprets only once, when you request the pages.
So your php code will load some content form DB after refreshing, then you clear input's value before displaying model and as it can't be executed again - you see empty modal.
I recommend you to return saved data from "data1_post.php" and than process it in success callback
UPDATE
if you want to present saved data, your php code would look like the following
include('db.php');
$response = ["success" => false];
$sql = "INSERT INTO `table1` (`date`, `v_no`, `name`,`narration`,`stk_y_n`)
VALUES ( '".$_POST['date']."','".$_POST['v_no']."', '".$_POST['user']."','".$_POST['narration']."', 'No')";
if ($conn->query($sql) === TRUE){
$sql = "SELECT `date` FROM tran ORDER BY id DESC limit 1";
$result = mysqli_query($conn,$sql);
$rows = mysqli_fetch_assoc($result);
$response = ["success" => true, "date" => $rows['date']];
}
header('Content-type: application/json');
echo json_encode($response);
and js
$("#savep").click(function(e){
e.preventDefault();
formData = $('form.pform').serialize() + '&'
+ encodeURI($(this).attr('name'))
+ '='
+ encodeURI($(this).attr('value'));
$.ajax({
type: "POST",
url: "data1_post.php",
data: formData,
success: function(response){
$('input[type="text"], textarea').val('');
if (response.success) {
$('#datepreview').val(response.date);
$('#entrysavedmodal').modal('show');
} else {
alert("failure");
}
},
error: function () {
alert("failure");
}
});
});

Bootstrap Modal shows up on one page but not the other?

I am trying to code a website using Bootstrap. I already have it implemented on one page using a modal (here) and the other page doesn't seem to show the modal (here) on that page, there is a button that can edit the ban details but when I click the edit button, it does nothing.
Also, I am using jQuery for form submissions so that I can redirect to the returned ID, however, I am stuck on how my function can return the ID because using
get_mysql()->fetch_assoc($result)["id"]
causes a 500 internal server error.
Codes can be found below.
ban.php
<div class="modal fade" id="modal" 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-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Edit Ban</h4>
</div>
<form id="form">
<div class="modal-body">
<div class="form-group">
<input type="text" value="<?php echo $ban["uuid"] ?>" id="uuid" name="uuid" placeholder="UUID" class="form-control"/>
</div>
<div class="form-group">
<input type="text" value="<?php echo $ban["reason"] ?>" id="reason" name="reason" placeholder="Reason" class="form-control"/>
</div>
</div>
<input type="hidden" id="id" name="id" value="<?php echo $ban["id"] ?>" />
<div class="modal-footer">
<input type="submit" class="btn btn-primary"/>
</div>
</form>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#form").submit(function(e) {
e.preventDefault();
var uuid = $("#uuid").val();
var reason = $("#reason").val();
$.post("add.php", { id: id, uuid: uuid, reason: reason, key: "<?php echo get_key() ?>" }, function(data) {
location.href = "ban.php?id=<?php echo data ?>";
});
});
});
</script>
index.php
<div class="modal fade" id="modal" 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-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Add Ban</h4>
</div>
<form id="form">
<div class="modal-body">
<div class="form-group">
<input type="text" value="<?php echo $ban["uuid"] ?>" id="uuid" name="uuid" placeholder="UUID" class="form-control"/>
</div>
<div class="form-group">
<input type="text" value="<?php echo $ban["reason"] ?>" id="reason" name="reason" placeholder="Reason" class="form-control"/>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary"/>
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$("#form").submit(function(e) {
e.preventDefault();
var uuid = $("#uuid").val();
var reason = $("#reason").val();
$.post("functions/add.php", { uuid: uuid, reason: reason, key: "<?php echo get_key() ?>" }, function(data) {
location.href = "functions/ban.php?id=<?php echo data ?>";
});
});
});
</script>
api.php
<?php
define("key", "redacted");
function get_mysql() {
$mysql = new mysqli("localhost", "redacted", "redacted", "redacted");
if($mysql->connect_error) {
die($mysql->connect_error);
}
return $mysql;
}
function add($uuid, $reason) {
$date = gmdate("Y-m-d H:i:s");
get_mysql()->query("insert into bans (uuid, date, reason) values ('$uuid', '$date', '$reason')");
$result = get_mysql()->query("select id from bans where uuid = '$uuid' and date = '$date' and reason = '$reason'");
get_mysql()->fetch_array($result);
return $result["id"];
}
function update($id, $uuid, $reason) {
get_mysql()->query("update bans set uuid = '$uuid', reason = '$reason' where id = $id");
}
function remove($uuid) {
get_mysql()->query("delete from bans where uuid = '$uuid'");
}
function remove_by_id($id) {
get_mysql()->query("delete from bans where id = $id");
}
function get($uuid) {
return get_mysql()->query("select * from bans where uuid = '$uuid'")->fetch_assoc();
}
function get_by_id($id) {
return get_mysql()->query("select * from bans where id = $id")->fetch_assoc();
}
function get_bans() {
return get_mysql()->query("select * from bans");
}
function login($username, $password) {
$password = hash("sha256", $password);
return get_mysql()->query("select count(*) from users where username = '$username' and password = '$password'")->num_rows > 0;
}
function register($username, $password) {
$password = hash("sha256", $password);
get_mysql()->query("insert into `users` (`username`, `password`) values ('$username', '$password'");
}
function get_key() {
return key;
}
?>
I've found the answer thanks to #stain88. I didn't provide the correct link to bootstrap.min.js (facepalm)
Thanks again #stain88.

Categories

Resources