load page content using jquery in codeigniter error - javascript

I had a home page which have a few tables that refresh itself every few sec.
Below is the code for the jquery in view file (inside_view.php)
<script>
$(document).ready(function() {
$("#encontainer").load("inside/home_en");
var refreshId = setInterval(function() {
$("#encontainer").load('inside/home_en?randval='+ Math.random());
}, 9000);
$.ajaxSetup({ cache: false });
});
</script>
<div id="encontainer"></div>
and here is the controller code (inside.php)
function index(){
// Write to $title
$this->template->write('title', 'Update to date data');
$this->template->write_view('header', 'header_content', true);
// Write to $content
$this->template->write_view('content', 'inside_view', true);
// Write to $sidebar
$this->template->write_view('sidebar', 'user_side_menu');
// Load and display the template
$this->template->load();
}
function home_en(){
//look latest enquirer data
$data['enresults'] = $this->customer_model->get_cp_list(5);
$this->load->view('ajax_home_en',$data);
}
here is the (ajax_home_en.php) code
<link type="text/css" rel="stylesheet" href="http://bravonet.my/tombocrm/assets/css/table.css" />
<?php if($enresults->num_rows() == 0){
echo 'No data result, please insert one';
}else{
?>
<table width="100%">
<tr>
<th>CP code</th>
<th>Code</th>
<th>Name</th>
</tr>
<?php foreach($enresults->result() as $row){
echo '<tr class="tr'. alternator('1', '2'). '">';
?>
<td align="center"><?php echo $row->cp_code?></td>
<td align="center"><?php echo $row->en_code?></td>
<td align="center"><?php echo $row->name?></td>
<td align="center"><?php echo anchor('customers/patient_update_view/'.$row->eid,'Edit');?></td>
<td align="center"><?php echo anchor('customers/cp_details_view/'.$row->cpid,'View');?></td>
</tr>
<?php }?>
</table>
<?php
echo anchor('customers','View all data');
} ?>
Everything is fine when i try to view this page with this url
http://mysite.com/inside
but once i type this url
http://mysite.com/inside/ or this http://mysite.com/inside/index
the
<div id="encontainer"></div>
show inside() view instead of home_en() view. n will have continuous page refreshing in the box (and makes my IE stop responding).
I don't understand why adding a "/" or /index in the URL will cause such bug, is my javascript appear error?
thx in advanced!

It might be an issue with relative links, try:
$(function() {
$("#encontainer").load("/inside/home_en");
var refreshId = setInterval(function() {
$("#encontainer").load('/inside/home_en?randval='+ Math.random());
}, 9000);
$.ajaxSetup({ cache: false });
});

Related

Why getElementById is not working with php echo when creating a dynamic table?

I'm trying to create a table, and in each row there will be a picture, and when the picture is clicked a js function gets executed, each entry of a row in the table will create a js script for the picture of that row. And for that reason I'm using <?php echo ?> on the id of the image and on the getElementById in the script. And I have no problem using the echo on the id of the image, but if I put it inside getElementById the js code doesn't get executed. And if I write instead directly the number of the id let's say
getElementById("3") instead of getElementById("<?php echo $contact['id']; ?>") it works perfectly, but if use echo it doesn't, even when the source code of the loaded page shows that getElementById("<?php echo $contact['id']; ?>") successfully got printed as getElementById("3")
Here's the full table's code:
<table>
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php $contacts = getContacts();
if($contacts->num_rows) {
foreach($contacts as $contact) { ?>
<tr>
<td>
<img id="<?php echo $contact['id']; ?>" src="img/arrow.png" onclick='removeImage("");'>
<script type="text/javascript">
function removeImage() {
document.getElementById("<?php echo $contact['id']; ?>").style.display = "none";
}
</script>
</td>
<td><?php echo $contact['Name']; ?></td>
<td><?php echo $contact['Status']; ?></td>
</tr>
<?php }} ?>
</tbody>
</table>
When looping, you are recreating the same function over and over again, but with a different ID in each. However, you can't create the same function over and over again with the same name.
On your img change removeImage('') to removeImage(this)
<img id="<?php echo $contact['id']; ?>" src="img/arrow.png" onclick='removeImage(this);'>
Then outside of the loop just have a single function that refers to the element passed to it
function removeImage(el) {
el.style.display = "none";
}

PHP & MySQL & JS editable table won't update records

So I'm trying to use a table to update some records in my database but each time I click on update it won't work and it won't do anything. A part of the code below was found in an another topic but it was incomplete so I added some other things.
Js script
$(function(){
$("#loading").hide();
var message_status = $("#status");
$("td[contenteditable=true]").blur(function(){
var field_userid = $(this).attr("id") ;
var value = $(this).text() ;
$.post('update.php' , field_userid + "=" + value, function(data){
if(data != '')
{
message_status.show();
message_status.text(data);
//hide the message
setTimeout(function(){message_status.hide()},1000);
}
});
});
});
This is the table fetching the rows from the database, however everything works besides updating.
HTML & PHP
<form method="post" action="update.php">
<div class="col-sm-12">
<div class="table-responsive">
<table class="table table-striped table-dark">
<tr bgcolor="#df4662" style="color:#FFFFFF;">
<td>ID</td>
<td>Nickname</td>
<td>Name</td>
<td>Rank</td>
</tr>
<?php
while($row = mysqli_fetch_array($result)) {
?>
<tr>
<td contenteditable="true" id="id:<?php echo $row["id"]; ?>"><?php echo $row["id"]; ?></td>
<td contenteditable="true" id="username:<?php echo $row["username"]; ?>"><?php echo $row["username"]; ?></td>
<td contenteditable="true" id="name:<?php echo $row["steamid"]; ?>"><?php echo $row["steamid"]; ?></td>
<td contenteditable="true" id="ranks:<?php echo $row["ranks"]; ?>"><?php echo $row["ranks"]; ?></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
</form>
After a few errors I've been able to have a clean error_logs, but now I don't get any error even after pressing the update button.
update.php
<?php
include '../database.php'
?>
<?php
if(!empty($_POST))
{
foreach($_POST as $field_name => $val)
{
$field_id = strip_tags(trim($field_name));
$split_data = explode(':', $field_id);
$id = $split_data[1];
$field_name = $split_data[0];
if(!empty($id) && !empty($field_name) && !empty($val))
{
$affected_rows = mysqli_query($mysqli,"UPDATE users SET $field_name = '$val' WHERE id = $id");
echo $affected_rows;
echo "Updated";
} else {
echo "Invalid Request";
}
}
}
else {
echo "Invalid Requests";
}
?>
EDIT: Thanking Sam now the problem is just that the record won't update at all

Ajax fresh input field generated by PHP DOM

I am a student studying Ajax to change the value of an input field generated with PHP DOM.
Here is the code that generates the table rows.
<?php
$totalval = 0;
foreach($_SESSION as $name=>$value){
$total = 0;
if(substr($name,0,5) == "item_"){
$id = substr($name,5,4);
$cart_xml= new DomDocument;
$cart_xml->Load('prod_db.xml');
$root=$cart_xml->getElementsByTagName('root')->item(0);
$product=$root->getElementsByTagName('product');
foreach($product as $prod){
$itms_id=$prod->getElementsByTagName('prod_id')->item(0)->nodeValue;
$itms_categ=$prod->getElementsByTagName('prod_categ')->item(0)->nodeValue;
$itms_imgsrc=$prod->getElementsByTagName('prod_imgsrc')->item(0)->nodeValue;
$itms_name=$prod->getElementsByTagName('prod_name')->item(0)->nodeValue;
$itms_price=$prod->getElementsByTagName('prod_price')->item(0)->nodeValue;
$itms_stock=$prod->getElementsByTagName('prod_stock')->item(0)->nodeValue;
if($id==$itms_id){
$price = floatval($itms_price);
$total=$price*$value;
?>
<tr>
<td><img src="<?php echo $itms_imgsrc?>" class="citemimg"/></td>
<td>
<p class="prodname"><?php echo ucfirst($itms_name);?></p>
<p class="prodcateg"><?php echo ucfirst($itms_categ)?></p>
<p class="prodprice"><?php echo "Php. ".number_format($itms_price,2)?></p>
</td>
<td class="cartAmount;">
<img onclick="ajaxMinus('<?php echo $itms_id;?>','<?php echo $itms_stock;?>')" class="carticons" src="images/logos/Minus_r_50px.png"/>
<input type="number" min="1" max="<?php echo $itms_stock;?>" class="cartqty" id="itmQty<?php echo $itms_id;?>" value="<?php echo $value; ?>" disabled>
<img onclick="ajaxAdd('<?php echo $itms_id;?>','<?php echo $itms_stock;?>')" class="carticons" src="images/logos/Add_r_50px.png"/>
</td>
<td><?php echo "Php. ".number_format($total,2);?></td>
<td>
<a href="cart_actionCart.php?del=<?php echo $itms_id;?>&maxval=<?php echo $itms_stock;?>">
<img class="carticons" src="images/logos/Remove_r_50px.png"/>
</a>
</td>
</tr>
<?php
}
}
$totalval+=$total;
}
}
?>
And I make my image tag clickable by adding
`onclick="ajaxMinus('<?php echo $itms_id;?>','<?php echo $itms_stock;?>')"`
And I add as well
`onclick="ajaxAdd('<?php echo $itms_id;?>','<?php echo $itms_stock;?>')"`
And here is my simple function for ajaxAdd
function ajaxAdd(id,maxqty){
if(window.XMLHttpRequest){
xhrAdd=new XMLHttpRequest();
}
else{
if(window.ActiveXObject){
try{
xhrAdd=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){}
}
}
if(xhrAdd){
xhrAdd.onreadystatechange=minusQty;
xhrAdd.open("GET","cart_actionCart.php?add="+id+"&maxval="+maxqty,true);
xhrAdd.send();
}
else{
alert("Couldn't create an XMLHttpRequest");
}
}
function minusQty(){
if(xhrAdd.readyState == 4 && xhrMinus.staus == 200){
document.getElementById('itmQty'+id).value = xhrAdd.responseText;
}
}
This is working but my problem is the input value is not changing until I refresh the page, where is my problem? Any help is greatly appreciated.
Anything loaded in via AJAX will not have a listener unless the parent element was there in the first place.
As an example, I had a form HTML come through AJAX, and the datepicker would not work, until I changed the original code from this:
$('.datepicker').datepicker();
To this:
$("body").on("focusin", ".datepicker", function(){
$(this).datepicker();
});
Because body is there always, the listener now works. This will probably what your issue is too, so I suggest trying to adapt your listeners as above.

id on click of button in PHP

I am working on PHP admin panel, where I want to show list of users in the form of HTML table. In each table row there is one button where admin can send notification to the selected user.
I have created the table from below code and shown as expected.:
<div class="table">
<div style="overflow: auto;height: 400px; width: 100%;">
<form method='post'>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<th>Id</th>
<th>Package</th>
<th>Date</th>
<th>Referring Agent</th>
<th>Content Control</th>
</tr>
<?php if(!empty($records)){
foreach($records as $k=>$v){
?>
<tr>
<td><?php echo $v['id']; ?></td>
<td><h3><?php echo $v['firstname']; ?></h3></td>
<td><?php echo $v['lastname']; ?></td>
<td><?php echo $v['email']; ?></td>
<!--<td><input id='<?php echo $v['id']; ?>' type='submit' name ='send_notification' value='Send Notification'></td>-->
<td>
<div class="pagging">
Send Notification
</div>
</td>
</tr>
<?php
}
}else{
?>
<tr>
<td colspan="5" align='center'><?php echo "No record added yet"; ?>
</tr>
<?php
}
?>
I want to send the 'id' of each row to some function on click of 'send notification' where I can perform DB operations in PHP. I am not able to do that. I want on click of 'send notification' a function in php will execute which will perform some DB operation.
You need to use AJAX. Use below code.
AJAX Code
<script>
function sendNotification(id)
{
$.ajax({
type: "POST",
url: "update.php",
data: {id:id},
success: function(html) {
alert("Updated successfully");
}
});
}
</script>
PHP Code : update.php
<?php
if(isset($_POST['id']))
{
//Update query and operation here
}
?>
Download latest and require jquery from here. Click Here

DataTables javascript could not be applied to repeating tables

I have a table function (table_view.php)
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="test_coding_rosa/table_design2.css">
</head>
<body>
<?php
$row_id="";
if($_GET['page']==1 || isset($_GET['page'])==false){
$row_id=1;
}elseif (isset($_GET['page']) && $_GET['page']>1) {
$row_id=($_GET['page']-1)."1";
}
$doc = JFactory::getDocument();
$doc->addScript('http://code.jquery.com/jquery-1.11.0.min.js');
$doc->addScript('http://datatables.net/download/build/nightly/jquery.dataTables.js');
$doc->addScriptDeclaration('
jQuery(document).ready( function () {
jQuery("#main-table").DataTable();
});
');
?>
<h1><?php echo $this->title ?></h1>
<table id="main-table" border="<?php echo $this->tableBorder ?>" class="display" <?php if(!empty($this->tableWidth)) echo 'width="'.$this->tableWidth.'"';?> >
<thead>
<?php
if(!$this->hideHeaderTable)
{
if($_GET['t']!='maklumat_ringkas'){
echo "<tr><th width='10px'>Bil</th>";
}
foreach($this->tableData[0] as $key=>$tableHeader)
{
?>
<th width="<?php echo $this->tableData[1][$key] ?>" scope="col"><?php echo $this->tableData[0][$key] ?></th>
<?php
}
?>
</tr>
</thead>
<?php
}
$lenData = count($this->tableData);
for ($j=3;$j < $lenData; ++$j)
{
?>
<tbody>
<tr class="centertable" <?php if($j % 2==1) echo 'bgcolor="#EFF4FB"'?>><?php if($_GET['t']!='maklumat_ringkas'){echo "<td>".$row_id++."</td>";}?>
<?php
foreach($this->tableData[0] as $key=>$tableHeader)
{
?>
<td width="<?php echo $this->tableData[1][$key] ?>" <?php echo $this->tableData[2][$key] ?>><?php echo stripslashes($this->tableData[$j][$key]) ?></td>
<?php
}
?>
</tr>
</tbody>
<?php
}
?>
</table>
</body>
</html>
This table_view.php is the default table for all data in the site. As you can see in the photo below, there are multiple tables being called from table_view.php.
The problem here is, I wanted to use DataTables.net to include the pagination of the tables. However, only the first table has been successfully implemented with DataTables.net plugin.
How can I implement it on all of the tables? Since all the tables are being called from the same function file (table_view.php), the table id is the same.
UPDATED declaration
$doc = JFactory::getDocument();
$doc->addScriptDeclaration("
jQuery('[id='main-table']').each(function(i,e) {
var id=jQuery(this).attr('id');
jQuery(this).attr('id', id+'_'+i);
jQuery(this).addClass('datatable-identifier');
}); ");
$doc->addScript('http://code.jquery.com/jquery-1.11.0.min.js');
$doc->addScript('http://datatables.net/download/build/nightly/jquery.dataTables.js');
$doc->addScriptDeclaration('
jQuery(document).ready( function () {
jQuery(".datatable-identifier").dataTable();
} );
Having multiple elements with the same id is a very bad habit :) You should really try to avoid it. Though HTML is forgiving, it results as you see in all kind of problems when trying to access elements in javascript.
If it is impossible to avoid, you could run the following function before calling dataTable() :
jQuery('[id="main-table"]').each(function(i,e) {
var id=jQuery(this).attr('id');
jQuery(this).attr('id', id+'_'+i);
jQuery(this).addClass('datatable-identifier');
});
This will rename the table id's to main-table_1, main-table_2 and so on. The class datatable-identifier is just a dummy class used when initializing the dataTables, change your code to :
jQuery(document).ready( function () {
jQuery(".datatable-identifier").dataTable();
});

Categories

Resources