I have a HTML table with employee name and id that is being retrieved from an SQL select. I want to be able to edit the employee password and update it my DB. The php function is working but I want to run it from an onclick function in javascript. My code is:
function update(id) {
var pass = document.getElementById('pass'+id).value;
var Cpass = document.getElementById('Cpass'+id).value;
if (pass != Cpass){
Notify("Passwords don't match. Please reneter passwords");
}
else{
//run php function $this->ea_user_settings->update_password(id, pass);
Notify("Password saved");
document.getElementById('update'+id).style.display = 'none';
}
}
function edit(id) {
if (document.getElementById('update'+id).style.display == 'inline'){
document.getElementById('update'+id).style.display = 'none';
}
else{
document.getElementById('update'+id).style.display = 'inline';
}
}
function Notify($msg) {
$("#notification").text("");
$("#notification").fadeIn(1000).append($msg);
$("#notification").fadeOut(5000);
}
<div id="notification" style="display : none" value=""></div>
<?php
$invoice = $this->ea_user_settings->get_employee_name_id();
?>
<table class="table table-hover table-bordered table-striped" id = "EmployeeList">
<thead>
<tr>
<th style="background-color:#BA9E5E; position:sticky; top: 0"><p style="color: white;">Name</p></th>
<th style="background-color:#BA9E5E; position:sticky; top: 0"><p style="color: white;">ID</p></th>
<th style="background-color:#BA9E5E; position:sticky; top: 0"><p style="color: white;">Update Password</p></th>
</tr>
</thead>
<tbody>
<?php
foreach ($invoice as $report): ?>
<tr>
<td><?php echo $report->Name ?> </td>
<td><?php echo $report->ID ?> </td>
<td>
<div>
<div id="<?php echo 'update'.$report->ID;?>" style="display:none">
<input type="text" id="<?php echo 'pass'.$report->ID;?>" name="pass" placeholder="Password">
<input type="text" id="<?php echo 'Cpass'.$report->ID;?>" name="Cpass" placeholder="Confirm Password">
<button id='updateBtn' type="button" onClick='update("<?php echo $report->ID;?>")'>Save</button>
</div>
<div id="<?php echo 'edit'.$report->ID;?>" style="display:inline; text-align:right; padding:10px" align="right">
<button id='editBtn' type="button" onClick='edit("<?php echo $report->ID;?>")'>Edit</button>
</div>
</div>
</td>
</tr>
<?php endforeach;?>
</tbody>
</table>
I want to run my php update function ($this->ea_user_settings->update_password(id, pass);) when I click on the save button.
You need to use ajax for the same.
$.ajax({
url: '/change-password.php',
data: {'user_id':user_id, 'pass': pass, 'new_pass': new_pass},
type: 'POST',
success: function (result)
{
//Do something
}
});
You can refer this sample code :)
You cannot directly call the PHP function from your JavaScript function. PHP runs on the server whereas JS runs on the client.
You could, however, send a get or post request to your server from a javascript function and execute your php function based on the received parameters.
[update - adding an example]
Consider your php page to contain the following function:
<?php
function writeMsg($param) {
echo "Hello ".$param;
}
writeMsg($_GET["name"]);
?>
//Here the parameter 'name' is retrieved from the http request and passed to the function.
For eg., if the link is something like //test-php-page?name=stackoverflow, the displayed HTML page will contain Hello stackoverflow
From your client code, you cannot call the function writeMsg. You would have to send a valid http request to the server with the parameter 'name'. It can be achieved just by placing an anchor tag.
<a href="/test-php-page?name=stackoverflow'>link</a>
or, by form action method
<form action="/test-php-page" method="get">
<input type="text" name="name">
<input type="submit" value="Submit">
</form>
or, by ajax calls using JS.
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "/test-php-page?name=stackoverflow", true);
xhttp.send();
You could also use jQuery or any other library for ease of using ajax calls.
Refer the following w3schools link for better understanding: https://www.w3schools.com/php/php_ajax_intro.asp
Related
I want to rerun a PHP File which was loaded in a div in my HTML code. On my main page, I have a form and a table. The form adds rows to the MySQL table, and the table on the page outputs that MySQL table. I want the table on the HTML page to update when the new row is added via the form, without refreshing the page. I tried putting the load command in the success part of the ajax function for my form but that didn't work. I looked at many other answers and none worked for me.
This is my code
redeem.php
<h1>Rewards</h1>
<form id="add-reward-form" action="" method="POST">
<label for="inputRewardDescription" class="form-label">Enter Reward Description</label>
<input type="text" id=inputRewardDescription name="description" class="form-control" required>
<label for="inputRewardCost" class="form-label">Enter Reward Cost</label>
<input type="text" id=inputRewardCost name="points" class="form-control" required>
<button type="submit" class="btn btn-success" id="submit-btn">Save</button>
</form>
<p id="message"></p>
<div id="sql-table">
<?php include 'tables.php'; ?>
</div>
tables.php
<?php
$host = "";
$user = "";
$pass = "";
$db_name = "";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
$result = mysqli_query($connection,"SELECT RewardName, PointsRequired FROM rewards");
$all_reward = array(); //declare an array for saving property
while ($reward = mysqli_fetch_field($result)) {
// echo '<th scope="col">' . $reward->name . '</th>'; //get field name for header
array_push($all_reward, $reward->name); //save those to array
}
// echo ' </tr>
// </thead>'; //end tr tag
echo '<table class="table">
<thead>
<tr>
<th scope="col">Reward</th>
<th scope="col">Points Required</th>
<th scope="col">Edit</th>
<th scope="col">Delete</th>
</tr>
</thead>';
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tbody>
<tr>";
foreach ($all_reward as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '<td><i class="fas fa-edit"></i></td>';
echo '<td><i class="fas fa-trash"></i></td>';
echo ' </tr>
</tbody>';
}
echo "</table>";
?>
redeem-form.js
$(document).ready(function() {
$("#add-reward-form").submit(function(e) {
e.preventDefault();
$.ajax( {
url: "add_rewards.php",
method: "POST",
data: $("form").serialize(),
dataType: "text",
success: function(strMessage) {
$("#message").text(strMessage);
$("#add-reward-form")[0].reset();
$("#sql-table").load(" #sql-table > *");
}
});
$("#sql-table").load(" #sql-table > *");
});
});
The form works perfectly fine with ajax, and submits to the database without refreshing. But I would like to update the table on my page as well without reloading.
$("#sql-table").load(" #sql-table > *");
This is what I tried. I placed it inside the success function and the submit function but both did not work.
You are mis-using $.load(). It's a shorthand for $.ajax(). The first argument must be a URL. Optional arguments are data and options.
You are passing it a selector, so the request fails. As-is, $("#sql-table").load(" #sql-table > *"); is attempting an AJAX request to the URL /%20#sql-table%20%3E%20*. (!)
Simply change the selector for the PHP file you want to execute:
$("#sql-table").load("tables.php");
How about forcing redeem.php to re-evaluate the PHP div every time a change happens to the inputs?
<h1>Rewards</h1>
<script>
function redrawSQLTable(){
document.getElementById('sql-table').innerHTML = "<?php include 'tables.php'; ?>"
}
</script>
<form id="add-reward-form" action="" method="POST">
<label for="inputRewardDescription" class="form-label">Enter Reward Description</label>
<input type="text" id=inputRewardDescription name="description" class="form-control" required onchange="redrawSQLTable()">
<label for="inputRewardCost" class="form-label">Enter Reward Cost</label>
<input type="text" id=inputRewardCost name="points" class="form-control" required onchange="redrawSQLTable()">
<button type="submit" class="btn btn-success" id="submit-btn">Save</button>
</form>
<p id="message"></p>
<div id="sql-table">
<?php include 'tables.php'; ?>
</div>
I started learning webdeveloping and i tried to send "id" of one of the rows generated from database to another page. The rows are clickable thanks to the javascript code, so i can choose whichever row i want. The problem is, that even though the POST method seems right:
<form id="send" method="POST" action=<?php echo "secondpage.php?id=". $row['id']; ?> ></form>
// In inspect of the main page it gets the value.
However
second page always receive id value of 1. Doesn't matter if i click on the row with id=18 or any other. It will always recieve value of 1...
I heard that this could be a problem with javascript code which i put under PHP code.
Here is a code with PHP:
<div id="content">
<table id="usersTable" class="table table-bordered table-hover table-sm ">
<form action=http://localhost/dodawanie.php>
<input class="btn btn-primary" type="submit" value="Dodawanie">
</form>
<?php if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {?>
<tr>
<td><?php echo "id: ". $row['id']; ?> </td>
<td><?php echo "Name: ". $row["first_name"]; ?> </td>
<td><?php echo "Last: ". $row["last_name"];?> </td>
<form id="send" method="POST" action=<?php echo "secondpage.php?id=". $row['id']; ?> >
</form>
</tr>
<?php }
} else {
echo "0 results";
}
$conn->close();
?>
</table>
</div>
Here is javascript:
<script type = "text/javascript">
$(document).ready(function(){
$('#usersTable').find('tr').click( function(){
// alert('You clicked row ' + ($(this).index()+1) );
$('#send').submit();
});
});
</script>
I would gladly accept any help to find an error here.
Change the <form id="send" id value as unique
or use a class some thing like below:
<form class="form_send" then in your javascript search for the form_class inside the clicked tr:
$(document).ready(function(){
$('#usersTable').find('tr').click( function(){
$(this).find('form.form_send').submit();
});
});
Ids have to be unique. $('#send').submit() only finds and submits the first form with that id.
You could add your row id to the form's id attribute to make them unique for example.
I've a UI which adds data to the database via ajax. That data should reflect in my datatable without reloading the whole page or by just reloading the datatable. I've tried using t.api().ajax.reload() & t.ajax.reload() but it throws error in console like "Cannot read property 'reload' of undefined" or "t.api is not a function" i Don't know what am doing wrong here. Below are some reference
UI - Adding datas through add role btn which brings a pop up
Add Role Pop Up
HTML
<div id="roles" style="display: block" >
<ul class="tab-onebtn">
<li class="logouttab"> <a style="float: left;" id="myBtn"> Add Role </a> </li>
</ul>
<div class="table roles_table" >
<table class="example display" id="mytable" cellspacing="0" width="100%">
<thead>
<tr>
<th>Roles</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach($resultRoles as $r) { ?>
<tr>
<td><?php echo $r->cptv_role; ?></td>
<td></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<h1> Roles coming soon</h1>
</div>
<div id="myModal" class="modal" >
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<!-- <div class="modal-header">
<h2 style="text-align:center";>Add Role</h2>
</div>-->
<div class="modal-body">
<form action="" method="post" class="addRoleForm">
<?php if(!empty($this->session->flashdata('error')) ) { ?><div class='error' style="margin-top: -20px;"><h2><?php echo $this->session->flashdata('error'); ?> </h2></div><?php } ?>
<?php if(validation_errors() != false) { ?><div class='error'><?php echo validation_errors(); ?></div><?php } ?>
<div class="field-wrap">
<label>
Role <span class="req">*</span>
</label>
<input name="role" class="roleInput" type="text"required autocomplete="off"/>
</div>
<div id="result" class="msg" style="display:none;"></div>
<button class="button button-block submitbtn"/><span class="addRole" >Add Role </span> <span class="Added" style="display:none;"><b>Successfully Added </b></span></button>
</form>
</div>
<!-- <div class="modal-footer">
<h3>Modal Footer</h3>
</div>-->
</div>
</div>
Javascript
// Ajax post
$(document).ready(function() {
var t = $('#mytable').DataTable();
$(".addRoleForm").submit(function(){
event.preventDefault();
var str = $(this).serialize();
console.log();
jQuery.ajax({
type: "POST",
url: base_url+ "admin/roles/addRole",
dataType: 'json',
data: str,
success: function(result) {
if (result)
{
console.log(result);
// Show Entered Value
jQuery("div#result").show();
if(result.success){
// $('#mytable tbody').append('<tr><td>'+$('input[name="role"]').val().trim()+'</td><td></td></tr>');
// $('#mytable').DataTable();
t.api().ajax.reload();
jQuery("div.msg").html("<div class='success'><h2>"+result.success+"</div>");
setTimeout(function(){
span.click();
}, 2000);
}else{
jQuery("div.msg").html("<div class='error'><h2>"+result.error+"</h2></div>");
}
//var ref = $('#mytable').DataTable();
//setInterval( function () {
// ref.ajax.reload(); // user paging is not reset on reload
//}, 1000 );
setTimeout(function(){
jQuery("div#result").hide();
$(".roleInput").val('');
}, 2000);
}
}
});
});
});
Controller
public function addRole() {
if (empty($this->sessionData)){
// print_r($this->sessionData['id']); exit;
$this->index();
}
$post = $this->input->post();
$this->form_validation->set_rules('role', 'Role', 'trim|required|xss_clean');
if ($this->form_validation->run()) {
$roleDet = $this->roles_model->checkCpRoles(array('cptv_role' => $post['role']));
if ($roleDet->num_rows()) {
$data['error'] = " Role already Exist.";
echo json_encode($data);
} else {
$result = $this->roles_model->addCpRoles(array('cptv_role' => $post['role']));
if ($result){
$data['success'] = " Successfully added the Role ";
echo json_encode($data);
} else {
$data['error'] = " Something went wrong ";
echo json_encode($data);
}
}
}
}
Can somebody help me please!?
Reload the datatable after ajax success like:
You're using old API: $().dataTable() (v1.9 and earlier) which is still available in DataTables v1.10. The old API returns jQuery object, so you should use .api() in order to use DataTable API methods:
oTable.api().ajax.reload();
// where oTable is the reference to datatable.
Since you have written some code in php I dont understand it much, But I can point the issue in your code. You are having a normal HTML table to which you apply the DataTable plugin.
Your code t.api().ajax.reload(); breaks because the DataTable is not fetching data via ajax, meaning your DataTable is not setup for a ajax based data, Its a normal HTML table.
What I suggest you is return the entire row that you need to append into the table (make sure all the columns are returned, right now you have only 2 columns in your table) in your ajax success method. Now all you have to do is add this new column into the dataTable and redraw the table.
Syntax to add a new row into the dataTable and redraw it is as below.
t.row.add(yourArrayGoesHere).draw( false );
So that means your response from the server must be a array. Example : ["Admin",""]
Test: Open your console window in the browser (press F12 to open)
and paste this code and hit enter. You must be able to see a new row with first cell having the value Admin.
t.row.add(["Admin",""]).draw( false );
Let me know if this helps.
This is the best example i have ever seen in which datatable is implemented with the Codeigniter framweork.
http://mbahcoding.com/tutorial/php/codeigniter/codeigniter-ajax-crud-using-bootstrap-modals-and-datatable.html
I'm pretty new to jQuery and I'm practicing with it. I've this html simple page:
<html>
<head>
<title> Testing jQuery
</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="script.js" type="text/javascript"></script>
<link href="mycss.css" rel="stylesheet" type="text/css">
</head>
<body>
<h2 id="myH"> This is a title.</h2>
<br>
<br>
<fieldset>
<legend>Data</legend>
<form name="myForm">
<input type="text" id="firstData" placeholder="Write something in here" \>
<br>
<br>
<input type="text" id="secondData" placeholder="Write something else in here" \>
<br>
</form>
<button id="formButton" value="Confirm">Confirm</button>
</fieldset>
<br><br><br>
<div id="myDiv"></div>
</body>
</html>
This PHP script:
<?php
/* Connection to DB*/
.... CONNECTIONS STUFF.........
$query = " SELECT * FROM table1;";
$results = mysql_query($query);
echo " <table border=\"2\"><tr> <th>ID</th><th>First</th><th>Second</th></tr>";
while($row = mysql_fetch_array($results)) {
?>
<tr>
<td>
<?php echo $row['ID']?>
</td>
<td>
<?php echo $row[ 'First']?>
</td>
<td>
<?php echo $row[ 'Second']?>
</td>
</tr>
<?php
} echo "</table>"; ?>
And finally this js code:
$(function () {
$('#formButton').on('click', function (e) {
var firstData = $('#firstData').val();
var secondData = $('#secondData').val();
var query = 'first=' + firstData + '&second=' + secondData;
// Here I use another php script.
$.get('myData.php', query, function (data) {
$('#myDiv').html(data);
});
});
$('#formButton').on('click', function (e) {
$.ajax({
url: "myquery.php",
type: "POST",
success: function (data) {
$("#myDiv").empty().html(data);
}
});
});
});
Ok , now that I've inserted all the code , the problem is that I can add elements to my database by using myData.php script but I'd like to create a page where in the top you can add elements and when you click on the confirmation button in the bottom (with a query) all the contents of the table are displayed. So I can add elements but I'm not able to display them. I'm new to jQuery and I'm trying to make it work , I've made different researches on the Web but I couldn't find anything that solved my problem. Could please someone help me? Thanks!
You can do both operation by single file myData.php
Put below code right after record inserted in myData.php
$query = " SELECT * FROM table1;";
$results = mysql_query($query);
echo " <table border=\"2\"><tr> <th>ID</th><th>First</th><th>Second</th></tr>";
while($row = mysql_fetch_array($results)) {
?>
<tr>
<td>
<?php echo $row['ID']?>
</td>
<td>
<?php echo $row[ 'First']?>
</td>
<td>
<?php echo $row[ 'Second']?>
</td>
</tr>
<?php
} echo "</table>"; ?>
No need of two ajax call. Remove the second button click jquery code.
On first button click event myData.php file will be called. First record will be inserted in your DB table with your existing code. After it place your code to fetch records from DB. your HTML will be sent in the response and place that HTML in the DIV with your existing jquery code.
you can use jquery load function for it, its very easy for you
http://www.w3schools.com/jquery/jquery_ajax_load.asp
just load a div from there to a div in current page
follow this url for the video tutorial, its very simple, use a div here then enter the id and in the page you are loading, please use another id and load that id into this page div
https://www.youtube.com/watch?v=mtz8MdQXhno
it works in wordpress and will simply work in php
same code
I want to refresh on the same page.I have script that allows the user to add in values in a text field then onclick displays the list at the bottom the same page.I want add in values on the same page. The array is not updating as I click and php.net is been blocked over my side.
<?php
session_start();
$_SESSION['mylist'] ;
$mylist = array();
?>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<form id="form1" name="form1" method="GET" action="">
<tr>
<td width="30%">
<label for="ref_num">Custom Number</label>
<input type="text" name="ref_num" id="ref_num" />
</td>
<td width="70%"><input name="Add" type="submit" value="Add" /></td>
</tr>
</form>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
<?php
if(isset($_GET['Add']))
{
$ref_num=$_GET['ref_num'];
$_SESSION['store'] = $ref_num;
}
array_push($_SESSION['mylist'],$_SESSION['store']);
echo '<pre>';
echo print_r($_SESSION['mylist']);
echo '</pre>';
?>
This is how you do it:
<?php
// Start PHP Session
session_start();
// Init List Array In Session
if (!isset($_SESSION['mylist'])) {
$_SESSION['mylist'] = array();
}
// Handle Set Data Via GET
if (isset($_GET['ref_num']))
{
// Append Data
$ref_num = trim($_GET['ref_num']);
if (!in_array($ref_num, $_SESSION['mylist'])) {
$_SESSION['mylist'][] = $ref_num;
}
}
?>
<form id="form1" name="form1" method="GET" action="">
<input type="text" name="ref_num" id="ref_num" />
<input name="Add" type="submit" value="Add" />
</form>
<?php
// Display Current Data (if Any)
if (isset($_SESSION['mylist'])) {
echo 'Data In Session So Far:<br /><br /><pre>';
print_r($_SESSION['mylist']);
echo '</pre>';
}
?>
Dont know what you try there. You try to save the array within "$_SESSION", and then you want to use $_GET to obtain the values?
You should take a closer look on $_GET, they are added in the url like this:
www.example.com?key=value
If you use $var = $_GET['key'] now, it will return "value".
remove the
echo '<pre>';
echo print_r($_SESSION['mylist']);
echo '</pre>';
echo from the middle line of content becuase print_r also print the records of array