I am displaying data results from database with php, ajax and jquery.
I have used codeigniter 4 pager library for pagination. But when I click the next page of pagination the serial number reset and start again from 1-10, all I want is when i click the next page to continue counting a serial number from 11-20, 21-30 etc...
Help please. Thank you.
//html table
<table>
<thead>
<tr>
<th>No.</th>
<th>MyColumn</th>
</tr>
</thead>
<tbody class="result"></tbody>
</table>
//jquery
show();
function show(){
let ajax = $.ajax({
url : '/Controller/getAll',
method : 'post',
dataType: 'json',
cache : false
});
ajax.done(function(data){
let serialNumber = 1;
$.each(data.result, function(k, v){
html += `<tr>
<td>${serialNumber}</td>
<td>${v.myColums}</td>
</tr>`;
serialNumber++;
});
});
$('.result').html(html);
}
// php controller
public function getAll()
{
$result = $this->model->getData()->asObject()->paginate('10');
$pager = $this->model->pager;
foreach($result as $row){
$output[] = [
'id' => $row->id,
'myColumn' => $row->myColumn,
];
}
$jsonArray = [
'result' => $output,
'pager' => $pager->links(),
];
return $this->response->setJSON($jsonArray);
}
You are initializing serialNumber when you receive a ajax response. Do it on page load.
function show(){
let ajax = $.ajax({
url : '/Controller/method',
method : 'post',
dataType: 'json',
cache : false
});
ajax.done(function(data){
let serialNumber = 1; // move this to page load
$.each(data.result, function(k, v){
html += `<tr>
<td>${serialNumber}</td>
<td>${v.myColums}</td>
</tr>`;
serialNumber++;
});
});
$('.result').html(html);
}
Declare a variable outside of the function
let serialNumber = 1;
function show(){
let ajax = $.ajax({
url : '/Controller/getAll',
method : 'post',
dataType: 'json',
cache : false
});
ajax.done(function(data){
$.each(data.result, function(k, v){
html += `<tr>
<td>${serialNumber}</td>
<td>${v.myColums}</td>
</tr>`;
serialNumber++;
});
});
}
Another option is to return the page number from PHP and calculate the start point of the serial
You can try this:
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 1;
$data["slno_start"] = (($page-1) * $config["per_page"]) + 1;
Related
I want to append php code and I want to use script varible in my php code.
How can i do this?
function sendajax(id,status,count){
$.ajax({
url : '{{url("admin/loadmoredata")}}',
method : "POST",
data : {id:id,status:status,count:count, _token:"{{csrf_token()}}"},
dataType : "json",
success : function (data)
{
if(status = 1)
{
if(data[0] == 400){
$('.acceptorder-btn').html('no data');
}else{
console.log(data[2])
var row = data[1];
$.each(data[2], function( index, value ) {
row++
$('.load').append(`<tr> <td> `+row+` </td> <td> <?php $vlue = `+value["id"]+` ; dd($vlue); ?></td> <td>`+value["receiver_name"]+`</td></tr>` );
$('#btn-more').removeAttr('data-id');
$('.loadmore-btn').attr('data-id',value['id']);
});
}
// $('.load').append(data);
}
else
{
$("#btn-more").html("No Data");
}
}
});
}
});
I can show script variable like this echo '+value["id"]+'
but I can't use this for variable in php and when I dd() variable it returns null.
I have two files fetch.php and index.php. The fetch.php file does a search and converts the results to Json.
Index.php has Jquery which loops through the Json result. One of the cells contains a URL. How can I get a user to redirect to the URL.
//index.php==============================
<script>
$(document).ready(function(){
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
$('#total_records').text(data.length);
var html = '';
if(data.length > 0)
{
for(var count = 0; count < data.length; count++)
{
html += '<hr>';
html += '<tr>';
html += '<div>'+data[count].title+'</div>';
html += '<td>'+data[count].book+'</td><tr/>';
html += '<br/><td>'+data[count].description+'</td><tr/>';
html += '<td><button> VIEW </button> '+data[count].url+'</td>'; //Is there a way to redirect to this URL by clicking on the VIEW button
html += '<hr>';
}
}
else
{
html = '<tr><td colspan="5">No Data Found</td></tr>';
}
$('tbody').html(html);
}
})
}
$('#search').click(function(){
var query = $('#search_id').val();
load_data(query);
});
</script>
Simple solution:
html += '<td><button onclick="window.location.href=\''+data[count].url+'\'"> VIEW </button> '+data[count].url+'</td>';
Consider the following suggestions:
$(function() {
function load_data(q) {
$.ajax({
url: "fetch.php",
method: "POST",
data: {
query: q
},
dataType: "json",
success: function(data) {
$('#total_records').text(data.length);
var row;
if (data.length > 0) {
$.each(data, function(k, d) {
row = $("<tr>");
$("<td>").html(d.title).appendTo(row);
$("<td>").html(d.book).appendTo(row);
$("<td>").html(d.description).appendTo(row);
var e = $("<td>").appendTo(row);
$("<button>").html("VIEW").click(function(e) {
window.location.href = d.url;
}).appendTo(e);
});
} else {
row = $("<tr>");
$("<td>", {
colspan: 4
}).html("No Results Found.").appendTo(row);
}
}
});
}
$('#search').click(function() {
var query = $('#search_id').val();
load_data(query);
});
});
As you can see, this makes use of a few more jQuery parts to help slimline your code. Additionally, we create a Click event callback when the button is created and added to the table.
You had a lot of improper HTML Syntax. My example does not replicate that. A Row Element should contain Cells and not other elements. Yes, you can do it, yet it's not good practice. This is why I removed them. If they are needed for some reason, you should provide a more complete example so it's clear why they are needed.
I cannot get a value of $id_pinjam = #$_GET['id_pinjam']; here's PHP code
<?php
include '../../inc/koneksi.php';
$id_pinjam = #$_GET['id_pinjam'];
$tgl_kembali = date("Y-m-d");
$queryResult = $db->query("SELECT * FROM detail_pinjam WHERE id_pinjam = '$id_pinjam'") or die($db->error);
echo $id_pinjam."<br>";
while($fetchData = $queryResult->fetch_assoc()){
echo "<tr>
<td class='text-center'>".$fetchData['id_detail']."</td>
<td class='text-center'>".$fetchData['id_pinjam']."</td>
<td class='text-center'>".$fetchData['kode_pustaka']."</td>
<td class='text-center'>".$fetchData['tgl_jatuh_tempo']."</td>
<td class='text-center'></td><td class='text-center'></td></tr>";
}
?>
Here's jQuery code(to load data):
loadDataPinjam();
function loadDataPinjam(){
var dataHandler = $("#load-data-pinjam-here");
dataHandler.html("");
$.ajax({
type : "GET",
data : "",
url : "proses/pinjam/getDataPinjam.php",
success : function(result){
var resultObj = JSON.parse(result);
$.each(resultObj,function(key, val){
var newRow = $("<tr>");
newRow.html("<td class='text-center'>"+val.no_anggota+"</td><td class='text-center'>"+val.nama+"</td><td class='text-center'>"+val.alamat+"</td><td class='text-center'>"+val.id_pinjam+"<td class='text-center'>"+val.tgl_pinjam+"</td><td class='text-center'>"+val.jml_pinjam+"</td><td class='text-center'>"+val.status+"</td><td style='width: 20px;'><a href='?page=kembali&id_pinjam="+val.id_pinjam+"'><img src='img/return.png' class='icon'></a><input type='hidden' name='getIdPinjam' id='getIdPinjam' value='"+val.id_pinjam+"'></td>");
dataHandler.append(newRow);
});
}
});
}
and when i click link, GET parameter is not set, but when i set $id_pinjam manually than code is working. Help me to identify issue?
I think the problem is that you are sending nothing via Ajax.
Try:
url : "proses/pinjam/getDataPinjam.php?id_pinjam=YourValue",
You can use below 2 methods for GET method in jQuery
1. Use $.get method
Please check below link for reference:
https://api.jquery.com/jquery.get/
$.get("test.php", {number: numValue} , function(data){
// Display the returned data in browser
});
2. Standard $.ajax method
$.ajax({
method: "GET",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.success(function( data ) {
alert( "Data : " + data );
});
As per your above sample code you need to pass parameters while you call ajax method
function getSearchClients() {
console.log('Inside searchClient');
$('#progressbar').show();
var searchClientPhone = document.getElementById('searchClientCellPhoneNo').value;
$.ajax({
type:"POST",
data: "searchClientPhone=" + searchClientPhone,
url: "searchClientCellPhoneNo",
success: function(result){
$("#progressbar").hide();
$("#example td").each( function() {
var thisCell = $(this);
var cellValue = parseInt(thisCell.text());
if (!isNaN(cellValue) && (cellValue >= document.getElementById("selectedClientRewardPoints").value)) {
thisCell.css("background-color","#FF0000");
}
}
);
$("#selectedClientName").show();
$("#selectedClientRewardPoints").show();
window.location.reload(true);
}
});
}
The textboxes do not become visible in the ajax success, though I have verified control goes to the success block.
I think this is because of window.location.reload(true), why do you think to reload the page again!!
As per my understand, when the page is reloaded for a second time, the search input parameter becomes null/empty, so in this snippet var cellValue = parseInt(thisCell.text()); cellValue is null/undefined.
Because of this, the following two lines do not function as expected
$("#selectedClientName").show();
$("#selectedClientRewardPoints").show();
If you want to keep your status like :
$("#progressbar").hide();
$("#selectedClientName").show();
$("#selectedClientRewardPoints").show();
you should store a boolean in the user localstore or a cookie (on ajax success). Then on the page just have a document ready:
$(document).ready({
if(localstorage/cookie) { / check the status of your cookie or localstorage
$("#progressbar").hide();
$("#selectedClientName").show();
$("#selectedClientRewardPoints").show();
// clear the cookie or the localstorage
}
});
I hope this gives you an idea man...
There were a few things wrong. Primarily you were reloading the page, which is probably the main issue.
Also you had a few small issues with your number parsing and validating. I have fixed it below.
function getSearchClients() {
console.log('Inside searchClient');
$('#progressbar').show();
var searchClientPhone = $('#searchClientCellPhoneNo').val();
$.ajax({
type: "POST",
data: "searchClientPhone=" + searchClientPhone,
url: "searchClientCellPhoneNo",
success: function (results) {
$("#progressbar").hide();
$("#example td").each(function () {
var thisCell = $(this);
var cellText = thisCell.text();
// This will update your textbox...
$("#selectedClientName").val(result.clientName);
// And this is an example of updating based on an array of data.
result.transactions.forEach(function(result){
// Create a list item and append it to the list.
$('<li></li>').text(result).appendTo('#resultList');
});
// If the cell text is a number...
if (!isNaN(cellText)) {
// Parse the text to a base 10 integer...
var cellValue = parseInt(thisCell.text(), 10);
if (cellValue >= $("#selectedClientRewardPoints").val()) {
thisCell.css("background-color", "#FF0000");
}
}
});
$("#selectedClientName").show();
$("#selectedClientRewardPoints").show();
// Do not reload the page.
}
});
}
Thanks #JimmyBoh for the pointers, this is how I fixed the issue :
1) Used struts2-json library. In struts.xml, added below:
<package name="json" extends="json-default">
<action name="searchClientCellPhoneNo" class="com.intracircle.action.RedeemAction" method="searchClientCellPhoneNo">
<result type="json">
<param name="root">jsonData</param>
</result>
</action>
</package>
2) In the action class, added a jsonData Map as follows :
private Map<String,Object> jsonData = new HashMap<String,Object>();
Added getters and setters for jsonData
public Map<String,Object> getJsonData() {
return jsonData;
}
public void setJsonData(Map<String,Object> jsonData) {
this.jsonData = jsonData;
}
In the action method, added data to be returned to jsp to the jsonData Map as follows :
public String searchClientCellPhoneNo() {
clientList = userdao.getClientsList(searchClientPhone);
if(clientList != null && clientList.size() > 0) {
selectedClientName = clientList.get(0).getProfileName();
jsonData.put("selectedClientName",selectedClientName);
int storeId = ((Stores)SecurityUtils.getSubject().getSession().getAttribute(SESSION_CONSTANTS.SESSION_STORE)).getStoreId();
selectedClientRewardPoints = redeemDao.getCountRewardPointsForClientForStore(storeId, clientList.get(0).getId());
jsonData.put("selectedClientRewardPoints", selectedClientRewardPoints);
}
viewRedeemScheme();
return SUCCESS;
}
3) In the jsp ajax method, did the following changes : Make sure, you add dataType:'json' and if you want to print the ajax result using alter, stringify it.
$.ajax({
type:"GET",
data: "searchClientPhone=" + searchClientPhone,
url: "searchClientCellPhoneNo",
dataType: 'json',
headers : {
Accept : "application/json; charset=utf-8",
"Content-Type" : "application/json; charset=utf-8"
},
success: function(result){
alert("result: " + JSON.stringify(result));
console.log("Result " + result);
$("#selectedClientName").val(result.selectedClientName);
$("#selectedClientRewardPoints").val(result.selectedClientRewardPoints);
$("#progressbar").hide();
$("#example td").each( function() {
var thisCell = $(this);
var cellValue = parseInt(thisCell.text());
if (!isNaN(cellValue) && (cellValue >= document.getElementById("selectedClientRewardPoints").value)) {
thisCell.css("background-color","#FF0000");
}
}
);
$("#selectedClientName").show();
$("#selectedClientNameLabel").show();
$("#selectedClientRewardPointsLabel").show();
$("#selectedClientRewardPoints").show();
}
});
Thanks everyone for the help, especially #JimmyBoh.
I want to check domain availability with php and ajax request. Requests will be sent to "whois.apitruck.com" API like this: "whois.apitruck.com/domain.com".
For each domain, a request is sent. I want to append table after complate all ajax request but this not work!
$(document).ready(function () {
$("#submit").click(function () {
var domain = $('#domains').val().split("\n");
var all_suffix = ["com","net","org","ir","biz","info","us","name","pro","eu","in","me","tv","cc"];
var counter = 0;
var TableDataString = '<table class="table table-bordered table-striped table-responsive domain-table"><thead><tr><th>ID</th><th>Domain Name</th><th>.Com</th><th>.Net</th><th>.Org</th><th>.Ir</th><th>.Biz</th><th>.Info</th><th>.Us</th><th>.Name</th><th>.Pro</th><th>.In</th><th>.Me</th><th>.Tv</th><th>.Cc</th></tr></thead><tbody>';
var domain_count = domain.length;
$.each(domain, function (i, val) {
//increase i counter
counter++;
TableDataString += '<tr><td>'+ counter +'</td><td>'+ val +'</td>';
$('input[type=checkbox]:checkbox:checked').each(function () {
var flag = '';
var suffix = $(this).val();
$.ajax({
type: "POST",
url: "includes/ajax/ajax.php",
dataType: "json",
data: {domain: val, suffix: suffix},
success: function (msg) {
flag = msg.suc;
},
error: function (err) {
$('#domain_tables').html(err.error);
}
});//end $.ajax
if(flag){TableDataString += '<td><i class="fa fa-times"></i></td>';}else{TableDataString += '<td><i class="fa fa-check"></i></td>';}
});//end get each suffix
TableDataString += '</tr>';
});//end each domain
TableDataString += '</tbody></table>';
if(counter === domain_count){
$(document).ajaxComplete(function(){
$('#domain_tables').append(TableDataString);
});
}
});
});
I am used a flag and check this after $.ajax. The display problem solved. But for each ajax request echo a new table, If that display one table for all ajax request. How to append table after complate all ajax request?! Another problem is that check flag does not work properly! why?!
You're using .append() on your $('#domain_tables'), so that each time a new table is generated. You should empty the #domain_tables div before making another AJAX request(s) queue.
You're not checking which check-boxes are checked and which are not, so that you only create <td> elements for chechbox:checked.
Even if you add all necessary <td> elements, these generated in AJAX success callback will be added at the end of the table, because your loop runs faster than AJAX request (simply saying). You have to state which <td> element belong to which AJAX request.
I'd go this way:
$(document).ready(function () {
$("#submit").click(function () {
// check if anything is selected:
if(!$('#domains').val() || !$('[type="checkbox"]:checked').length){
return false;
}
// disable the button:
var btn = $(this).prop('disabled', true);
var domain = $('#domains').val().split("\n");
var counter = 0;
// an indicator to state when the button should be enabled again:
var ajaxQueue = 0;
var Table = '<table class="table table-bordered table-striped table-responsive domain-table"><thead><tr><th>ID</th><th>Domain Name</th><th>.Com</th><th>.Net</th><th>.Org</th><th>.Ir</th><th>.Biz</th><th>.Info</th><th>.Us</th><th>.Name</th><th>.Pro</th><th>.Eu</th><th>.In</th><th>.Me</th><th>.Tv</th><th>.Cc</th></tr></thead><tbody>';
// create the td elements, but do not perform AJAX requests there:
$.each(domain, function (i, val) {
counter++;
Table += '<tr><td>'+ counter +'</td><td>'+ val +'</td>';
$('input[type=checkbox]').each(function () {
if($(this).is(':checked')){
ajaxQueue++;
// if checkbox is checked make td element with specified values and a "load-me" class:
Table += '<td class="load-me" data-domain="'+val+'" data-suffix="'+$(this).val()+'"><small>loading...</small></td>';
}else{
Table += '<td><span class=text-muted><i class="fa fa-minus"></i></span></td>';
}
});
Table += '</tr>';
});
// Replace HTML of the 'domain_tables' div and perform AJAX request for each td element with "load-me" class:
$('#domain_tables').html(Table+'</tbody></table>').find('td.load-me').each(function(){
var td = $(this);
$.ajax({
type: "POST",
url: "includes/ajax/ajax.php",
dataType: "json",
data: {domain: td.attr('data-domain'), suffix: td.attr('data-suffix')},
success: function (msg) {
// decrease ajaxQueue and if it's 0 enable button again:
ajaxQueue--
if(ajaxQueue === 0){
btn.prop('disabled', false);
}
if(msg.suc == false){
td.html('<span class=text-danger><i class="fa fa-times"></i></span>');
}else{
td.html('<span class=text-success><i class="fa fa-check"></i></span>');
}
},
error: function (err) {
$('#domain_tables').html(err.error);
}
});
});
});
});
My final answer is look like this:
$(document).ready(function () {
$("#submit").click(function () {
var domain = $('#domains').val().split("\n");
var all_suffix = ["com","net","org","ir","biz","info","us","name","pro","eu","in","me","tv","cc"];
var counter = 0;
var TableDataString = '<table class="table table-bordered table-striped table-responsive domain-table"><thead><tr><th>ID</th><th>Domain Name</th><th>.Com</th><th>.Net</th><th>.Org</th><th>.Ir</th><th>.Biz</th><th>.Info</th><th>.Us</th><th>.Name</th><th>.Pro</th><th>.In</th><th>.Me</th><th>.Tv</th><th>.Cc</th></tr></thead><tbody>';
var domain_count = domain.length;
$.each(domain, function (i, val) {
//increase i counter
counter++;
TableDataString += '<tr><td>'+ counter +'</td><td>'+ val +'</td>';
$('input[type=checkbox]:checkbox:checked').each(function () {
var flag = false;
var suffix = $(this).val();
$.ajax({
type: "POST",
url: "includes/ajax/ajax.php",
dataType: "json",
data: {domain: val, suffix: suffix},
success: function (msg) {
flag = msg.suc;
if(flag){TableDataString += '<td><i class="fa fa-times"></i></td>';}else{TableDataString += '<td><i class="fa fa-check"></i></td>';}
TableDataString += '</tr>';
},
error: function (err) {
$('#domain_tables').html(err.error);
}
});//end $.ajax
});//end get each suffix
});//end each domain
if(counter === domain_count){
TableDataString += '</tbody></table>';
$('#domain_tables').append(TableDataString);
}
});
});
I think this will solve your last two mentioned problem.