How to get CSS on-off button value in PHP page? - javascript

Well,
I have this code which generate CSS on-off button in a php while loop:
<div class="onoffswitch">
<input type="hidden" name="hiddenID" value="<?php echo $id; ?>">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch<?php echo $i ?>" <?php echo $status; ?>>
<label class="onoffswitch-label" for="myonoffswitch<?php echo $i; ?>">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div>
When the on-off button changes then I am calling a PHP page using jQuery/Ajax.
jQuery/Ajax Code:
$(document).ready(function () {
$(".onoffswitch").change(function() {
var hiddenID = $(this).find("[name='hiddenID']").val()
var status = $('.onoffswitch-checkbox').val();
$.ajax({
type: 'post',
url: 'changeInlineData.php',
data: {
'id' : hiddenID,
'status' : status,
},
dataType : 'html',
success: function ( result ) {
$('.validation_msg').html(result);
}
});
});
});
Here you can see I just pass 2 key which is id and status in a php page. Now in php page I see the id value only not status value. Everytime status key is showing 0. It's should be 0 or 1.
PHP page:
<?php
echo $id = (int) $_POST['id'];
echo $status = (int) $_POST['status'];
Can you tell me what I am doing wrong?
Update:
I see in console log network tab that is showing status:on always if I toggle the button to on or off!!
Form Data
id:2203
status:on

You have to take value of checked checkbox. Change your status var in jquery as below :
var status = $('.onoffswitch-checkbox:checked').val();

Related

Unable to get button value/attribute in jquery using php loop

I'm working on "like" and "dislike" module in jQuery with PHP,And I'm facing these two problems:
Right now unable to get id of button (like=1, dislike=0)
Query showing correct result but how to display ajax response under "like dislike" section ?
Here is my code, following code inside foreach loop:
<?php foreach // ?>
<form class="form-horizontals1" method="post" >
<input type="hidden" id="ReviewId" name="ReviewId" value="<?php echo $rev->id;?>">
<button class="likebutn_r" id="show<?php echo "1";?>" type="submit"><img src="<?php echo base_url(); ?>/assets/img/thumb.png" height="24" width="24"></button>
<label class="lilkcount">10(dynamic) </label>
<button class="likebutn_r" id="shows<?php echo "0";?>" type="submit"><img src="<?php echo base_url(); ?>/assets/img/thumbdown.png" height="24" width="24"></button>
<label class="lilkcount">5(dynamic)</label>
<div id="counter"></div>
</form>
<?php end foreach // ?>
<script type="text/javascript">
$(document).ready(function(){
//likebutn_r
$('.form-horizontals1').submit(function(e){
var ids = $(this).attr('ids');
console.log(ids);
alert($(this).attr("id"));
e.preventDefault();
$.ajax({
url:'<?php echo base_url();?>main/AddVote',
type:"post",
data:new FormData(this),
//dataType: 'json',
processData:false,
contentType:false,
cache:false,
async:false,
success: function(data){
console.log(data);
alert(data);
$('#counter').html(data);
}
});
});
});
</script>
Here is my controller code, please tell me how I can get "like dislike" value in script and how I can show result in views ?
function AddVote()
{
$ReviewId=$_POST['ReviewId'];
$vote=$_POST['vote'];
echo $result['TotalUpVotes'] = $this->M_main->CountSubmittedCoinVote($ReviewId,$vote);
echo $result['TotalDownVotes'] = $this->M_main->CountSubmittedDownVotes($ReviewId,$vote);
}
First, move the form ouside the loop.
<form class="form-horizontals1" method="post" >
<?php foreach // ?>
<div class="my-rev-container js-rev-container">
...
</div>
<?php end foreach // ?>
</form>
Add a class to the inputs, you whould access with
<input type="hidden" class="js-form__rev" id="ReviewId" name="ReviewId" value="<?php echo $rev->id;?>">
Finaly access them
$('.form-horizontals1').submit(function(e){
var ids = $(this).find(".js-form__rev");
console.log(ids);

Can I use php and javascript create form edit data?

I want to create form for edit data from MySQL with javascript. when I click link Edit it will show edit form for edit data.
This is from and php code for show data.
<form id="form-edit" method="post">
<?php
$sql = "SELECT * FROM comment WHERE question_id = $question_id ORDER BY id DESC";
$r1 = mysqli_query($link, $sql);
while($cm = mysqli_fetch_array($r1)) {
$comment_id = $cm['id'];
echo '<section class="section-comment">';
echo '<span class="commentator">' .$cm['user_id'] . '</span>';
echo $cm['detail'];
// This is link Edit
echo 'Edit';
echo $comment_id; //This can show correct comment_id
?>
<div id="form-edit-dialog">
<input type="text" name="user_id" value="<?php echo $user_id ?>" readonly > <br>
//I add this line for check comment_id but it show max comment_id to min when I open and close form
<input type="text" name="id" value="<?php echo $comment_id ?>" readonly > <br>
<textarea name="detail"></textarea><br>
<button type="submit" id="submit-edit">Submit</button>
<input type="hidden" name="comment_id" id="comment-id">
}
</form>
</div>
I write code java script like this.
$(function() {
$('a.edit-comment').click(function(event) { //Click link Edit
$('#form-edit')[0].reset();
event.preventDefault();
var t = "Edit Comment";
$('#form-edit-dialog').dialog({
width: '600px',
title: t,
modal: true,
position: { my: "center", at: "center", of: window}
});
//set value for hidden
$('#comment-id').val($(this).attr('edit-id'));
});
$('#submit-edit').click(function() {
$('form#form-edit').ajaxForm({
url: 'save-edit.php',
type: 'post',
dataType: 'script',
beforeSend: function() {
$.blockUI({message:'<h3>Sending data...</h3>'});
},
complete: function() {
$.unblockUI();
}
});
});
});
PHP can list all comment and show comment_id correctly but when I click at Edit , it show max number of comment_id and when I close form and click Edit again. The comment_id will reduce comment_id number untill no comment_id.
Can I use php and javascript create form edit data or I have to send data to new page?
if the user has the right to comment it means he is logged, so basically you can get the id from session, cookie; doesn't make sens to extract here the user id OR you can make the check if he has the right to comment ( user_id is same with session one).
just make the switch between and like this:
<
<div id="showtext<?php echo $comment_id ?>" >
<span id="comment<?php echo $comment_id ?>"><?php echo $cm['detail'] ?></span>
Edit
<div>
<!-- this is invisible at start -->
<div id="showedit<?php echo $comment_id ?>" style="display:none">
<textarea id="edittext<?php echo $comment_id ?>"><?php echo $cm['detail'] ?></textarea>
Save comment
</div>
and javascript to toggle views:
$('.edit-comment').click(function() {
var id=$(this).attr("id");
$("#showedit"+id).show();
$("#showtext"+id).hide();
});
and to submit
$('.submit-comment').click(function() {
var id=$(this).attr("id");
var comment=$("#edittext"+id).val();
//send the data via ajax with parameters id and comment to alter the row, in php add the user id from session, cookie and on success:
//replace the old text
$("#comment"+id).html(comment);
//and make the switchback
$("#showedit"+id).hide();
$("#showtext"+id).show();
})

.html file redirect to .php file after clicking a button

<?php
session_start();
include_once("config.php");
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
?>
<!-- View Cart Box Start -->
<?php
if(isset($_SESSION["cart_products"]) && count($_SESSION["cart_products"])>0)
{
echo '<div class="cart-view-table-front" id="view-cart">';
echo '<h3>Your Shopping Cart</h3>';
echo '<form method="post" action="cart_update.php">';
echo '<table width="100%" cellpadding="6" cellspacing="0">';
echo '<tbody>';
$total =0;
$b = 0;
foreach ($_SESSION["cart_products"] as $cart_itm)
{
$product_name = $cart_itm["product_name"];
$product_qty = $cart_itm["product_qty"];
$product_price = $cart_itm["product_price"];
$product_code = $cart_itm["product_code"];;
$bg_color = ($b++%2==1) ? 'odd' : 'even'; //zebra stripe
echo '<tr class="'.$bg_color.'">';
echo '<td>Qty <input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
echo '<td>'.$product_name.'</td>';
echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /><strong>Remove</strong></td>';
echo '</tr>';
$subtotal = ($product_price * $product_qty);
$total = ($total + $subtotal);
}
echo '<td colspan="4">';
echo '<button type="submit">Update</button>Checkout';
echo '</td>';
echo '</tbody>';
echo '</table>';
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
}
?>
<!-- View Cart Box End -->
<!-- Products List Start -->
<?php
$results = $mysqli->query("SELECT product_code, product_name, product_desc, product_img, price FROM products ORDER BY id ASC");
if($results){
$products_item = '<ul class="products">';
//fetch results set as object and output HTML
while($obj = $results->fetch_object())
{
$products_item .= <<<EOT
<li class="product">
<form method="post" action="cart_update.php">
<div class="product-content"><h3><strong>{$obj->product_name}</strong></h3>
<div class="product_img"><img src="product_images/{$obj->product_img}"class="img-responsive img-thumbnail" width="150px" height="150px"></div>
<div class="product-desc">{$obj->product_desc}</div>
<div class="product-info">
<div class="product-price"><strong>
Price {$currency}{$obj->price}
</strong>
</div>
<fieldset>
<label>
<span>Quantity</span>
<input type="text" size="2" maxlength="2" name="product_qty" value="1" />
</label>
</fieldset>
<input type="hidden" name="product_code" value="{$obj->product_code}" />
<input type="hidden" name="type" value="add" />
<input type="hidden" name="return_url" value="{$current_url}" />
<div align="center"><button type="submit" class="add_to_cart">Add to cart</button></div>
</div></div>
</form>
</li>
EOT;
}
$products_item .= '</ul>';
echo $products_item;
}
?>
Im developing a ecommerce website. I'm new to AJAX.I don't know how to solve this problem. In index.html i put ajax code to load the index.php inside the html body. And when i click "add to cart" "checkout" "update" button its redirecting to index.php instead staying on index.html.
UPDATED*
<script >
function load_data(){
$.ajax({
url: "index.php",
dataType: 'html',
cache: false,
success: function(data){
$("#mydiv").html(data);
}
});
}
$(document).ready(function(){
load_data();
});
</script>
index.html
index.php
The jQuery $.ajax() function is used to perform an asynchronous HTTP request. It was added to the library a long time ago, existing since version 1.0. The $.ajax() function is what every function discussed in the previously mentioned article calls behind the scene using a preset configuration. The signatures of this function are shown below:
$.ajax(url[, options])
$.ajax([options])
The url parameter is a string containing the URL you want to reach with the Ajax call, while options is an object literal containing the configuration for the Ajax request.
In its first form, this function performs an Ajax request using the url parameter and the options specified in options. In the second form, the URL is specified in the options parameter, or can be omitted in which case the request is made to the current page.
The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).
In Your case your code should be
$(document).ready(function(){
auto_load();
});
setInterval(auto_load,10000);
function auto_load(){
$.ajax({
url: 'path/to/file/index.php',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
dataType: 'jsonp',
success: function(data) {
alert(data);
//auto_load(); your code assignment and result goes here
},
type: 'GET'
});
}
and also refer https://www.sitepoint.com/use-jquerys-ajax-function/

Failed ajax call within wordpress

I previously had help here making a generic Ajax function for some checkboxes. I am now trying to integrate that project into a Wordpress site and having a few issues.
Here is my current code:
<label class="rep_label"><input type="checkbox" id="goal1<?php get_current_user_id() ?>" name="GOAL_1_HIT" value="1" <?php if($rep_goal1_hit == 'YES'){echo "checked";}?> />
<?php echo $rep_goal1; ?></label>
<br />
<label class="rep_label"><input type="checkbox" id="goal2<?php echo get_current_user_id() ?>" name="GOAL_2_HIT" value="1" <?php if($rep_goal2_hit == 'YES'){echo "checked";}?> />
<?php echo $rep_goal2; ?></label>
<br />
<label class="rep_label"><input type="checkbox" id="goal3<?php echo get_current_user_id() ?>" name="GOAL_3_HIT" value="1" <?php if($rep_goal3_hit == 'YES'){echo "checked";}?> />
<?php echo $rep_goal3; ?></label>
<br />
<label class="rep_label"><input type="checkbox" id="incentive<?php echo get_current_user_id() ?>" name="INCENTIVE_HIT" value="1" <?php if($rep_incentive_hit == 'YES'){echo "checked";}?> />
<?php echo $rep_incentive; ?></label>
JS/Ajax
jQuery(document).ready(function($) {
$("input[type=checkbox]").change(function() {
var $input = $(this);
$.ajax({
url: 'checkbox.php',
type: 'POST',
data: { db_column:$input.attr("name"), strState:$input.is(":checked"), user:"<?php echo $current_user->ID; ?>" },
success: function() { // this happens after we get results
$input.attr('checked', true);
},
error:function(){
$input.attr('checked', false);
}
});
});
});
PHP
<?php
$db_column = $_POST['db_column'];
$strState = $_POST['strState'];
$user = $_POST['user'];
if(set_cimyFieldValue('$user', '$db_column', '$strState')){
echo "ok";
} else {
echo "error";
}
?>
I am getting an "unexpected end of input" error on my javascript that I've googled endlessly to no avail.
I had the script within the html and the Ajax call wasn't even being triggered so I moved it to a .js file and included it in the same spot and now the ajax call goes, but returns a 404 on the php file.
This is only the tip of the iceberg of Ajax I'm going to have to implement. What general considerations do I need to be aware of using my own Ajax functions within Wordpress?
If anyone is familiar with Cimy Extra User Fields, I am merely trying to make an ajax driven front end for the fields provided from that plugin. I think I have problem trying to use a plugin function in my php file...
data: ({ db_column:$input.attr("name"), strState:$input.is(":checked"), user:"<?php echo $current_user->ID; ?>" })

How i can list one rows with foreach?

I have one question for you.
Have this code right now:
<?php
use yii\helpers\Url;
use yii\helpers\Html;
use yii\web\JsExpression;
?>
<form action="<?= Url::to(['/worker/equipment/updatecol']) ?>" id="editcol" method="POST">
<div class="form-group">
<?php foreach($columns as $column) { ?>
<label >Edit title</label>
<input type="text" class="form-control" value="<?= $column->equipment_column_title ?>" name="equipment_column_title" placeholder="Put name.." />
<?php } ?>
</div>
<div class="form-group">
<?php foreach($columns as $column) { ?>
<label>Edit type</label>
<select class="form-control" name="equipment_column_type">
<option value="1" <?php if ($column->equipment_column_type==1) echo "selected='selected'"?>>Int</option>
<option value="2" <?php if ($column->equipment_column_type==2) echo "selected='selected'"?>>Varchar</option>
<option value="3" <?php if ($column->equipment_column_type==3) echo "selected='selected'"?>>Date</option>
<option value="3" <?php if ($column->equipment_column_type==4) echo "selected='selected'"?>>File</option>
</select>
<?php } ?>
</div>
<input type="hidden" name="_csrf" value="<?=Yii::$app->request->getCsrfToken()?>" />
<?php foreach($columns as $column) { ?>
<input type="hidden" name="column" value="<?= $column->equipment_column_id ?>" />
<?php } ?>
<button type="submit" class="btn btn-primary">Update column</button>
</form>
</div>
This is my form for edit choosen column right?
Its yii2 framework and now my problem. This is form for editing my columns, but i dont want list all of fields, but one field i wanna edit. How i do it?
This function is my form controller:
public function actionUpdatecolumnform()
{
$columns = EquipmentColumn :: find() -> all();
return $this->renderAjax('_editcol',['columns'=>$columns]);
}
And this i have for updating columns:
public function actionUpdatecol(){
$model = EquipmentColumn::findOne($_POST['id']);
$model -> equipment_column_title = $_POST['equipment_column_title'];
$model -> equipment_column_type = $_POST['equipment_column_type'];
$model -> update();}
Now we going for jquery, where i have modal.
$('.editcolumn').click(function()
{
var essay_id = $(this).data('id');
$.ajax({
cache: false,
type: 'POST',
url: '".Url::to(['/worker/equipment/updatecolumnform'])."',
data: 'id='+essay_id,
success: function(data)
{
console.log(data);
$('#update_col').modal('show');
$('#edit_col').html(data);
}
});
});
$('#editcol').submit(function(){
var th=$(this);
console.log(th);
$.ajax({
url: '".Url::to(['/worker/equipment/updatecol'])."',
type: 'POST',
data: th.serialize(),
error: function(data,status,text) {alert(text);},
success: function(data) {
var n=noty({
text: '".Yii::t('app', 'Type was saved')."',
type:'success',
layout: 'topCenter',
animation: {
open: 'animated bounceInLeft', // Animate.css class names
close: 'animated bounceOutLeft', // Animate.css class names
easing: 'swing', // unavailable - no need
speed: 500 // unavailable - no need
}
})
}
})
})
This two part of jquery scripts i using for submit edited fields.
My question is: This code list all of columns with titles and types, but i want list only one column with title and type which i want edit.
Thanks for the help :)
I think there is a problem with foreach, but im not sure. :)
You update for given id but render all. With foreach you see all of records. If you want to see just the edited one data record, send one data to view.
$columns = EquipmentColumn::model()->findAllByPk($id);
With that code you get all the infos by given id which belongs to changed record.

Categories

Resources