Cannot pass hidden form value to php - php

When i pass the hidden value to the php file it gives (true) 1 as a answer.
I am passing the value from the modal to the php file.
The span value was retrieved using jquery.
PHP CODE:
<?php
include "dbcon.php";
if(isset($_POST['pd_del']))
{
echo mysql_error();
$delid=isset($_POST['delidd']);
echo $delid;
}else
{
echo mysql_error();
}
?>
HTML CODE:
Form thats send the product id to the php file
<form name="prd_del" action="del_prod.php" method="post">
<div class="modal fade" id="delModal" tabindex="-1" role="dialog" aria-labelledby="delModalLabel" 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">DELETE PRODUCT</h4>
</div>
<div class="modal-body">
<h5>Do you want to Delete this Product ??? <span id="delid" name="delid"></span></h5>
<input type="hidden" name="delidd" id="delid">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" name="pd_del" >Delete It!</button>
</div>
</div>
</div>
</div>
</form>

Your HTML :
<h5>Do you want to Delete this Product ??? <span id="delid" name="delid"></span></h5>
<input type="hidden" name="delidd" id="delid">
Your JS :
$(".modal-body #delid").text( pd_del_id);
First problem is that you have 2 elements with the same id value (the sppan and the input field). You shouldn't.
Change one of your ids, something like that :
<h5>Do you want to Delete this Product ??? <span id="delid" name="delid"></span></h5>
<input type="hidden" name="delidd" id="delid_value">
And in your JS, if I understood what you want to do :
$(".modal-body #delid").text(pd_del_id); // Here you put the product's ID in your span to show it to the user.
$(".modal-body #delid_value").val(pd_del_id); // Here you put the product's ID in your hidden field to send it with your form.
Now, your PHP :
$delid=isset($_POST['delidd']);
echo $delid;
isset() function returns either true or false if the variable is set or not.
The variable $_POST['delidd'] is set (the hidden field is always sent to your PHP).
If you want to get the value (your product's ID) :
if (!empty($_POST['delidd'])) {
// The value is not empty
$delid = $_POST['delidd'];
} else {
// The value is empty : there is a problem (For example echo an error message or do whatever you have to do in that case.)
}

Related

Breaking login flow if already logged in with another session

I am working on a codeigniter 3 app and ive recently implemented a session checker that deletes a user session if they're already logged in. Now we want a modal box to pop up if the user is already logged in with another session. I am able to get a modal box to pop up using a button but i want to implement it into the original flow of the login system. As it is the login form takes you straight to the validate login system. This is the login form now:
<form action="<?php echo site_url('login/validate_login/user'); ?>" method="post">
<div class="content-box">
<div class="basic-group">
<div class="form-group">
<label for="login-email"><span class="input-field-icon"><i class="fas fa-envelope"></i></span> <?php echo get_phrase('email'); ?>:</label>
<input type="email" class="form-control" name = "email" id="login-email" placeholder="<?php echo get_phrase('email'); ?>" value="" required>
</div>
<div class="form-group">
<label for="login-password"><span class="input-field-icon"><i class="fas fa-lock"></i></span> <?php echo get_phrase('password'); ?>:</label>
<input type="password" class="form-control" name = "password" placeholder="<?php echo get_phrase('password'); ?>" value="" required>
</div>
</div>
</div>
<div class="content-update-box">
<button type="submit" class="btn"><?php echo get_phrase('login'); ?></button>
</div>
<!-- Modal -->
<div class="modal fade" id="login" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">You are already logged in</h4>
</div>
<div class="modal-body">
<p>You are currently logged in on a different session on the site. Please note that if you continue, the existing session will be terminated. Please change your password if you suspect that your account has been conpromised.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel Login</button>
<button type="submit" class="btn"><?php echo get_phrase('login'); ?></button>
</div>
</div>
</div>
</div>
<div class="forgot-pass text-center">
<span><?php echo get_phrase('or'); ?></span>
<?php echo get_phrase('forgot_password'); ?>
</div>
<div class="account-have text-center">
<?php echo get_phrase('do_not_have_an_account'); ?>? <?php echo get_phrase('sign_up'); ?>
</div>
</form>
The button at the moment goes straight to this login function:
public function validate_login($from = "") {
$email = $this->input->post('email');
$password = $this->input->post('password');
$credential = array('email' => $email, 'password' => sha1($password), 'status' => 1);
// Checking login credential for admin
$query = $this->db->get_where('users', $credential);
if ($query->num_rows() > 0) {
$row = $query->row();
$this->session->set_userdata('user_id', $row->id);
$this->session->set_userdata('role_id', $row->role_id);
$this->session->set_userdata('role', get_user_role('user_role', $row->id));
$this->session->set_userdata('name', $row->first_name.' '.$row->last_name);
$this->delete_session_user_id();
$this->session->set_flashdata('flash_message', get_phrase('welcome').' '.$row->first_name.' '.$row->last_name);
if ($row->role_id == 1) {
$this->session->set_userdata('admin_login', '1');
redirect(site_url('admin/dashboard'), 'refresh');
}else if($row->role_id == 2){
$this->session->set_userdata('user_login', '1');
$this->set_session_user_id();
redirect(site_url('home/my_courses'), 'refresh');
}
}else {
$this->session->set_flashdata('error_message',get_phrase('invalid_login_credentials'));
redirect(site_url('home/login'), 'refresh');
}
}
I created this function to pull the user id from the emails:
public function get_user_id($user_email = "") {
$this->db->select('id');
$this->db->where('email', $user_email);
$user_id=$this->db->get('users');
return $user_id;
}
This function can get the user id based on the email supplied.
Then I use this function to check if there is a session and return false if there are 0 results and true if there is a session with that user id. So if its false they should be able to log in and the modal pop-up shouldnt open but if its true it should open.
public function user_has_session($user_id=''){
$this->db->where('user_id',$user_id);
$this->db->from('ci_sessions');
$total=$this->db->count_all_results();
if($total<0)
return false;
else
return true;
}
I think this is the best approach without having to redo the entire login flow. Perhaps someone can advise if this is the best approach or if in fact i should change the entire flow.
Thanks
Here is the previous problem I had which I have answered myself
https://stackoverflow.com/questions/62458226/codeigniter-3-stop-multiple-logins-using-ci-sessions-database
UPDATE Added to clarify my problem
Well the problem is when a login is attempted from another device it should logout the other active session. So if o logged in on my desktop in a new browser or even my phone with the same user ID the active session should end, at the moment it does so without warning the user. So I want to have a modal pop up warning the user that there is an active session currently running with this user id
You need to implement an Ajax call which will check whether the user is already logged in or not. If the user is not logged In than you can proceed to login otherwise trigger your popup open to display the message.
Here the user has choices to log in or not, If users choose to login then you can unbind the event on submit and let the user go ahead.
I have made some changes to your HTML file. Please check below -
Your HTML template
<form action="<?php echo site_url('login/validate_login/user'); ?>" id="login-form" onSubmit="return checkUserSession();" method="post">
<div class="content-box">
<div class="basic-group">
<div class="form-group">
<label for="login-email"><span class="input-field-icon"><i class="fas fa-envelope"></i></span> <?php echo get_phrase('email'); ?>:</label>
<input type="email" class="form-control" name = "email" id="login-email" placeholder="<?php echo get_phrase('email'); ?>" value="" required>
</div>
<div class="form-group">
<label for="login-password"><span class="input-field-icon"><i class="fas fa-lock"></i></span> <?php echo get_phrase('password'); ?>:</label>
<input type="password" class="form-control" name = "password" placeholder="<?php echo get_phrase('password'); ?>" value="" required>
</div>
</div>
</div>
<div class="content-update-box">
<button type="submit" class="btn"><?php echo get_phrase('login'); ?></button>
</div>
<!-- Modal -->
<div class="modal fade" id="login" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">You are already logged in</h4>
</div>
<div class="modal-body">
<p>You are currently logged in on a different session on the site. Please note that if you continue, the existing session will be terminated. Please change your password if you suspect that your account has been conpromised.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel Login</button>
<button type="button" id="modal-submit-button" class="btn"><?php echo get_phrase('login'); ?></button>
</div>
</div>
</div>
</div>
<div class="forgot-pass text-center">
<span><?php echo get_phrase('or'); ?></span>
<?php echo get_phrase('forgot_password'); ?>
</div>
<div class="account-have text-center">
<?php echo get_phrase('do_not_have_an_account'); ?>? <?php echo get_phrase('sign_up'); ?>
</div>
</form>
<script>
/** Trigger function on form submit whether to check user logged in */
function checkUserSession(){
var email = $("#login-email").val();
$.ajax({
url: "<?php echo site_url('login/checkUserSession'); ?>",
type: 'POST',
data: { 'email': email},
success: function(status){
if(status == true) { // User is already logged in somewhere, display the messege.
$("#login").modal();
return false;
} else { // User is not logged in, submit the form
return true;
}
}
});
}
/** Allow user to log in with exception */
$("#modal-submit-button").on("click", function(){
$("#login").modal('hide'); // hide the modal
$("#login-form").attr("onSubmit", ""); // unbind the function
$("#login-form").submit(); // submit login form
})
</script>
Controller -
<?php
/** Function to check user logged in or not */
public function checkUserSession() {
$user_email = $this->input->post('email');
$userId = $this->get_user_id($user_email);
$response = $this->user_has_session($userId);
echo $response;
}
public function get_user_id($user_email = "") {
$this->db->select('id');
$this->db->where('email', $user_email);
$user_id=$this->db->get('users');
return $user_id;
}
public function user_has_session($user_id=''){
$this->db->where('user_id',$user_id);
$this->db->from('ci_sessions');
$total=$this->db->count_all_results();
if($total<0)
return false;
else
return true;
}
?>

Bootstrap-Select: get comma values from a Mysql column and display them automaticly inside bootstrap-select as checked

I'm working with Bootstrap-Select and I would like that some options inside this multiple dropdown list, would it be checked based on comma values from a Mysql column. I found one similar question, but I didn't find a correct way to solve my question:
Bootstrap select - Get selected Value
Below are two tables that describe my question:
colors_tbl
colorID | color |
--------+-------+
01 | Blue |
02 | Black |
03 | Green |
04 | Red |
05 | White |
-----------------
And below is the table that storage the values with comma inside column Color. The color column is a foreign key of Colors table above.
cars_tbl
carID | car | colors
------+------+------------------
01 | BMW | Red,Blue,Green
02 | GM | Red,Black,White
03 | FORD | Green,Gray,Black
--------------------------------
Based on the information above, I would like to get color values from cars_tbl on colors column (ID 03), for example, and display these values inside Bootstrap select as checked when a bootstrap modal is open.
Below is an image that show what has been described:
Below is the html code of bootstrap modal that display Bootstrap-Select inside and a jQuery function that open modal and display data using ajax results:
<div class="modal fade" id="userModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit Car</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="post" id="user_form" enctype="multipart/form-data">
<div class="row">
<div class="col">
<label>Car</label>
<input type="text" name="car" id="car" class="form-control"/>
</div>
<div class="col">
<div class="form-group">
<label>Colors</label>
<?php
include 'pdo_connection.php';
$stmt = $connection->prepare('SELECT * FROM colors_tbl');
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<select class="selectpicker form-control" name="colors[]" id="colors" data-actions-box="true" multiple>
<?php foreach($results as $row): ?>
<option value="<?= $row['colorID']; ?>"><?= $row['color']; ?></option>
<?php endforeach ?>
</select>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="user_id" id="user_id" />
<input type="hidden" name="operation" id="operation" />
<input type="submit" name="action" id="action" class="btn btn-warning" value="" />
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>
<script>
$(document).on('click', '.update', function(){
var user_id = $(this).attr("id");
$.ajax({
url:"fetch_single.php",
method:"POST",
data:{user_id:user_id},
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#car').val(data.car);
$('#colors').val(data.colors);
$('#user_id').val(user_id);
$('#action').val("Edit Car");
$('#operation').val("Edit");
}
})
});
</script>
And a php script (fetch_single.php) that fetch data when modal above is open:
<?php
include 'pdo_connection.php';
if(isset($_POST["user_id"]))
{
$output = array();
$statement = $connection->prepare(
"SELECT * FROM cars = '".$_POST["user_id"]."'
LIMIT 1"
);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output["car"] = $row["car"];
$output["colors"] = $row['colors'];
}
echo json_encode($output);
}
?>
To try to solve this doubt, i tried to put this code below after variable $output = array(); of fetch_single script above:
$array = array($row['colors']);
$colors = implode(",", $array);
And replace this line:
$output["colors"] = $row['colors'];
to this:
$output["colors"] = $color;
But no success.
UPDATED
I found a method that Bootstrap-select use to get values and display inside dropdown list. The method is:
$('.selectpicker').selectpicker('val', ['value 1','value 2']);
In this case, i put this selectpicker method inside ajax success and i dont know how can i get colors values from my php script that send results in JSON format to Ajax. If i replace the values 'value 1' and 'value 2' to 'data.colors' inside brackets above, i didn't get nothing when modal is opened:
$.ajax({
url:"fetch_single.php",
method:"POST",
data:{user_id:user_id},
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#car').val(data.car);
$('#colors').selectpicker('val', [data.colors]);
$('#user_id').val(user_id);
$('#action').val("Edit Car");
$('#operation').val("Edit");
}
})
How can i put colors values from JSON format and put indide selectpicker.('val', [])?
I dont understand the method of some moderators. I found a solution myself to solve my doubt and probably hundreds of doubts of programmers who might have the same doubt. Less bureaucracy, please.
To be more specific, according to some incomprehensible moderators:
I solve my question using javascript string split() method. The split() method is used to split a string into an array of substrings, and returns a new array.
Tip: If an empty string ("") is used as the separator, the string is split between each character.
Note: The split() method does not change the original string.
$('.selectpicker').selectpicker('val', data.color.split(','));
Is that good now? Free hugs for all lords of stackoverflow!!!

Show modal after redirection, laravel

I am trying to show a modal after redirection.
I have seen all the ways on the net but nothing worked.
Controller
return redirect()->back()->with('code');
Blade
#if(session('code')) )
<script>
$(function() {
$('#verify_code').modal('show');
});
</script>
#endif
<div id="verify_code" class="modal custom-modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Verify Phone Number</h3>
</div><!-- end modal-header -->
<div class="modal-body">
<form method="POST" action="{{ url('verify_code') }}">
#csrf
<div class="form-group">
<input type="number" class="form-control" id="code" name="code" placeholder="Enter verification code" required/>
</div>
<button class="btn btn-orange btn-block">Verify Phone Number</button>
</form>
</div><!-- end modal-bpdy -->
</div><!-- end modal-content -->
</div><!-- end modal-dialog -->
</div><!-- end edit-profile -->
The with function on redirect can have two parameters, a key and a value. You are passing just a key, 'code' and by default Laravel will set the value to null.
So, when you fetch the value of session('code'), this will return null. And php views null as a false value, so your condition is never true.
To fix this, pass a value to your with function:
return redirect()->back()->with('code', true);
i think better approachment like this,
In Controller
Session::flash('code','randomvalue');
return redirect()->back();
and then change your blade like this
//checking if the session has 'code'
#if(Session::has('code'))
your script
#endif
Your code variable is probably never set when it arrives in your view.
If your variable is defined in your code before you try to return it. You can use compact() function to pass it to your view. Like so:
return redirect()->back()->with(compact('code'));
Compact creates an array containing variables and their values.
Or with just an array:
return redirect()->back()->with([
'code' => $code
]);
Once your variable is passed to your view, you can just test it. Assuming $code contains a boolean or something not empty:
#if ($code)
...
#endif

Get MySQL data to bootstrap model

I have a list of users on my web page echoed using a PHP loop. The names are links look like this.
{$user['username']}
So, when I click on each user, I am taken to user.php page.
user.php displays each user's information based on the query parameter $user['id'] in the URL. Using $_GET['id'] method.
So, that's the current situation I have.
What I now want to do is, display user's information in a Bootstrap Model
So, how could I get that query parameter into the Bootstrap model. And do the same PHP processes to get the same functionality ?
If you have google this you can get number of results related to it.
Here is code seems to be referred from one of this question passing-data-to-a-bootstrap-modal
HTML
<a data-toggle="modal" data-id="ISBN564541" title="Add this item" class="open-AddBookDialog btn btn-primary" href="#addBookDialog">test</a>
<div class="modal hide" id="addBookDialog">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h3>Modal header</h3>
</div>
<div class="modal-body">
<p>some content</p>
<input type="text" name="bookId" id="bookId" value=""/>
</div>
</div>
Javascript
$(document).ready(function () {
$(".open-AddBookDialog").click(function () {
$('#bookId').val($(this).data('id'));
$('#addBookDialog').modal('show');
});
});

Save Inputs into database & class errors - building coupon system

Okay, I'm building (trying) a coupon code system for my admin panel, what I want to achieve is allow admin to manually create coupons by setting its coupon_code and coupon_discount (1% TO 100%). When he will submit, it will be stored in two different tables of two dbs.
TABLE coupons:
coupon_id INT(10) NOT NULL AUTO INCREMENT - Primary key
coupon_code VARCHAR(15) NOT NULL - unique
discount DECIMAL(3,2)
expire DATETIME -NULL
count INT(10) -NULL
I checked lots of examples on the net and this is my probably poorly written class:
class ProductDiscount {
static public function validate($coupon_code);
private $_coupon_code; // string
private $_coupon_discount; // integer??
private $_expire; // null cause unlimited
private $_count; // null
private function __construct(); //for this line I got an error
public function getCouponCode(); // return string
public function getCouponDiscount(); // return
public function getCount(); // returns null unlimited
public function getExpireDate();// null
public function useDiscount(); // apply this discount now
public function useAllDiscount(); // invalidate this discount for future use
COUPONS.PHP - new coupon creation
On the admin side, I am totally lost about how to pass the coupon_code and coupon_discount to the database...How to utilize the functions that I wrote in the class...This is what I did:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$coupon_code = $_POST['coupon_code'];
$coupon_discount = $_POST['coupon_discount'];
//insert into db for admin
$connect = new mysqli("localhost","-----","-------","--------");
$stmt = $connect->prepare("INSERT INTO `coupons` (`coupon_code`, `coupon_discount`) VALUES (?,?)");
$stmt->bind_param('si', $coupon_code, $coupon_discount);
$stmt->execute();
$connect->close();
}
?>
I'm getting undefined index errors for both the coupon_code and coupon_discount..
If I require_once my class file here, I'm getting Non-abstract method ProductDiscount::create() must contain body error.
<form class="form-horizontal" role="form" action="createcoupon.php">
<div class="form-group">
<label class="col-sm-2 control-label">Coupon Code</label>
<div class="col-sm-2">
<input type="text" class="form-control" name="coupon_code" id="couponCode" placeholder="e.g SAVE10">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Coupon Discount</label>
<div class="col-sm-2">
<input type="number" class="form-control" name="coupon_discount" id="couponDiscount" placeholder="e.g 10 for 10%">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-3">
<input type="submit" style="background-color:#7575DD; padding:0 !important; color:white;" name="create_coupon" value="Create Coupon" class="btn btn-default"/>
</div>
</div>
</form>
Here is my createcoupon.php:
<?php
//Connect to the 1st db
$coupon_code = $_POST['coupon-code'];
$coupon_discount = $_POST['coupon-discount'];
//the prepared stmt to insert into db1
//Connect to the 2nd tb
$coupon_code = $_POST['coupon-code'];
$coupon_discount = $_POST['coupon-discount'];
//prepared stmt to insert into db2
header("location: http://example.com/admin/coupons");
?>
It's 4am and been hours that I'm trying to learn these.
So my question is: "How can I save the necessary form data to the table in the correct way and save the coupon into the table?"
(edited and specified my current problem only, can you reopen?)
(commented the long/unnecessary parts to clarify)
Thank you so much for your time!
Okay so far, I managed to solve it. Using bootstrap table.
With an "add coupon" button:
<button data-toggle='modal' data-target='#myModal' type='button' class='btn btn-primary' style="margin: 20px;" name='add-btn' id='add-btn'>Add Coupon</button>
data-toggle='modal' and data-target='#myModal' to link the modal div to the button
SELECT statement to get the coupon table and pull the data into a bootstrap table.
<div style="padding: 20px;">
<?php
$con = new mysqli("------","--------","--------","-----");
$query = "SELECT * FROM coupons WHERE expire > NOW() OR expire IS NULL OR expire = '0000-00-00 00:00:00'";
if ($result = $con->query($query))
{
echo "<table border='1' class='table table-hover' data-toggle='table'>
<tr>
<th>Coupon Code</th>
<th>Amount</th>
<th>Expiry</th>
<th></th>
</tr>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row['coupon_code'] . "</td>";
echo "<td>" . $row['coupon_discount'] . "</td>";
echo "<td>" . $row['expire'] . "</td>";
echo "<td><button data-toggle='modal' data-target='#myModal' type='button' class='btn btn-primary' name='submit-btn' data-id='" . $row["coupon_id"] ."'>Edit</button></td>";
echo "</tr>";
}
echo "</table>";
}
mysqli_close($con);
?>
These are the modal divs and form to post the inputs and save it to the table.
<!-- Modal -->
<div class="modal fade" id="myModal" 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">Coupon Information</h4>
</div>
<div class="modal-footer">
<form action='createcoupon.php' method='POST'>
<input type='hidden' name='coupon_id' id='couponId' value='0'/>
<input type="text" class="form-control" style="margin-bottom:10px;" name="coupon_code" id="couponCode" placeholder="e.g SAVE10">
<input type="number" class="form-control" style="margin-bottom:10px;" name="coupon_discount" id="couponDiscount" placeholder="e.g 10 for 10%">
<input type="text" class="form-control" style="margin-bottom:10px;" name="coupon_expire" id="couponExpire" placeholder="e.g 01/01/2015">
<input class="btn btn-primary" type='submit' name='submit-btn' value='Save' />
</form>
</div>
</div>
</div>
</div>
</div>
This is the javascript
<script>
// Function added to each edit button. Sets the ID to the button "data-id" value.
// Finds the parent (td) of the button, then goes to each sibling with the correct class name
// and changes the modal input value to the inner text of the TD
var editfunction = function() {
$('#couponId').val($(this).attr('data-id'));
var parent = $(this).parent();
$('#couponCode').val($(parent).siblings('.coupon_code').text());
$('#couponDiscount').val($(parent).siblings('.coupon_discount').text());
$('#couponExpire').val($(parent).siblings('.coupon_expire').text());
};
// Called on the ADD button only
// Sets the ID to 0 (to INSERT the record on the form submit)
// Sets the other inputs to blank values
function addNewCoupon()
{
$('#couponId').val('0');
$('#couponCode').val('');
$('#couponDiscount').val('');
$('#couponExpire').val('');
}
// When the page has loaded...
// Attach the edit function call to the click event of each edit button
// Attach the add new coupon to the click event of the add button
$(document).ready(function() {
$('button[name="submit-btn"]').click(editfunction);
$('#add-btn').click(function() { addNewCoupon(); });
});
</script>
Then on the createcoupon.php I did this:
// Check connection
$coupon_id = intval($_POST['coupon_id']);
$coupon_code = $_POST['coupon_code'];
$coupon_discount = $_POST['coupon_discount'];
and after with mysqli connection I inserted/updated (in an if else statement, "if is 'add coupon' or 'edit coupon') them.
I solved this in the end, If you have any ideas about it, please share with me so that I can improve.
I hope these codes can be useful for someone!
Thanks for your time.

Categories