How to get ajax response using custom attribute in php loop - javascript

I am working with ajax with php,I have following buttons in loop,I just want to
show/fetch data(number) on correct place/div using "attr" in jquery but not working in my side
Here is my button in loop
<?php
foreach //
<button class="btn likebutn_r" data-datac="1" data-datacw="<?php echo $WalletAddress; ?>" data-datacr="<?php echo $rev->id; ?>" data-datacoin="<?php echo $rev->coin_id; ?>" data-datasymbol="<?php echo $rev->symbol; ?>" id="show<?php echo "1";?>" value="1" type="submit"><img src="<?php echo base_url(); ?>/assets/img/thumb.png" height="24" width="24"></button>
<div id="<?php echo $rev->id; ?>">12(dynamic)</div>
endforeach//
Here is my ajax code,How can i get data using custom attribute (via pass ReviewId)? Thanks in advance
<script type="text/javascript">
$(document).ready(function () {
$('.btn').click(function (e) {
var vote = $(this).data('datac');
var review = $(this).data('datacr');
var CoinId = $(this).data('datacoin');
var symbol = $(this).data('datasymbol');
var WalletAddress = $(this).data('datacw');
var datacrp = $(this).data('datacrp');
$('#' + review).hide();
e.preventDefault();
$.ajax({
type: 'POST',
url: '<?php echo base_url();?>main/AddVote',
data: {
vote: vote,
review: review,
CoinId: CoinId,
symbol: symbol,
WalletAddress: WalletAddress
},
success: function (data) {
alert(data);
$('#' + review).html(data);
}
});
});
});
</script>

Hope this code help you.
*Reminder the js code below have to implement inside the php file so the Post url ajax will get the value.
$('body').on('click', '.btn', function(e){
var allData = {
"vote": $(this).data('datac'),
"review": $(this).data('datacr'),
"CoinId": $(this).data('datacoin'),
"symbol": $(this).data('datasymbol'),
"WalletAddress": $(this).data('walletaddress'),
}
e.preventDefault();
$.ajax({
type: 'POST',
url:'test.com',
data: allData,
success: function(data) {
$(this).attr('data-datac', data['vote']);
$(this).attr('data-datacr', data['review']);
$(this).attr('datacoin', data['CoinId']);
$(this).attr('data-datasymbol', data['review']);
$(this).attr('data-datacoin', data['review']);
$(this).attr('data-datasymbol', data['symbol']);
$(this).attr('data-walletaddress', data['WalletAddress']);
}
});
});
<button
class="btn likebutn_r"
data-datac="1"
data-datacw="teste"
data-datacr="asdfasf"
data-datacoin="asdfasdf"
data-datasymbol="asdfasdf"
data-datacrp="asfsa"
id="31"
data-walletaddress="dsaf"
value="1"
type="submit">Hello</button>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>

Related

Display none not working with dynamically Id using Ajax

I am working with jquery and i am trying to enable/disable using ajax jquery,Function working but showing result after
page refresh,ajax response condition is not working(dynamically),
Here is my html
<td>
<?php if(($ban->status)==1) {?>
<button type="button" class="btn btn-warning" id="disable <?php echo($ban->id); ?>" onclick="enable(<?php echo($ban->id); ?>)">Disable</button>
<?php }else{ ?>
<button type="button" id="enable <?php echo($ban->id); ?>" class="btn btn-success" onclick="enable(<?php echo($ban->id); ?>)">Enable</button>
<?php }?>
</td>
Here is my ajax
<script type="text/javascript">
function enable(id) {
var id = id;
alert(id);
$.ajax({
type: 'POST',
url: "<?php echo base_url('upload_controller/enable');?>",
data: {'id': id},
cache: false,
dataType: "html",
async: false,
success: function(data){
alert(data);
$('#response').html(data);
if (jQuery.trim(data) == "disabled")
{
document.getElementById(`enable ${id}`).style.display = "none";
document.getElementById(`disable ${id}`).style.display = "block";
}
else // if status enabled ( query working fine)
{
document.getElementById(`disable ${id}`).style.display = "none";
document.getElementById(`enable ${id}`).style.display = "block";
}
}
});
}
</script>
Here is my controller
public function enable(){
$id=$this->input->post('id');
$sql = "SELECT status from banner WHERE id=$id";
$querys=$this->db->query($sql);
$rtnArr = $querys->row_array();
//echo "<pre>";print_R($rtnArr);
$status=$rtnArr['status'];
//die();
if($status=="1")
{
$sql = "UPDATE banner SET status=0 WHERE id=$id";
$query=$this->db->query($sql);
echo "disabled";
die();
}
else
{
$sql = "UPDATE banner SET status=1 WHERE id=$id";
$query=$this->db->query($sql);
echo "enabled";
}
}
Here's an example to show how you can use a single button and toggle it's style and text. I did it this way thinking you may have multiple buttons to toggle, though it works fine with one. TO keep it flexible, we put the status and the id into data-attributes. You can test it here, and it will show the toggle, but to test it with your code, remove the part that is commented for you to remove.
$(document).ready(function() {
$('.btn-enable').each(function() {
setButton($(this), +$(this).attr('data-status'))
})
$('.btn-enable').click(function() {
// remove the next 2 lines for your actual code. This is for the snippet test
setButton($(this), +$(this).attr('data-status') === 1 ? 0 : 1)
return
$.ajax({
type: 'POST',
url: "<?php echo base_url('upload_controller/enable');?>",
data: {
'id': $(this).data('id')
},
cache: false,
dataType: "html",
async: false,
success: function(data) {
//alert(data);
$('#response').html(data);
if (jQuery.trim(data) == "disabled") setButton($(this), 0)
else setButton($(this), 1)
}
})
})
})
function setButton(button, status) {
console.log(status)
let cl = status ? 'btn-warning' : 'btn-success';
let text = status ? 'Disable' : 'Enable';
$(button).removeClass(['btn-warning', 'btn-success']);
$(button).addClass(cl);
$(button).attr('data-status', status);
$(button).text(text)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<button type="button" class="btn btn-enable" data-id='<?php echo($ban->id); ?>' data-status="<?php echo($ban->status); ?>"></button>

How i pass the dropdown value to ajax controller?

This is my dropdown box:
I am sending drop down value to ajax controller function to get some value.But the value is not passed correctly and i can't find the error;
My ajax code:
<script type="text/javascript">
$(function() {
$('.states').change(function(){
$id = $('.states').val();
$.ajax({
type : "POST",
url : "<?php echo base_url();?>Reports/Fetch_Item",
data :{id:$(this).val()},
success : function (data) {
alert(data);
var obj=jQuery.parseJSON(data);
}
});
});
});
</script>
My controller code;
public function Fetch_Item(){
$name = $this->input->post('id');
$result = $this->db->query("SELECT * FROM acc_master WHERE accName = '$name'")->row();
echo json_encode($result);
}
Front drop down box :
<div id="item3">
Party Name Selection:
<select multiple="multiple" style="width:400px;height:205px;" name="PName"id="Name" class="form-control states">
<option value=""></option>
</select>
<?php echo form_error('Area', '<div class="text-danger">', '</div>'); ?><br><br><br></div>
Dropdown ajax code:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "<?php echo base_url();?>Reports/get_countries1",
data:{id:$(this).val()},
beforeSend :function(){
$('.states').find("option:eq(0)").html("Please wait..");
},
success: function (data) {
$('.states').find("option:eq(0)").html("");
var obj=jQuery.parseJSON(data);
$(obj).each(function()
{
var option = $('<option />');
option.attr('value', this.value).text(this.label);
$('.states').append(option);
});
}});
});
</script>
Can you try this
<script type="text/javascript">
$(function() {
$('.states').change(function(){
var id = this.value;
$.ajax({
type : "POST",
url : "<?php echo base_url();?>Reports/Fetch_Item",
data :{'id':id,},
success : function (data) {
alert(data);
var obj=jQuery.parseJSON(data);
}
});
});
});
</script>
The $(this).val() returns an array, you have to change your backend code to handle the array.
Something like below.
public function Fetch_Item(){
$name = implode(",", $this->input->post('id'));
$result = $this->db->query("SELECT * FROM acc_master WHERE accName in ('$name')")->rows();
echo json_encode($result);
}
Note: Fetch_Item methon sql will return multiple results so you have to handle this as well.

php query not being processed that has been delivered by ajax post

I got two pages:
Page 1:
<input type="hidden" name="rateableUserID" value="<?php echo $rateableUserID;?>"/>
<input type="hidden" name="rateablePictureID" value="<?php echo $rateablePictureID;?>"/>
<script>
var rateableUserID = $('input[name="rateableUserID"]').val();
var rateablePictureID = $('input[name="rateablePictureID"]').val();
$('#mR-RateableFramePicture').dblclick(function () {
$.ajax({
type: "POST",
url: 'moduleRateable/scriptSavedStyle.php',
data: {"rateableUserID": rateableUserID, "rateablePictureID": rateablePictureID},
success: function() {
}
});
});
</script>
Page 2:
<?php
session_start();
$userID = $_SESSION["ID"];
$ratedUserID = $_POST['rateableUserID'];
$ratedPictureID = $_POST['rateablePictureID'];
include '../../scriptMysqli.php';
$sql = $conn->query("UPDATE styles SET savedByUser = '$userID' WHERE userID = '$ratedUserID' AND pictureID = '$ratedPictureID'");
?>
<script>alert("success");</script>
But the $sql variable never gets executed and the part with the alert is not being shown on the original page (page 1) eiher :/
What am I doing wrong here?
From the comments the changed code:
<input type="hidden" name="rateableUserID" value="<?php echo $rateableUserID;?>"/>
<input type="hidden" name="rateablePictureID" value="<?php echo $rateablePictureID;?>"/>
<script>
$('#mR-RateableFramePicture').dblclick(function () {
var rateableUserID = $('input[name="rateableUserID"]').val();
var rateablePictureID = $('input[name="rateablePictureID"]').val();
$.ajax({
type: "POST",
url: 'moduleRateable/scriptSavedStyle.php',
data: {"rateableUserID": rateableUserID, "rateablePictureID": rateablePictureID},
success: function(scriptCode) { $('body').append(scriptCode); }
});
});
</script>
The important line is the success handler. It takes the response from your ajax call (echoed by your php script) and add it to the DOM, so it will executed in case of javascript code.

clearing form fields after submitting via ajax not working

I am trying to clear form fields after submitting via ajax but it does not work. Someone please help check my codes and give me some good suggestions. Below is my code:
jQuery(document).on('click', '.um-message-send:not(.disabled)',function(e){
e.preventDefault();
jQuery('.um-message-send:visible').addClass('disabled');
var message_to = jQuery('.um-message-body:visible').attr('data-message_to');
var content = jQuery('.um-message-textarea textarea:visible').val();
jQuery.ajax({
url: um_scripts.ajaxurl,
type: 'post',
dataType: 'json',
data: { action: 'um_messaging_send', message_to: message_to, content: content },
success: function(data){
jQuery('.um-message-textarea textarea:visible').val('');
jQuery('.um-message-body:visible').find('.um-message-ajax:visible').html( data.messages );
if ( data.limit_hit ) {
jQuery('.um-message-footer:visible').html( jQuery('.um-message-footer:visible').attr('data-limit_hit') );
}
jQuery('.um-popup-autogrow:visible').mCustomScrollbar('update').mCustomScrollbar("scrollTo", "bottom",{ scrollInertia:0});
}
});
return false;
});
Html
<div class="um-message-textarea">
<?php echo $this->emoji(); ?>
<textarea name="um_message_text" id="um_message_text" data-maxchar="<?php echo $limit; ?>" placeholder="<?php _e('Type your message...','um-messaging'); ?>"></textarea>
</div>
<div class="um-message-buttons">
<span class="um-message-limit"><?php echo $limit; ?></span>
<i class="um-faicon-envelope-o"></i><?php _e('Send message','um-messaging'); ?>
</div>
The answer was simply to replace success with complete as such...
success: function(data) {
// [...]
=>
complete: function(data) {
// [...]

Checkbox (iswitch) in html table with multiple rows

This is the HTML code (a part of the table code):
<td class="center">
<?php if ($row['datum_afhaling']) { ?>
<input class="active iswitch iswitch-success" type="checkbox" cdid="<?php echo $row['cdid']; ?>" value="<?php echo $row['id']; ?>" checked></td>
<?php } else { ?>
<input class="active iswitch iswitch-success" type="checkbox" cdid="<?php echo $row['cdid']; ?>" value="<?php echo $row['id']; ?>"></td>
<?php } ?>
</td>
And the javascript code:
$("input.active").click(function() {
var check_active = $(this).is(':checked') ? 'ja' : 'nee';
var check_id = $(this).attr('value');
var cd_id = $(this).attr('cdid');
$.ajax({
type: "POST",
url: "cudi-afhalen-status-ajax.php",
data: {id: check_id, active: check_active, cdid: cd_id},
success: function(){
alert ('id: '+check_id+' & active: '+check_active+' & cdid: '+cd_id);
location.href='cudi-bestellingen-overzicht.php';
}
});
return true;
});
If I switch the checkbox to the other side I create a alertbox with some params. That works great so far, but the code gives me 15 alertboxen after each other because I have 15 rows in my table. The values (params) in all alertboxes are the same. I switch 1 checkbox-iswitch so I will have just 1 alertbox with the params and not all 14 other boxes. I don't know why it is happen?
EDIT
I found what is going wrong with the code here. The javascript code was inside my while loop. So i replaced it outside my loop and everything goes fine.
Try below code
$("input.active").click(function() {
var check_active = $(this).is(':checked') ? 'ja' : 'nee';
var check_id = $(this).attr('value');
var cd_id = $(this).attr('cdid');
var al = 1;
$.ajax({
type: "POST",
url: "cudi-afhalen-status-ajax.php",
data: {id: check_id, active: check_active, cdid: cd_id},
success: function(){
if(al==1){
alert ('id: '+check_id+' & active: '+check_active+' & cdid: '+cd_id);
al=0;
}
location.href='cudi-bestellingen-overzicht.php';
}
});
return true;
});

Categories

Resources