I have a javascript function which makes an ajax request to php controller method which returns a JSON encoded array.
function initGallery(offset) {
if(offset === undefined)
{
var request_url = url+'avatar/gallery';
} else {
var request_url = url+'avatar/gallery/'+offset;
}
$('#avatar_gallery').html('')
$.get(request_url,function(data) {
var dat = jQuery.parseJSON(data);
//Build gallery
$('#avatar_gallery').html('<div class="gallery_box"></div>');
$('.gallery_box').append('<div class="gallery_header">Your Avatar Gallery</div>');
$('.gallery_box').append('<div class="gallery_container"></div>');
$.each(dat.avatars,function(index,item)
{
$('.gallery_container').append(
'<div class="gallery_item">'+
'<img src="'+item.avatar_src+'" id="'+item.avatar_id+'" onclick="avatar.view_avatar(this.id)"/>'+
'</div>'
);
});
$('.gallery_box').append('<div class="gallery_footer"></div>');
$('.gallery_footer').html('<div class="gallery_pagination"><div>');
});
}
And this is my controller method
function gallery($offset= 0)
{
$limit = 12;
$user_id = $this->session->userdata('user_id');
$data = $this->avatar_model->user_avatars($user_id,$limit,$offset);
$avatars = array();
$count = $this->avatar_model->count_user_avatars($user_id);
$pages = ceil($count/$limit);
foreach($data as $key => $avatar)
{
$dat['avatar_id'] = $avatar->avatar_id;
$dat['avatar_src'] = $avatar->avatar_small;
$dat['create_date'] = time("d-m-Y",$avatar->create_date);
$avatars[] = $dat;
}
$server_response['avatar_count'] = $count;
$server_response['avatars'] = $avatars;
echo json_encode($server_response);
}
I dont really have an idea on how to paginate the data returned from the reques.
Please point me in the right direction
It's easy. Add a class to your pagination link (you can use full_tag_open and full_tag_close config variable: <p class="pagination> and </p>).
After that you can redefine the .pagination a click event (I'm using JQuery):
function () {
$(".pagination a").click(function(event){
event.preventDefault();
YourJSFunction($(this).attr("href"));
});
}
I hope this helps you.
Related
So I'm working with datatables and where I can edit the values in the datatables. I ran into a problem with actually saving the changes, at first this method worked but when I came back the next day it just didn't want to work anymore.
Is there anything obvious I'm missing here? Or is there something more to the story?
Server side code:
case 'form_save': {
$form_id = !empty($post['form_id']) ? $post['form_id'] : false;
$data = array();
$where = array('id'=>$this->db->escape($post['id']));
if(!empty($form_id)) {
switch($form_id) {
case 'translations': {
$data['value'] = $this->db->escape($post['value']);
$rc['success'] = $this->db->update('translations',$data,$where);
break;
}
case 'carousel': {
$data['title'] = $this->db->escape($post['title']);
$data['src'] = $this->db->escape($post['src']);
$data['alt'] = $this->db->escape($post['alt']);
$data['slide_url'] = $this->db->escape($post['slide_url']);
$data['slide_order'] = $this->db->escape($post['slide_order']);
$rc['success'] = $this->db->update('carousel',$data,$where);
break;
}
}
}
JQuery code:
$(document).on('submit','form',function(){
var $form = $(this);
var $error = $form.find('div.error');
var form_id = $form.attr('id');
var $modal = $(document).find('.modal');
var data = $form.serializeArray();
data.form_id = form_id;
data.type = 'form_save';
$.post('/admin_get/',data,function(rc){
if(rc.success) {
$modal.modal('hide');
$modal.find('modal-title').html('');
$modal.find('modal-body').html('');
} else {
$error.html(rc.error).show();
$error.html('').hide();
}
},'json');
});
});
EDIT: forgot to add the edit form jquery side :
$(document).on("click", ".edit", function(){
var id = $(this).data('id');
var table = $(this).closest('table').attr('id');
var $modal = $(document).find('.modal');
$.post('/admin_get/', {id:id, type:'get_form', table:table}, function(data){
$modal.find('.modal-title').html(data.title);
$modal.find('.modal-body').html(data.html);
$modal.find('.modal-body').find('#summernote').summernote();
$modal.find('.modal-body').find('.select2').select2();
$modal.modal('show');
},'json');
});
designing a Facebook like scrolling system the data shows but it does not show the first 5 values and it shows the values in repetition
here is my code:
view:
$(document).ready(function() {
var total_record = 0;
var total_groups = <?php echo $total_data; ?>;
$('#results').load("<?php echo base_url() ?>user/load_more", {'group_no':total_record}, function() {total_record++;});
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height())
{
if(total_record <= total_groups)
{
loading = true;
$('.loader_image').show();
$.post('<?php echo site_url() ?>user/load_more',{'group_no': total_record},
function(data){
if (data != "") {
$("#results").append(data);
$('.loader_image').hide();
total_record++;
}
});
}
}
});
});
then my controller
public function load_more()
{
$group_no = $this->input->post('group_no');
//print_r($group_no);
$content_per_page = 10;
$start = ceil($group_no * $content_per_page);
//print_r($start);
$this->load->model('Pmodel');
$user_id = $this->session->userdata('user_id');
$all_content = $this->Pmodel->get_all_content($user_id,$start,$content_per_page);
// echo '<pre>';
//print_r($all_content);
if(isset($all_content) && is_array($all_content) && count($all_content)) :
foreach ($all_content as $key => $content) :
echo '<li>'.$content->status.'</li>';
echo '<p>'.$content->status_image.'</p>';
endforeach;
endif;
// echo '<pre>'; print_r($this->data['labels_message']); exit;
}
and then my model
public function get_all_content($id,$start,$content_per_page)
{
$query=$this->db->select('*')
->from('post_status')
->where('user_id',$id)
->limit($start,$content_per_page)
->get();
//echo "<pre>";
//print_r($query);
//var_dump($query);
$result = $query->result();
//echo "<pre>";
//print_r($result);
return $result;
}
how to show the data according to the database
let me add a image for database
I have been struggling with this for a while. There are tons of topics on the subject but none is actually working for me, but being a newbie might be the cause so please elaborate.
I simplified the code and it won't work, I posted the code below
I am queering the Database, and saving the values to an array in a function
I then need to pass that array to a jquery in the same function. I used json_encode but i am getting this error:
Uncaught SyntaxError: Unexpected token <
Here is the code:
function Test()
{
$query1 = $wpdb->get_results("SELECT(element_value) FROM wp_piic_formmaker_submits WHERE form_id = 13 AND element_label = 1 AND user_id_wd = 1 ORDER BY date asc", OBJECT);
if($query1)
{
foreach($query1 as $q)
{
$PHPArray[$i] = $q->element_value ;
$i = $i + 1;
}
}
$UserInput = "<script type='text/javascript'>
jQuery('#wdform_1_element13').on('change',function()
{
var test = <?php echo json_encode($PHPArray); ?>;
jQuery.each(test , function (i, elem)
{
alert('here');
});
});
</script>";
return $UserInput ;
}
Change it to this:
$UserInput = "<script type='text/javascript'>
jQuery('#wdform_1_element13').on('change',function()
{
var test = ".json_encode($PHPArray)."; //Notice the change here
jQuery.each(test , function (i, elem)
{
alert('here');
});
});
</script>";
return $UserInput ;
}
You have to escape the string correctly:
function Test()
{
$query1 = $wpdb->get_results("SELECT(element_value) FROM wp_piic_formmaker_submits WHERE form_id = 13 AND element_label = 1 AND user_id_wd = 1 ORDER BY date asc", OBJECT);
if($query1)
{
foreach($query1 as $q)
{
$PHPArray[$i] = $q->element_value ;
$i = $i + 1;
}
}
$UserInput = "<script type='text/javascript'>
jQuery('#wdform_1_element13').on('change',function()
{
var test = " . json_encode($PHPArray) . ";
jQuery.each(test , function (i, elem)
{
alert('here');
});
});
</script>";
return $UserInput ;
}
If you put PHP inside JavaScript the PHP part is only text, do this:
function Test()
{
$query1 = $wpdb->get_results("SELECT(element_value) FROM wp_piic_formmaker_submits WHERE form_id = 13 AND element_label = 1 AND user_id_wd = 1 ORDER BY date asc", OBJECT);
if($query1)
{
foreach($query1 as $q)
{
$PHPArray[$i] = $q->element_value ;
$i = $i + 1;
}
}
$UserInput = "<script type='text/javascript'>
jQuery('#wdform_1_element13').on('change',function()
{
var test = " . json_encode($PHPArray) . ";
jQuery.each(test , function (i, elem)
{
alert('here');
});
});
</script>";
return $UserInput ;
}
At least from what is shown, neither $i nor $PHPArray are initialized. PHP can be messy about these things, but you cannot directly refer to indexes of non-existent arrays, or variables that have not been declared.
I'll guess the token error was from your browser trying to deal with the text output of a PHP error being flushed, along the lines of 'undefiend' or 'undefined index.'
Also, the real (or at least convenient) purpose of the foreach construct is not fooling with indexes. Try the following substitute for your current loop:
$PHPArray = array(); // $PHPArray = [];
if($query1){
foreach($query1 as $q){
$PHPArray[] = $q->element_value;
}
}
Beyond that, "wpdb" suggests calls related to specific frameworks, but in case this is a mysqli_stmt call, i believe the call is singular: get_result.
I am using the below code to create a YUI datatable with dynamic data(columns). But am facing a issue in server side pagination. As of now it is working fine with client side pagination, but I need server side pagination, so that my page loading time will get reduced. Can you help me on this to fix the issue. Since I'm struggling in this area for past 2 days.Server side pagination with AJAX to render the data is my expectation.
Here is the code I Used
DataProvider.prototype = {
url:null,
data:null,
ds:null,
getData:function() {return this.data},
initialize:function(){
var str = generateRequest();
var newUrl = this.url+str;
YAHOO.util.Connect.asyncRequest('GET', newUrl, this);
},
success:function(response){
var responseVal = YAHOO.lang.JSON.parse(response.responseText);
var columnList = responseVal.columnList;
var sortedBy = responseVal.sortedBy;
this.data = responseVal.results;
if(this.data == '') {
$('#dynamicdata').html('<font style="color:red;"> No Data Found!</font>');
} else {
this.ds = new YAHOO.util.FunctionDataSource(function(){return this.dataProvider.getData()});
this.ds.responseSchema = {
resultsList:"results",
fields:columnList,
// Access to values in the server response
metaFields: {
totalRecords: "totalRecords",
startIndex: "startIndex"
}
}
this.ds.dataProvider = this;
// DataTable configuration
var myConfigs = {
paginator: new YAHOO.widget.Paginator({ rowsPerPage:20 }), // Enables pagination
width:"80%", height:"auto"
};
// FORMATTING CELL COLOUR BASED ON THEIR VALUES
var myCustomFormatter = function(elLiner, oRecord, oColumn, oData) {
var columnKey = oColumn.getKey();
var frmCurrentPeroid = $('#from').val();
//var frmCurrentPeroid = '2013-03-13';
var defaultLabels = ['Product type','Total 1','Total 2','Change'];
if (isDate(columnKey) && $.inArray(columnKey, defaultLabels) === -1) {
if(columnKey < frmCurrentPeroid) {
YAHOO.util.Dom.addClass(elLiner.parentNode,'orange');
elLiner.innerHTML = oData;
//alert('blue');
} else {
YAHOO.util.Dom.addClass(elLiner.parentNode,'blue');
elLiner.innerHTML = oData;
}
} else {
if(columnKey == 'Total 1') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'orange');
elLiner.innerHTML = oData;
//alert('blue');
}
else if(columnKey == 'Total 2') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'blue');
elLiner.innerHTML = oData;
//alert('blue');
}
else if(columnKey == 'Change') {
split_data = oData.toString().split('_');
var fieldData = null;
var fieldFormatter = null;
fieldData = split_data[0];
fieldFormatter = split_data[1];
if(fieldFormatter == 'green') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'green');
elLiner.innerHTML = fieldData;
}
if(fieldFormatter == 'red') {
YAHOO.util.Dom.addClass(elLiner.parentNode,'red');
elLiner.innerHTML = fieldData;
}
}
else if(columnKey == 'Product Name') {
var filterStr = oData.substring(0,30);
elLiner.innerHTML = ''+filterStr+'';
//alert('blue');
}
else {
elLiner.innerHTML = oData;
}
}
};
// Add the custom formatter to the shortcuts
YAHOO.widget.DataTable.Formatter.myCustom = myCustomFormatter;
//YAHOO.widget.DataTable.formatLink = formatLink;
/* make call to initialize your table using the data set */
var myDataTable = new YAHOO.widget.DataTable("dynamicdata", columnList, this.ds, myConfigs);
}
}
}
Followed the code posted in this page
Click here
Thanks in Advance,
Raja
I haven't been doing YUI2 for quite some time so I am no longer able to help you directly. Perhaps this example can help: http://www.satyam.com.ar/yui/#ServerDriven . I do remember that there were big changes in 2.6 and this examples are marked 2.4, perhaps they no longer work.
I'm trying to do a realllly simple post of a javascript variable to a php file.
Jquery bit in keyinput.php:
<script type="text/javascript">
var imgArray = [<?php echo implode(',', getImages($cat, $site)) ?>];
$(document).ready(function() {
var img = document.getElementById("showimg");
img.src = imgArray[<?php echo $imgid ?>];
var imgIndex = <?php echo $imgid ?>;
$(document).keydown(function (e) {
var key = e.which;
int rightarrow = 39;
int leftarrow = 37;
int random = 82;
if (key != rightarrow && key != leftarrow && key != random) {
return;
}
else {
//next image: right arrow
if (key == rightarrow)
{
imgIndex++;
if (imgIndex > imgArray.length-1)
{
imgIndex = 0;
}
img.src = imgArray[imgIndex];
}
//last image: left arrow
if (key == leftarrow)
{
if (imgIndex == 0)
{
imgIndex = imgArray.length;
}
img.src = imgArray[--imgIndex];
}
//random: r
if (key == random)
{
imgIndex = Math.floor((Math.random()*(imgArray.length-1))+1);
img.src = imgArray[imgIndex];
}
}
$.post('./templates/viewcomic.php', {variable: imgIndex});
});
});
</script>
<?php
function getImages($catParam, $siteParam) {
include './scripts/dbconnect.php';
if ($siteParam == 'artwork') {
$table = "artwork";
}
else {
$table = "comics";
}
if ($catParam != null) {
$catResult = $mysqli->query("SELECT id, title, path, thumb, catidFK FROM $table WHERE catidFK = $catParam");
}
else {
$catResult = $mysqli->query("SELECT id, title, path, thumb, catidFK FROM $table");
}
$img = array();
while($row = $catResult->fetch_assoc())
{
$img[] = "'" . $row['path'] . "'";
}
return $img;
}
?>
PHP bit in viewcomic.php:
include './scripts/keyinput.php';
$JSIndex = $_POST['variable'];
echo "Index = " . $JSIndex;
//$JSIndex should be equal to the javascript variable imgIndex... but it outputs nothing
Any thoughts would be extremely helpful! I'm trying to get my comics website to go live.
Thanks!
Your logic is wrong: at the moment you define your key variable, e is undefined. Then you attach your event handler inside an if statement that will always evaluate to false so that will never work.
The assignment to key should be inside your event handler and the conditional needs to go, you already have that inside your event handler.
Edit: you should also only do your ajax call if one of your action keys is pressed (put it inside the event handler) and do something with the result.
Edit 2: Checkout the manual on $.post, you should add a callback function to process the return value of your php script.
For example:
$.post(
'./templates/viewcomic.php',
{ variable: imgIndex },
function(data) { /* data contains what you have echoed out in your php script */
alert(data);
}
);