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.
Related
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 have an admin panel for an application. For this admin panel, the admin has the option to select a user from a dropdown list. When the user is selected, I use an AJAX call to grab the users data and store it in a variable called $result. Now when I try to access $result outside of the if statement in my HTML file, it is not recognized. What are the possible ways I can access this variable?
HTML file (AJAX call)
$(document).ready(function(){
$('#user').change(function() {
var user_id = $(this).val();
$.ajax({
url: 'adminNew.php',
method:'POST',
data: {user_id : user_id},
success: function(data) {
alert(user_id);
}
});
});
});
Php file (if statement)
if (isset($_POST["user_id"])) {
if ($_POST["user_id"] != '') {
$sql = "SELECT * FROM user_data WHERE user_id ='".$_POST["user_id"]."'";
}
$result = mysqli_query($connect, $sql);
}
HTML file (table)
<tr>
<tbody id="expBody">
<?php
if ($result != ''){
while($row1 = mysqli_fetch_array($result)) {
echo '
<tr id = '.$row1["id"].'>
<td> '.$row1['user_id'].'</td>
<td> '.$row1['name'].'</td>
<td> '.$row1['email'].'</td>
<td> '.$row1['city'].'</td>
<td> '.$row1['state'].'</td>
<td> '.$row1['zip'].'</td>
';
}
}
?>
</tbody>
</tr>
Your PHP code needs to send something back to the ajax request
i have seen this done as below before
if (isset($_POST["user_id"])) {
if ($_POST["user_id"] != '') {
$sql = "SELECT * FROM user_data WHERE user_id ='".$_POST["user_id"]."'";
}
$result = mysqli_query($connect, $sql);
echo $result;
die;
}
you can load the new table into your #expBody via jquery:
$('#user').change(function() {
var user_id = $(this).val();
$("#expBody").load("yourphpfile.php?userid="+userid);
});
and in your phpfile you actualy "make" the table out of the result..
<?php
$userid = $_GET["userid"];
// make your db query
if ($result != ''){
while($row1 = mysqli_fetch_array($result)) {
echo '
<tr id = '.$row1["id"].'>
<td> '.$row1['user_id'].'</td>
<td> '.$row1['name'].'</td>
<td> '.$row1['email'].'</td>
<td> '.$row1['city'].'</td>
<td> '.$row1['state'].'</td>
<td> '.$row1['zip'].'</td>
';
}
}
?>
that way, this table will be put into your div!
I want when I add a product to the cart and reload the same page, but the problem did not this product.
The controller
public function detail()
{
$data=array('title' =>'Ecommerce Online | Detail Product',
'username' => $this->session->userdata('id'),
'categories' => $this->categories_model->get_categories(),
'details' => $this->categories_model->get_details($this->uri->segment(3)),
'isi' =>'member/detail');
$this->load->view('template_home/wrapper',$data);
}
function addtocart()
{
if($this->cart_model->validate_add_cart_item() == TRUE){
if($this->input->post('ajax') != '1'){
redirect('member/detail/'); // this problem
}else{
echo 'true';
}
}
}
I add my models
function validate_add_cart_item()
{
$id = $this->input->post('product_id');
$cty = $this->input->post('quantity');
$this->db->where('productID', $id);
$query = $this->db->get('product', 1);
if($query->num_rows > 0){
foreach ($query->result() as $row)
{
$data = array(
'id' => $id,
'qty' => $cty,
'price' => $row->price,
'name' => $row->productName
);
$this->cart->insert($data);
return TRUE;
}
}else{
return FALSE;
}
}
I add my view
<?php foreach ($details as $s) { ?>
<div class="col-md-5">
<div class="box text-center">
<img src="<?php echo base_url('upload/'.$s->photo); ?>" width="150px" height="150px">
<br><?php echo $s->productName; ?>
<br><strong>Rp. <?php echo $s->price; ?></strong>
<br>
<?php echo form_open('member/add'); ?>
<fieldset>
<label>Quantity</label>
<?php echo form_input('quantity', '1', 'maxlength="2"'); ?>
<?php echo form_hidden('product_id', $s->productID); ?>
<?php echo form_submit('add', 'Add'); ?>
</fieldset>
<?php echo form_close(); ?>
</div>
</div>
<?php } ?>
Jquery script
<script type="text/javascript">
$(document).ready(function() {
/*place jQuery actions here*/
var link = "<?php echo site_url('member/detail')?>/"; // Url to your application (including index.php/)
$(".detail-product").submit(function(){
var id = $(this).find('input[name=product_id]').val();
var qty = $(this).find('input[name=quantity]').val();
$.post(link + "member/add", { product_id: id, quantity: qty, ajax: '1' },
function(data){
if(data == 'true'){
$.get(link + "member/detail", function(cart){ // Get the contents of the url cart/show_cart
$("#cart_content").html(cart); // Replace the information in the div #cart_content with the retrieved data
});
}else{
alert("Product does not exist");
});
return false; // Stop the browser of loading the page defined
});
});
</script>
This is problem url: http://localhost/scientificwriting/member/detail/ and productid can not be invoked. Do I need to replace the IF statement on my controller and my jquery?
Please help me thanks
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();
i did some coding to group the product attributes on frontend and show their groups names above theme like this:
attgroup 1
attribute 1
attribute 2
...
attgroup 2
attribute 3
attribute 4
...
I added /app/code/local/Mage/Catalog/Block/Product/View/Attributesgroups.php with the following code:
<?php
class Mage_Catalog_Block_Product_View_Attributesgroups extends Mage_Core_Block_Template
{
protected $_product = null;
function getProduct()
{
if (!$this->_product) {
$this->_product = Mage::registry('product');
}
return $this->_product;
}
public function getAdditionalData(array $excludeAttr = array())
{
$data = array();
$product = $this->getProduct();
$attributes = $product->getAttributes();
foreach ($attributes as $attribute) {
if ($attribute->getIsVisibleOnFront() && !in_array($attribute->getAttributeCode(), $excludeAttr)) {
$value = $attribute->getFrontend()->getValue($product);
// TODO this is temporary skipping eco taxes
if (is_string($value)) {
if (strlen($value) && $product->hasData($attribute->getAttributeCode())) {
if ($attribute->getFrontendInput() == 'price') {
$value = Mage::app()->getStore()->convertPrice($value,true);
} elseif (!$attribute->getIsHtmlAllowedOnFront()) {
$value = $this->htmlEscape($value);
}
$group = 0;
if( $tmp = $attribute->getData('attribute_group_id') ) {
$group = $tmp;
}
$data[$group]['items'][ $attribute->getAttributeCode()] = array(
'label' => $attribute->getFrontend()->getLabel(),
'value' => $value,
'code' => $attribute->getAttributeCode()
);
$data[$group]['attrid'] = $attribute->getId();
}
}
}
}
// Noch Titel lesen
foreach( $data AS $groupId => &$group ) {
$groupModel = Mage::getModel('eav/entity_attribute_group')->load( $groupId );
$group['title'] = $groupModel->getAttributeGroupName();
}
return $data;
}
}
Then, I created the /app/design/frontend/MY_TEMPLATE/default/template/catalog/product/view/attributesgroups.phtml file with the following content:
<?php
$_helper = $this->helper('catalog/output');
$_product = $this->getProduct()
?>
<?php if($_additionalgroup = $this->getAdditionalData()): ?>
<div class="box-collateral box-additional">
<h2><?php echo $this->__('Additional Information') ?></h2>
<?php $i=0; foreach ($_additionalgroup as $_additional): $i++; ?>
<h3><?php echo $this->__( $_additional['title'] )?></h3>
<table class="data-table" id="product-attribute-specs-table-<?php echo $i?>">
<col width="25%" />
<col />
<tbody>
<?php foreach ($_additional['items'] as $_data): ?>
<tr>
<th class="label"><?php echo $this->htmlEscape($this->__($_data['label'])) ?></th>
<td class="data"><?php echo $_helper->productAttribute($_product, $_data['value'], $_data['code']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<script type="text/javascript">decorateTable('product-attribute-specs-table-<?php echo $i?>')</script>
<?php endforeach; ?>
</div>
<?php endif;?>
Last step was to modify /app/design/frontend/default/YOUR_TEMPLATE/layout/catalog.xml in line 223, and replaced
<block type="catalog/product_view_attributes" name="product.attributes" as="additional" template="catalog/product/view/attributes.phtml">
with
<block type="catalog/product_view_attributesgroups" name="product.attributes" as="additional" template="catalog/product/view/attributesgroups.phtml">
i did this but nothing is changed on product attribute tap on frontend product page.
im using magento 1.9.1 ce and custom template
First try to simple way
foreach($product->getAttributes() as $att){
$group_id = $att->getData('attribute_group_id');
$group = Mage::getModel('eav/entity_attribute_group')->load($group_id); var_dump($group);
}
or please try to below code....
Get attribute set ID programmatically..
$sDefaultAttributeSetId = Mage::getSingleton('eav/config')
->getEntityType(Mage_Catalog_Model_Product::ENTITY)
->getDefaultAttributeSetId();
Get group name programmatically..
$attributeSetId = 10;
$groups = Mage::getModel('eav/entity_attribute_group')
->getResourceCollection()
->setAttributeSetFilter($attributeSetId)
->setSortOrder()
->load();
$attributeCodes = array();
foreach ($groups as $group) {
echo $groupName = $group->getAttributeGroupName();
$groupId = $group->getAttributeGroupId();
}