AJAX JQUERY codeigniter - php

hy , I use AJAx in my project
<?php foreach ($dt_pesanan_detail->result_array() as $key) { ?>
<tr class="content">
<td class="td-keranjang" id="id_kelas"><?php echo $key['nama_menu']; ?></td>
<script type="text/javascript">
$("#id_kelas").change(function(){
var id_kelas = {id_kelas:$("#id_kelas").val()};
$.ajax({
type: "POST",
url : "<?php echo base_url(); ?>transaksi/ambil_data_pelanggan_ajax",
data: id_kelas,
success: function(msg){
$('#siswa').html(msg);
}
});
});
</script>
but this code only for array index 1 , if result $dt_pesanan_detail more then 2 row,why j query only run in 1 row, 2 row can't run

The first problem is that you're generating that script in every iteration of the array $dt_pesanan_detail. The 2nd (and real issue) is that ID's are unique, and therefore you can't do what you're trying to achieve. Therefore, perform these adjustments:
<?php foreach ($dt_pesanan_detail->result_array() as #key) { ?>
<tr class="content">
<td class="td-keranjang" id="id_kelas" class="id_kelas">
Then don't generate the script in your foreach loop.
$(".id_kelas").change(function(){
$.ajax({
type: "POST",
url : "<?php echo base_url(); ?>transaksi/ambil_data_pelanggan_ajax",
data: id_kelas,
success: function(msg){
$('#siswa').html(msg);
}
});
});

Related

Delete Task on a todo list, without refreshing the site with PHP

I am working an a to-do list with php and mysql. I have already connected my programm with the Database. Now I have this output:
2022-09-24 X Task1
2022-09-24 X Task2
2022-09-24 X Task1
the HTML looks
<ul>
<li><span>X </span>Task1</li>
<li><span>X </span>Task2</li>
<li><span>X </span>Task3</li>
</ul>
How i can delete a Task with php, if I click on "X" without refreshing the site?
your HTML should like (don't forget to save the file as PHP):
<tr class="delete_task<?php echo $id ?>">
<td><?php echo $row_task['task_name']; ?></td>
<td>
<a class="btn btn-success" id="<?php echo $id; ?>">Delete</a>
</td>
</tr>
you need to add event on button with js code first
<script type="text/javascript">
$(document).ready(function() {
$('.btn-success').click(function() {
var id = $(this).attr("id");
if (confirm("Are you sure you want to delete this Member?")) {
$.ajax({
type: "POST",
url: "task_delete.php",
data: ({
id: id
}),
cache: false,
success: function(html) {
$(".delete_task" + id).fadeOut('slow');
}
});
} else {
return false;
}
});
});
</script>
your PHP code in task_delete.php
<?php
include ('database.php'); // your DB connection
$id = $_GET['id'];
$delete_data"delete from tasks where task_id = '$id' ";
$database->exec($delete_data);
?>

JSON table displays fine on first and throws 403 error on next

I used a solution in this post
I used this solution on my webpage and it works partially.
Basically I have a table with a link on each row and when I click a link, I retrieve data via AJAX and display this data in another table. All works well when I click the first link but throws a "403 Forbidden" error when I click another link in the table.
<div class="col-lg-4" id="media-sources-view">
<div id="result">
<table class="table table-hover hidden" id="xarticletab">
<tr>
<th>Title</th>
<th>Name</th>
</tr>
</table>
</div>
</div>
<script type="text/javascript">
$('#mashed_row a').click(function () {
var link_id = $(this).attr('link_id');
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>main/explode_link',
data: {'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>', link_id},
dataType: 'json',
success : function(data) {
if(data){
var len = data.length;
var txt = "";
if(len > 0){
for(var i=0;i<len;i++){
if(data[i].title){
txt += "<tr><td>"+data[i].title+"</td><td>"+data[i].name+"</td></tr>";
}
}
if(txt != ""){
$("#xarticletab").append(txt).removeClass("hidden");
}
}
}
}
});
return false;
});
</script>
It's because of CSRF token regeneration after every POST request.
First time when you output the page, CSRF token in javascript is valid but after first request it gets regenerated but your javascript code still uses old one.
Either disable CSRF regeneration which will use same CSRF token until it expires - default 7200 seconds (this lowers security a bit so I wouldn't recommend it) - in application/config/config.php
$config['csrf_regenerate'] = false;
or refactor your javascript code and the php file which processes ajax to use GET request which doesn't require CSRF token.
To clear old table rows and populate new, first make a proper html table layout:
<table class="table table-hover hidden" id="xarticletab">
<thead>
<tr>
<th>Title</th>
<th>Name</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
And ajax code:
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>main/explode_link',
data: {'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>', link_id},
dataType: 'json',
success : function(data) {
if (data) {
// Clear table body rows
$('#xarticletab tbody').empty();
var len = data.length;
var txt = "";
if (len > 0) {
for (var i=0;i<len;i++) {
if (data[i].title) {
txt += "<tr><td>"+data[i].title+"</td><td>"+data[i].name+"</td></tr>";
}
}
if (txt != "") {
$('#xarticletab').removeClass('hidden');
// Append rows to table body
$("#xarticletab tbody").append(txt);
}
}
}
}
});

increase php variable in jquery

I have a problem and I do not know if the method I am using is correct.
I want to decrease the variable $ pag -1 if a record is deleted.
I do this because I have a pagination and affects which records are deleted, I must decrease that variable I use in the pagination.
In this code I decreases though it has not eliminated any registration.
How can I do to make me decrease the variable only if a record is deleted?
her code:
<?php $pag=20; ?>
<script type="text/javascript">
$('.delete').live("click",function()
{
var ID = $(this).attr("id");
var dataString = 'id='+ ID;
jConfirm('DELETE?',
function(r) {
if(r==true)
$.ajax({
type: "POST",
url: "delete.php",
data: dataString,
cache: false,
beforeSend: function(){
$("#stbody"+ID).animate({'backgroundColor':'#F2F2F2'},300);},
success: function(html){
$("#body"+ID).fadeOut(300,function(){$("#body"+ID).remove();});
//div update
setTimeout(function() {
$("#apDiv101").load('disminuye.php');
}, 100);
}
});
});
return false;
});
</script>
<!--html delete-->
<a class="delete" href="#" id="<?php echo $id;?>" title="DELETE"></a>
<!--DIV update-->
<div id="apDiv101"><?php
include('disminuye.php');
?></div>
file disminuye.php
<?php
$pag = $pag-1;
echo $pag;
?>

Ajax/php how do I identify a single generic field?

I'm building a checkout on a marketplace application. I need to be able to increment, decrement and remove items at the checkout but when there is multpile items the AJAX event jQuery only picks up the first item_id when the AJAx event fires no mater what item a user clicks on, how can I fix this?
Here's the PHP/HTML code...
<?php
$total = 0;
$subtotal = 0;
foreach($items as $item):
$subtotal += $item['product_price']*$item['product_qty'];
?>
<tbody id="item_<?=$item['cart_item_id']?>">
<tr>
<td>
<img src="<?=$item['product_image']?>">
<?php if($item['brand_name']!='None'): ?>
<p style="color: #666;"><?=$item['brand_name']?></p>
<?php endif; ?>
<p style="font-size: 16px;"><?=$item['product_name']?></p>
<a href="#" id="remove-item-button" >Remove this item</a> <!--HERE-->
</td>
<td class="align-td-center">
<?=formatted_price($item['product_price'])?>
</td>
<td class="align-td-center">
Less<!--AND HERE-->
<input type="hidden" id="item_id" value="<?=$item['cart_item_id']?>">
</td>
<td class="align-td-center">
<span id="value-shipping-<?=$item['cart_item_id']?>"><?=formatted_price($item['product_price']*$item['product_qty'])?></span>
</td>
</tr>
</tbody>
And here's my jQ/AJAX...
$('a#qty-inc-button').click(function(){
$("#processing").fadeIn("fast");
$.ajax({
url: "<?=BASE_URL?>landing/inc_cart_item",
type: "post",
dataType: "json",
data: {inc:1, item_id: $('#item_id').val(),},
success: function(data){
$("#processing").fadeOut("fast");
if(data.error) {
alert(data.error);
} else {
// parent.$('#line1').text(data.line1);
//parent.$('#line2').text(data.line2);
//parent.$('#address-dialog').dialog('close');
alert(data.line1);
}
}
});
return false;
});
$('a#qty-dec-button').click(function(){
$("#processing").fadeIn("fast");
$.ajax({
url: "<?=BASE_URL?>landing/dec_cart_item",
type: "post",
dataType: "json",
data: {dec:0, item_id: $('#item_id').val(),},
success: function(data){
$("#processing").fadeOut("fast");
if(data.error) {
alert(data.error);
} else {
//parent.$('#line1').text(data.line1);
//parent.$('#line2').text(data.line2);
//parent.$('#address-dialog').dialog('close');
alert(data.line1);
}
}
});
return false;
});
$('a#remove-item-button').click(function(){
$("#processing").fadeIn("fast");
$.ajax({
url: "<?=BASE_URL?>landing/rem_cart_item",
type: "post",
dataType: "json",
data: {item_id: $('#item_id').val(),},
success: function(data){
$("#processing").fadeOut("fast");
if(data.error) {
alert(data.error);
} else {
//parent.$('#line1').text(data.line1);
//parent.$('#line2').text(data.line2);
//parent.$('#address-dialog').dialog('close');
alert(data.line1);
}
}
});
return false;
});
All help appreciated and thanks for looking.
An id is meant to be an unique identifier on a page. http://css-tricks.com/the-difference-between-id-and-class/
So, JQuery stops searching as soon as it finds the first occurrence of #qty-inc-button.
There are many ways to do what you are trying to acheive. You should make qty-inc-button a class name along with any id that appears multiple times on a page. Then you can try
$('a.qty-inc-button').click(function(){
$(this).DoSomething(); // where $(this) is the 'a.qty-inc-button' that the user clicked on.
// you can do:
$(this).children(".aChildClass").hide();
// you can do:
$(this).find( 'someElement' ).css( 'background-color', 'red' ); //etc, etc
});
However, in my very humble opinion you should learn more about HTML attributes and JQuery traversal before trying things of this caliber. Otherwise, you'll keep stumbling.
Try to change IDs to classes, modify selectors to find child object of parent table_item
Read about difference bteweeen id and classes.
After speaking to both client and PM and experimenting with traversal this is the answer...
onClick="remItem(<?=$item['cart_item_id']?>)"
In the relevant anchor tags, untidy it is but time is against us. Thanks to all.

Loading a facebox modal window after an ajax request

this is what i have in the head tags of my html page to load the facebox plugin:
<!-- This is for the facebox plugin to work -->
<link href="<?php echo base_url();?>styles/facebox/src/facebox.css" media="screen" rel="stylesheet" type="text/css" />
<script src="<?php echo base_url();?>styles/facebox/lib/jquery.js" type="text/javascript"> </script>
<script src="<?php echo base_url();?>styles/facebox/src/facebox.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('a[rel*=facebox]').facebox({
loadingImage : "<?php echo base_url();?>styles/facebox/src/loading.gif",
closeImage : "<?php echo base_url();?>styles/facebox/src/closelabel.png"
})
})
</script>
this is the code for my div
<?php if(isset($$j)) : foreach($$j as $row) : ?>
<div class="single-result" id="single-result">
<div class="name"><?php echo $row->Name; ?></div>
<div class="description"><?php echo $row->Description; ?></div>
</div>
<?php endforeach; ?>
<?php else : ?>
error here
<?php endif; ?>
what i am wanting, is some ajax code that calls a function when the user clicks on the div id="single-result" so that it makes an ajax call to a php controller that gets the data from the database and then loads the view into a facebox modal window.
The part i am unsure about is how to make it load into a facebox modal window, l know how to use ajax calls to make it send data to a file and then load a view into a certain div on the page, l just want it to load it into the modal window instead of a certain div on the page.
Is this possible at all? (also i am using codeigniter for the php framework)
here is my ajax code which would load the ajax request results into the content-right div when the user clicks on div.
<script type="text/javascript">
$("#single-result").click(function() {
var form_data = {
ajax: '1',
itemcode: "<?php echo $row->id; ?>"
};
$.ajax({
url: "<?php echo site_url('ajax/item_info_right'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
$('#content-right').html(msg);
}
});
return false;
});
</script>
<!-- END -->
how do i modify this code above to make it work with going into a facebox modal window? I know facebox provides this code below, but i have no idea what to do with it?
jQuery.facebox(function() {
jQuery.get('code.js', function(data) {
jQuery.facebox('<textarea>' + data + '</textarea>')
})
})
It's not really clear what you're after...
If what you want is to have the data returned from the ajax POST to be populated into a facebox, simply call facebox on the success callback of the ajax post:
$("#single-result").click(function() {
var form_data = {
ajax: '1',
itemcode: "<?php echo $row->id; ?>"
};
$.ajax({
url: "<?php echo site_url('ajax/item_info_right'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
jQuery.facebox(msg);
})
});
alternatively, it looks like if you want the facebox loading graphics while the post is processed, you can wrap the ajax POST in facebox function:
$("#single-result").click(function() {
jQuery.facebox(function() {
var form_data = {
ajax: '1',
itemcode: "<?php echo $row->id; ?>"
};
$.ajax({
url: "<?php echo site_url('ajax/item_info_right'); ?>",
type: 'POST',
data: form_data,
success: function(msg) {
jQuery.facebox(msg);
})
});
})
})

Categories