i created a table with the help of kendoGrid data table plugin in which i perform a delete after the delete table sholud get reload and do not the show the deleted user but table doesnot reload and still showing the user in table when i refresh the page the user details will be gone i have tired the following code but it is not working
Note:delete operation is working properly
<head>
<script>
$(function () {
$("#example").dataTable();
})
</script>
<script>
$(document).ready(function () {
$("#example").kendoGrid({dataSource: {
pageSize: 10
},
editable: "popup",
sortable: true,
filterable: {
extra: false,
operators: {
string: {
contains: "Contains",
startswith: "Starts with"
}
}
},
pageable: true,
});
});
</script>
<script>
function deleteuser(obj) {
var uid = obj.id;
var uname = obj.name;
if (confirm("This user '" + uname + "' maybe using some other events, Are you sure to delete this user?")) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
//alert(xmlhttp.responseText.trim());
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//alert(xmlhttp.responseText.trim());
if (xmlhttp.responseText.trim() == 'deleted') {
alert('This user "' + uname + '" succesfully deleted');
$('#example').data('kendoGrid').dataSource.read();
} else
alert('Error : user cannot deleted');
}
}
var url = "deleteuser.php?id=" + uid;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<div>
<table id="example">
<thead>
<tr>
<td>Action</td>
<td>Name</td>
<td>Username</td>
<td>Email</td>
</tr>
</thead>
<tbody>
<?php
$sql = "SELECT * from registration";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td><button class="btn btn-danger btn-xs" id="<?php echo $row['user_id'] ?>" onClick="deleteuser(this);" name="<?php echo $row['first_name'] ?>" title="Delete"><i class="fa fa-trash-o"></i></button></td>
<td><?php echo $row['first_name'] ?></td>
<td><?php echo $row['user_name'] ?></td>
<td><?php echo $row['email'] ?></td>
<?php
}
?>
</tr>
</tbody>
</table>
</div>
</body>
deleteuser.php
<?php
session_start();
$id = $_GET['id'];
include("../model/functions.php");
$table = "registration";
$condition = "user_id=" . $id . "";
$delete = Deletedata($table, $condition);
if ($delete === TRUE) {
echo'deleted';
} else {
echo 'not deleted';
}
?>
You are not be able to update the table data as is because you have not defined where the table gets the data. The can either refresh the entire page, or create a datasource with a transport & url that you can use to get the data.
When you populate the table server side:
<tbody>
<?php
$sql = "SELECT * from registration";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
?>
<tr>
<td><button class="btn btn-danger btn-xs" id="<?php echo $row['user_id'] ?>" onClick="deleteuser(this);" name="<?php echo $row['first_name'] ?>" title="Delete"><i class="fa fa-trash-o"></i></button></td>
<td><?php echo $row['first_name'] ?></td>
<td><?php echo $row['user_name'] ?></td>
<td><?php echo $row['email'] ?></td>
<?php
}
?>
</tr>
</tbody>
There is nothing for the table to refresh.
You need to add a source of data for the table to get the data from.
Ordinarily, I define the datasource for the grid separate from the grid definition itself.
As an example:
var gridDataSource = new kendo.data.DataSource({
transport: {
read: {
url: "someurl/to/my/data"
}
},
schema: {
model: { id: "user_id" }
}
});
Then you can define your table something like this:
var jgrid = $("#example").kendoGrid({
columns: [
{
field: "first_name",
title: "First Name"
},
{
field: "user_name",
title: "User Name",
},
{
field: "email",
title: "Email"
}
],
dataSource: gridDataSource
}).data("kendoGrid");
$('#GridName').data('kendoGrid').dataSource.read();
$('#GridName').data('kendoGrid').refresh();
Related
I have a little trouble with my PHP, js code. When I submit form page is reloading but input checkbox isn't in checked mode, but I need is.
I think maybe I need to get parameter from URL and then compare it with the DOM element and after that set checked mode for input?
PHP code:
if(isset($_GET['user_id'])) {
try {
$PDO_connection = new PDO($dsn, $user, $password, $opt);
$queryForUserInfo = "SELECT position, dateOfBirth, rank, tellNumber, worker_id
FROM workers
WHERE user_id = :id";
$sth = $PDO_connection->prepare($queryForUserInfo);
$sth->bindParam(":id", $_GET['user_id'], PDO::PARAM_STR);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
$queryForComeAndReturnUserInfo = "SELECT date_come, date_return
FROM outside_records
WHERE worker_id = {$result[0]['worker_id']}
ORDER BY date_return DESC";
$sth1 = $PDO_connection->prepare($queryForComeAndReturnUserInfo);
$sth1->bindParam(":id", $_GET['user_id'], PDO::PARAM_STR);
$sth1->execute();
$outsideSchedule = $sth1->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e){
echo $e->getMessage();
};
}
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="get" id="listOfUsers_form">
<!--just for getting id to make db query-->
<?php foreach ($AllUsers as $user):?>
<tr class='usersList'>
<td><input type='checkbox' name='user_id' value='<?php if(isset($user)){echo $user['user_id'];}?>'></td>
<td><?php echo $user['name'];?></td>
<td><?php echo $user['surname'];?></td>
<td><?php echo $user['position'];?></td>
</tr>
<?php endforeach; ?>
</tbody>
</form>
js code:
<script>
$(document).ready(function(){
let row = $('#colorful_row').html();
if(row == "Відсутній на робочому місті") {
$("#status").css("background-color", "red");
} else if (row == "На робочому місці") {
$("#status").css("background-color", "lightgreen");
} else {
$("#status").css("background-color", "white");
}
$(".usersList td input:checkbox").on("change", function(){
$(this.attr("checked", "checked"));
$("#listOfUsers_form").submit();
});
});
</script>
Thanks, everybody
Use localStorage
Demo
For localstorage saved the boolean value as string .That why we compare with localStorage.getItem("box") == 'true'
$('input').prop('checked', localStorage.getItem("box") == 'true')
$('input').on('change', function() {
window.localStorage.setItem($(this).attr('name'), Boolean($(this).is(':checked')))
})
I'm writing a code to add the dynamic fields and save them to the database, but when I save it's not getting saved, below is my code, can anyone please tell what am I doing wrong
This is a plugin code where in I have added the form to dynamically add fields and save it data
This is form code:
<?php
/*
Plugin Name: Link Changer
Description: Changes the button link after certain clicks
Version: 1.0
Text Domain: button-link-changer
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
add_action( 'admin_menu', 'link_changer_menu' );
$con = mysqli_connect('localhost','aejaz_wp1','Q.gslkbUNCOT2zZUVSw82','aejaz_wp1');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
else{
echo '';
}
global $jal_db_version;
$jal_db_version = '1.0';
function jal_install() {
global $wpdb;
global $jal_db_version;
$table_name = $wpdb->prefix . 'liveshoutbox';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
links varchar(55) DEFAULT '' NOT NULL,
hitsmade mediumint(9) NOT NULL,
hitstocount mediumint(9) NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
add_option( 'jal_db_version', $jal_db_version );
}
function jal_install_data() {
global $wpdb;
$welcome_name = 'Mr. WordPress';
$welcome_text = 'Congratulations, you just completed the installation!';
$table_name = $wpdb->prefix . 'liveshoutbox';
$wpdb->insert(
$table_name,
array(
'time' => current_time( 'mysql' ),
'name' => $welcome_name,
'text' => $welcome_text,
)
);
}
register_activation_hook( __FILE__, 'jal_install' );
register_activation_hook( __FILE__, 'jal_install_data' );
function link_changer_menu(){
$page_title = 'Link Changer';
$menu_title = 'Button Link Changer';
$capability = 'manage_options';
$menu_slug = 'Button-Link-Changer';
$function = 'extra_post_info_page';
$icon_url = 'dashicons-media-code';
$position = 6;
add_menu_page( $page_title,
$menu_title,
$capability,
$menu_slug,
$function,
$icon_url,
$position );
add_action( 'admin_init', 'link_register_settings' );
}
function link_register_settings() {
// Let's create and register the Sections.
// - register_setting( $option_group, $option_name, $sanitize_callback );
register_setting('button-link-changer', 'link_options', 'link_options_sanitize');
}
//to save options as array create input fields
function bp_options_sanitize($input){
$input['link_one'] = sanitize_text_field($input['link_one']);
$input['link_two'] = sanitize_text_field($input['link_two']);
$input['link_hits'] = sanitize_text_field($input['link_hits']);
$input['links'] = sanitize_text_field($input['links']);
return $input;
} // end link_options_sanitize
// Let's create the Main Page
function extra_post_info_page(){
#saving plugin options to database from form ?>
<h1>Button Link Changer</h1>
<form method="post" action="options.php">
<?php settings_fields( 'button-link-changer' ); ?>
<?php //do_settings_sections( 'button-link-changer' ); ?>
<?php $link_options = get_option('link_options') ?>
<table class="form-table">
<tr valign="top">
<th scope="row">Link one</th>
<td>
<input type="text" name="link_options[link_one]" value="<?php echo esc_attr($link_options['link_one']); ?>" />
</td>
</tr>
<tr valign="top">
<th scope="row">Link two</th>
<td>
<input type="text" name="link_options[link_two]" value="<?php echo esc_attr($link_options['link_two']) ?>" />
</td>
</tr>
<tr valign="top">
<th scope="row">Link Hits</th>
<td>
<input type="text" name="link_options[link_hits]" value="<?php echo esc_attr($link_options['link_hits']) ?>" />
</td>
</tr>
</table>
<?php submit_button(); ?>
</form>
<form name="add_me" id="add_me">
<table id="dynamic">
<input type="text" name="name[]" placeholder="Enter Your Name" />
<button type="button" name="add" id="add_input">Add</button>
</table>
<input type="button" name="submit" id="submit" value="Submit" />
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-rc1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var i = 1;
$('#add_input').click(function() {
i++;
$('#dynamic').append('<tr id="row' + i + '" ><td><input type="text" name="name[]" placeholder="Enter Your Name"/></td><td><button type="button" name="remove" id="' + i + '" class="btn_remove">Remove</button></td></tr>');
});
$(document).on('click', '.btn_remove', function() {
var button_id = $(this).attr("id");
$('#row' + button_id + '').remove();
});
$('#submit').click(function() {
$.ajax({
url: "insert.php",
method: "POST",
data: $('#add_me').serialize(),
success: function(data) {
alert(data);
$('#add_me')[0].reset();
}
});
});
});
</script>
<?php
//fetching data from database
global $wpdb;
$results = $wpdb->get_results( "SELECT option_value FROM $wpdb->options WHERE option_name='link_options'");
if(!empty($results)) {
// output data of each row
$arrayvalues=$results[0]->option_value;
$unserialized_categoriesx = unserialize($arrayvalues);
echo $unserialized_categoriesx['link_one'];
$varlinkone = $unserialized_categoriesx['link_one'];
echo "</br>";
echo $unserialized_categoriesx['link_two'];
$varlinktwo = $unserialized_categoriesx['link_two'];
$unserialized_categoriesx['link_hits'];
$varlinkhits =$unserialized_categoriesx['link_hits'];
}
$hits = 0;
//counting and comparing hits
if ($hits[0]<= $varlinkhits)
{
$buttonlink="$varlinkone";
}
else
{
$buttonlink="$varlinktwo";
}
echo $hits[0];
?>
<a href="<?php echo $_SESSION["button_url"] ?>" >Join Whatsapp Group</a>;
<?php
$_SESSION["button_url"] = $buttonlink;
?>
<?php
}
function link_button_function() {?>
Join Whatsapp Group;
<?php }
add_shortcode('button_link', 'link_button_function');
This is insert.php
<?php
$conn = mysqli_connect("localhost", "root", "", "aejaz_wp1");
$number = count($_POST["name"]);
if($number > 0)
{
for($i=0; $i<$number; $i++)
{
if(trim($_POST["name"][$i] != ''))
{
$sql = "INSERT INTO wp_liveshoutbox(links) VALUES('".mysqli_real_escape_string($conn, $_POST["name"][$i])."')";
mysqli_query($conn, $sql);
}
}
echo "Data Inserted Successfully";
}
else
{
echo "Enter Your Name";
}
?>
I'm trying to solve this problem for a long time and stil have no clue to it.
I am trying to send and catch AJAX request within CodeIgniter framework.
PHP file with page tamplate:
<table id="jivoClients" class="display nowrap" cellspacing="0" width="100%">
<tbody>
<?php foreach($clients as $client): ?>
<td class="details-control" id="<?php echo $client["chat_id"]. ","
.$this->security->get_csrf_token_name(). ","
.$this->security->get_csrf_hash(); ?>"></td>
<th class="clientData"><?php echo str_replace(",", "<br>" , $client["visitor_info"]); ?></th>
<th class="clientData"><?php echo ($client['session_geoip_country']); ?></th>
<th class="clientData"><?php echo ($client['session_geoip_city']); ?></th>
<th class="clientData"><?php echo ($client['visitor_chats_count']); ?></th>
<th class="clientData"><?php echo ($client['agents_names']); ?></th>
<th class="clientData"><?php if(isset($client['messages']['0']['timestamp'])): ?>
<?php echo date('m/d/Y', $client['messages']['0']['timestamp']); ?>
<?php endif;?></th>
<th class="clientData"><?php if(isset($client['messages']['0']['timestamp'])): ?>
<?php echo date('H:i:s', $client['messages']['0']['timestamp']); ?>
<?php endif;?></th>
<th class="clientData"><?php if(isset($client['messages']['0']['Message'])): ?>
<?php echo ($client['messages']['0']['Message']); ?>
<?php endif;?></th>
<th class="clientData"><?php echo ($client['Manager_note']); ?></th>
</tr>
<?php endforeach; ?>
</tbody>
</table>
In my js file code looks like:
var id = $(this).attr('id');
var messageData = id.split(",");
var token = "" + messageData[1];
var post_data = {
'id' : messageData[0],
'csrf_crm' : messageData[2]
}
$.ajax({
type:'POST',
data: {
func : 'getNewLocations',
'id' : messageData[0],
'csrf_crm' : messageData[2]
},
url:'application/controllers/AjaxController.php',
success: function(result, statut) {
if (result == 'add') {
//do something
}
else if (result == 'remove') {
//do something
}
}
});
And I constantly get 403 error. As I already read on forum, it means that my CSRF token is not correct. But it seems that I get it normally (checked in debugger).
However this does not solve the problem.
Thanks in advance.
You need to do echo to assign value of php variable. Also wrap token in ''
var token = '<?php echo $this->security->get_csrf_hash() ?>'; //<----- do echo here
var id = $(this).attr('id');
$.ajax({
type:'POST',
data: {
func : 'getNewLocations',
'id' : id,
'csrf_crm' : token
},
url:'application/controllers/AjaxController.php',
success: function(result, statut) {
if (result == 'add') {
//do something
}
else if (result == 'remove') {
//do something
}
}
});
Get the csrf token value like this:
var token = $('[name="csrf_token"]').val();
Finally I solved this problem.
It appered, that I was using incorrect route in js file.
The correct sequence of actions looks like this:
1) add new line in file routes.php:
$route['jivosite/user'] = 'jivosite/user';
2) add code in js file:
post_data = JSON.stringify(post_data);
post_data = JSON.stringify(post_data);
var url = baseurl + "jivosite/user"
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.addEventListener("readystatechange", function () {
if (xhr.readyState == 4 && xhr.status === 200) {
console.log(xhr.response);
}
});
xhr.addEventListener("error", function (err) {
console.log(err);
});
xhr.send(post_data ? JSON.stringify(post_data) : null);
3) check config.php file.
$config['cookie_secure'] = FALSE; should be like this
and $config['csrf_exclude_uris'] = array('jivosite/user'); should include my route
4) create file Jivosite.php in controllers folder with contents:
class Jivosite extends CI_Controller
{
public function user()
{
$id=$this->input->post('id');
echo $id;
}
}
And it worked for me.
Thanks for all answers.
I want to save checkbox change using ajax.But I can't get any saved changes.
this is the view:actionacces.phtml
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
$title = 'Action \'s acces by role ';
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?></h1>
<table class="table">
<tr>
<th>Action</th>
<?php foreach ($roles as $role) : ?>
<th><?php echo $this->escapeHtml($role['name']); ?> </th>
<?php endforeach; ?>
</tr>
<tr><?php foreach ($actions as $action) : ?>
<th> <?php echo $this->escapeHtml($action['name']);
'<\br>' ?></th>
<?php
foreach ($roles as $role) :
$exist = 0;
foreach ($acls as $acl) :
if ($acl['fk_role_id'] == $role['id'] && $acl['fk_action_id'] == $action['id'] && $acl['acces'] == 1) {
$exist = 1;
}
endforeach;
?>
<th> <?php if ($exist == 1) { ?>
<label class="css-input switch switch-sm switch-primary push-10-t">
<input type='checkbox' class="checkboxAccess" id_role="<?= $role['id'] ?>" id_action="<?= $action['id'] ?>" acces="<?= $exist ?>" checked><span></span>
</label>
<?php } else { ?>
<label class="css-input switch switch-sm switch-primary push-10-t">
<input type="checkbox" class="checkboxAccess" id_role="<?= $role['id'] ?>" id_action="<?= $action['id'] ?>" acces="<?= $exist ?>" > <span></span>
</label>
</th>
<?php }
endforeach;
?>
</tr>
<?php endforeach; ?>
</table>
this is the droit.js:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
$(document).ready(function () {
$(".checkboxAccess").on('click', function () {
// console.log($(this).attr("id_role"));
// var role_id = $(this).attr("id_role");
// var action_id = $(this).attr("id_action");
// var droit = $(this).is(':checked');
console.log($(this).attr("id_role"));
var role_id = $(this).attr("id_role");
var action_id = $(this).attr("id_action");
var acces = $(this).is(':checked');
// alert(role_id);
// alert(action_id);
$.ajax({
type: "POST",
// url:'Privilege/ACL/addACL',
url: 'Detect/Acl/modifrole',
// data: {
// "id_role": role_id,
// "id_action": action_id,
// "droit": droit},
data: {
"id_role": role_id,
"id_action": action_id,
"acces": acces
},
Success: function (result) {
alert('Success');
console.log(result);
},
Error: function () {
alert('Error');
}})
});
});
this function in controller:
public function modifroleAction() {
$request = $this->getRequest();
// echo'<pre>'; print_r($this->getRequest());die;
if ($request->isPost()) {
$parametres = $this->params()->fromPost();
$acl = new Acl();
$acl->fk_role_id = $parametres['role_id'];
$acl->fk_action_id = $parametres['action_id'];
$acces = $parametres['acces'];
if ($acces == "false") {
$acl->acces = 0;
} else {
$acl->acces = 1;
}
$this->getAclTable()->saveAcl($acl);
return $this->redirect()->toRoute('acl');
}
}
Can you help me ?
You are trying to get data by $parametres['role_id'] and $parametres['action_id'] that means role_id and action_id
But you sending -
data: {
"id_role": role_id,
"id_action": action_id,
"acces": acces
},
that means id_role, and id_action.
Change your post index may work.
Script:
$('.removeVehicle').click(function() {
var $this = $(this),
$row = $(this).parent().parent();
alert($row.attr('data-vehicle-id'));
if (confirm("Delete vehicle? ") == true) {
$.post("removevehicle.php", {Id: $row.attr('data-vehicle-id')});
};
});
HTML/PHP:
<?php while ($row = $products->fetch_assoc()) { ?>
<tr data-vehicle-id="<?= $row['Vehicle_ID']?>">
<td class="VRM"><?= $row['VRM']; ?></td>
<td class="Make"><?= $row['Make']; ?></td>
<td class="Model"><?= $row['Model']; ?></td>
<td class="Colour"><?= $row['Colour']; ?></td>
<td class="Mileage"><?= $row['Mileage']; ?></td>
<td class="Advertised Price">£<?= $row['Advertised_Price']; ?></td>
<td class="Date of Registration"><?= $row['Date_of_Registration']; ?></td>
<td class="HPi Status"><?= $row['HPI_Status']; ?></td>
<td class="actions">
<button class="editLine">Edit line</button>
<button class="saveLine hide">Save line</button>
<button class="startSale" onclick="div_showSale()">Start Sale</button>
<button class="removeVehicle"><img id="trash" src="images/trash.png" alt="Delete Vehicle" height=20 width=20></button>
</td>
</tr>
<?php } ?>
removevehicle php:
<?php
require 'config/init.php';
if (isset($_SESSION['myusername'])) {
$mysqli = new mysqli($db['hostname'], $db['username'], $db['password'], $db['database']);
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$queryStr = "DELETE FROM VEHICLE WHERE Vehicle_ID = '" . $_POST['Id'] . "'";
$query = $mysqli->query($queryStr);
}
Works up to the point of the alert with the vehicle ID (correct vehicle ID is alerted). Essentially all I need to do is delete the vehicle/record from the database - any better suggestions or how to get the current method working?
Once I've got this working, I'll change the MySQLi query to counteract injection (it's not live yet).
obtain your data attribute information using .data() . Also return your PHP results and dump it to the console. Lastly, check your console for errors. Use this instead:
PHP:
$query = $mysqli->query($queryStr);
echo $query;
JS:
$('.removeVehicle').click(function() {
var $this = $(this),
$row = $(this).parent().parent();
var vehicle_id = $row.data("vehicle-id");
if (confirm("Delete vehicle? ") == true) {
$.post("removevehicle.php", {Id: vehicle_id}, function(result) {
console.log(result);
});
}
});
I think it the issue is with the sql query and wrapping the vehicle_id in quotes?
If you need to delete the row after you'll want to do it in a callback like this:
$.post("removevehicle.php", {Id: $row.attr('data-vehicle-id')}, function() {
// delete the row
});