<li>
<a id="collection" href="collections.php">
<span class="glyphicon glyphicon-th white"> Collections</span>
</a>
</li>
<script>
$(document).ready(function(){
$("#collection").click(function(){
$.ajax({
type: 'POST',
url: 'pagination.php',
success: function(data) {
$('#cont').show();
}
});
});
});
</script>
pagination.php :
<?php
require_once "database.php";
$db = new Database();
$perPage = 9;
$page = (isset($_GET['page'])) ? (int)$_GET['page'] : 1;
$startAt = $perPage * ($page - 1);
$queryTotalRow = "SELECT COUNT(*) FROM image";
$rsetTotalRow = $db->query($queryTotalRow);
$fetchTotalRow = mysqli_fetch_array($rsetTotalRow);
$totalPages = ceil($fetchTotalRow["0"] / $perPage);
$links = "";
for ($i = 1; $i <= $totalPages; $i++) {
$links .= ($i != $page ) ? "<li><a href='collections.php?page=$i'>Page $i</span></a></li> "
: "<li><a href='collections.php?page=$i'>Page $page</a></li> ";
}
$paginationQuery = "select name,image,price,description from image LIMIT $startAt, $perPage";
$result = $db->query($paginationQuery);
if($result){
echo '<div class="containerCollection" id="cont" style="display:none" >';
while($row = mysqli_fetch_array ($result)){
echo '<div style="float:left" class="divEntry">';
echo "<div align='center' class='nameEntry'>".$row['name']."</div>";
echo '<div align="center"><img src="'.$row['image'].'" class="imageEntry"/></div>';
echo "<div align='center' class='priceEntry'>".$row['price']."</div>";
echo "<div class='descEntry'>".$row['description']."</div>";
echo '</div>';
}
echo "<div class='text-center' style='clear:both'>";
echo "<ul class='pagination'>";
echo $links;
echo '</ul>';
echo '</div>';
echo '</div>';
}
?>
why is this not working ? i trigger an ajax call from collection button click , then i want to return some echoes wrapped in div which i set to hide, then i want to show it.
edit : fully updated my pagination.php seems like at fault .
edit2 : solver using this solution jQuery showing div and then Disappearing
Your response isn't on the page yet. You've just echoed it in a Ajax call.
In your success function take the returned data put it on the page then try and show it i.e
success: function(data) {
$('body').append(data);
$('body #cont').show();
}
This is assuming the data is being returned correctly, I'd put something in our pagination.php that says return json_encode($row) then you have the data in a JSON format in your success function to build the elements you want.
Check your payload and responses in the browser when running the code make sure it returns data. You can then specify an explicit html type to be returned in your ajax, finally append the html like follow:
Apply html:
<!--html-->
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery-1.11.3.js"></script>
<script language="javascript" type="text/javascript" src="script.js"></script>
</head>
<body>
<h1>Test header</h1>
<h2 id="idTxt"></h2>
</body>
</html>
Apply javascript:
//javascript
$(document).ready(function() {
var data = 'name=getData'; //data parameter passed through to execute specific functions
$.ajax({
type: "POST",
url: "function.php",
data: data,
dataType: 'json',
success: function(data) {
$("#idTxt").append(data["html"]);
console.log(data["html"]);
},
error: function(data) {
//console.log(data);
}
});
});
Apply php:
//php
<?php
if (isset($_POST["name"]))
{
$string = "<h4> Hi there </h4>"; //build up html as string
$obj = new stdClass();
$obj->html = $string;
echo json_encode($obj);
}
?>
Also try to replace your POST with a get maybe, remember you are trying to get html response data from the server. Good luck hope it helps. :)
I am struggling to convert json code in CodeIgniter, i wanna make pagination.
I am using ajax and want to controle data convert to json and send it to view. I can someone explain me how to do that.
Code in controler, instead foreach part i am trying to make Json, and send it to view
function ajax(){
$rpp= $_POST['rpp'];
$last = $_POST['last'];
$pn = $_POST['pn'];
if($pn<1){
$pn=1;
}
elseif($pn>$last){
$pn =$last;
}
$l = ($pn - 1) * $rpp;
$this->db->limit($l, $rpp);
$row = $this->db->get('pages');
$dataString='';
foreach($row->result() as $r){
$id = $r->id;
$info = $r->info;
$dataString .= $id.'|'.$info.'||';
}
echo json_encode($dataString);
}
}
view part
function request_page(pn)
{
var rpp = <?php echo $rpp; ?>; // results per page
var last = <?php echo $last; ?>; // last page number
var results_box = document.getElementById("results_box");
var pagination_controls = document.getElementById("pagination_controls");
results_box.innerHTML = "loading results ...";
$.ajax({
type: "POST",
url: "<?php echo site_url('search/ajax')?>",
data: { 'rpp' : rpp , 'last' : last, 'pn' : pn},
dataType: "text",
success: function(msg){
// alert(msg)
;
var dataArray = msg.split("||");
var html_output = "";
for(i = 0; i < dataArray.length - 1; i++){
var itemArray = dataArray[i].split("|");
html_output += "ID: "+itemArray[0]+" - Testimonial from <b>"+itemArray[1]+"</b><hr>";
}
results_box.innerHTML = html_output;
}
});
var paginationCtrls = "";
if(last != 1){
if (pn > 1) {
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b>Page '+pn+' of '+last+'</b> ';
if (pn != last) {
paginationCtrls += '<button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
its easy
you should have a view to encode the data to json. Its just this:
<?php
$this->output->set_header('Content-Type: application/json; charset=utf-8');
echo json_encode($json);
In the controller you just have to load this view with an array as parameter (i think that stdClass is also valid):
$data['json'] = array("foo" => "bar", "bar" => "foo");
$this->load->view('your_json_view', $data);
Why does this code work fine in the unit test, but not in the page? I have Firebug and FirePHP in place and can see the variable pass just fine if I hard code it, the operation is passing an int just fine in the unit test, but I've tried parseInt, Math.floor, and many other wacky methods and the value for statementCount simply won't post.
The ajax:
//polling code
var statementCount = 0;
(function poll(){
setTimeout(function(){
$.ajax({ url: "RROO_update.php",
type: "POST",
data: {'meetID': 2176, 'statementCount': statementCount},
success: function(data){
if(data.length > 0){
var statements = JSON.parse(data);
//reset the statement count
statementCount = statementCount + statements.length;
$(this).actplug_RROO('formatReturns', statements, userID);
poll();
}
},
error: function(){
poll();
},
});
}, 5000);
})();
and the php:
<?php
include("../inc/variables.php");
error_reporting (E_ALL ^ E_NOTICE);
require_once('../FirePHPCore/FirePHP.class.php');
require_once('../FirePHPCore/fb.php');
$firephp = FirePHP::getInstance(true);
ob_start();
$MeetingID = $_POST['meetID'];
$StatementCount = (int)$_POST['statementCount'];
$firephp-> log($StatementCount, 'Statement count passed in' );
$Finished = FALSE;
while($Finished == FALSE){
$MeetingStats = mysql_query("SELECT RROO_UPDATE.*, MEMBER.UserName, MEMBER.UserImage FROM RROO_UPDATE JOIN MEMBER ON RROO_UPDATE.MemberID = MEMBER.MemberID WHERE MeetingID = $MeetingID ORDER BY TimeStamp DESC", $DB_Connection);
$MyNum = mysql_num_rows($MeetingStats);
$firephp->log($MyNum, 'Row Query');
if($MyNum > $StatementCount){
$Returns = array();
while($Return = mysql_fetch_array($MeetingStats)){
array_push($Returns, $Return);
}
$NewReturns = array();
$NewStats = $MyNum - $StatementCount;
$firephp->log($NewStats, 'heres the new stats count');
for($i = 0; $i < $NewStats; $i++){
array_push($NewReturns, $Returns[$i]);
}
$Here = count($NewReturns);
$firephp->log($Here, 'The length of the new returns array');
$Finished = TRUE;
echo json_encode($NewReturns);
}
else{
sleep(3);
}
}
?>
Like I said, it comes back fine on the unit test which is the same in all the aspects I can see (I actually copy pasted it into the page) the only difference being that the postback is routed differently on the page (to the plugin) but I've messed around with callback to no avail. Is there some reason the statementCount won't reset and Post in this code?
I don't think that statementCount is defined inside the callback, only in the function which executes the ajax call.
Here is a question and answer which should help you do what you want.
After searching for a long time I've decided to just ask it here, since the things I found either don't work(or I can't get them to work ;)) - or require me to change things on my server, which I would like to avoid.
I want below function to show the output after each result, so the function doesn't have to be loaded first, which takes a long time. My idea, as you can see below, was to try this with jQuery(1.8.2).
It doesn't work and I simply can't get it to work. Is there a better way to do this? Did I make a mistake somewhere causing it not to work?
If you need additional information, please ask.
<?php
print_r($_POST);
if(isset($_POST['p']) && isset($_POST['domain']) && isset($_POST['option']))
{ error_reporting(0);
define('INCLUDE_CHECK',true);
require('admin/API/class_api.php');
require('admin/functions/core.inc.php');
$dom = explode('.',$_POST['domain']);
$dom = $dom[0];
$ext = array('nl','be','eu','net','com','org','biz','info','tk','ws','gr','me','cc','in','gs','name','ch','co','tv','ru','bz','li','lu','pl','se','vg','cx','tl','im','sg','ms','sh','io','mu','fm','am','xxx','ag','sc','nf','md');
if ($_POST['loop']==40)
{ print 'Laatste loop dus .. STOP : .'.$ext[41]; }
else
{ print 'Loop: '.$_POST['loop'].' - zoek op : .'.$ext[$_POST['loop']];
?>
<script>
$.post('test.php', { p:'full', domain:dom, option:opt, loop:'<?php echo $_POST['loop']+1; ?>'},
function(data){
$('#domresults2').css('display','block').html(data);
$('#domloading').css('display','none');
});
</script>
<?php
}
}
?>
//Start JS
<script>
$('#domsubmit.complete').click( function() {
var dom = escape($('#domsearch').val());
var opt = escape($('#option').val());
$('#domresults2').css('display','none').html('');
$('#domloading').css('display','inline');
$.post('test.php', { p:'full', domain:dom, option:opt, loop:0},
function(data){
$('#domloading').css('display','none');
$('#domresults2').css('display','block').html(data);
});
return false;
});
</script>
//end JS
///////////////////////////
update : solved!
so, what went wrong? -> the php function in core.inc.php referred to a incompatible with jQuery 1.8.2 lib ('qTip2'). Thanks for the support!
<?php
print_r($_POST);
if (isset($_POST['p']) && isset($_POST['domain']) && isset($_POST['option'])) {
error_reporting(0);
define('INCLUDE_CHECK', true);
require('admin/API/class_api.php');
require('admin/functions/core.inc.php');
$dom = explode('.', $_POST['domain']);
$dom = $dom[0];
$ext = array('nl','be','eu','net','com','org','biz','info','tk','ws','gr','me','cc','in','gs','name','ch','co','tv','ru','bz','li','lu','pl','se','vg','cx','tl','im','sg','ms','sh','io','mu','fm','am','xxx','ag','sc','nf','md');
$loop = $_POST['loop'];
DomCheck($_POST['domain'],$ext[$_POST['loop']]);
if ($loop != count($ext)) {
$loop++;?>
<script type="text/javascript">
var opt = '<?php echo $_POST['option']; ?>';
var dom = '<?php echo $_POST['domain']; ?>';
$.post('test.php', { p:'full', domain:dom, option:opt, loop:'<?php echo $loop; ?>'},
function(data){
$('#domresults2').css('display','block').append(data);
<?php if ($loop < count($ext)) {
echo "$('#domloading').css('display','none');";
} ?>
});
</script>
<?php
}
}
?>
One thing you need to understand is that PHP executes on the server and JavaScript (jQuery) executes on the client.
This means that by the time jQuery starts executing, PHP is done.
However, I don't see a loop anywhere in your code. I think this is more of what you wanted. You're not doing a "PHP loop using jQuery," you're outputting jQuery code in a PHP loop:
<?php
if (isset($_POST['p']) && isset($_POST['domain']) && isset($_POST['option'])) {
error_reporting(0);
define('INCLUDE_CHECK', true);
require('admin/API/class_api.php');
require('admin/functions/core.inc.php');
$dom = explode('.', $_POST['domain']);
$dom = $dom[0];
$ext = array('nl','be','eu','net','com','org','biz','info','tk','ws','gr','me','cc','in','gs','name','ch','co','tv','ru','bz','li','lu','pl','se','vg','cx','tl','im','sg','ms','sh','io','mu','fm','am','xxx','ag','sc','nf','md');
foreach ($_POST['loop'] as $loop) {
if ($loop == 40) {
print "Laatste loop dus .. STOP : .{$ext[41]}";
} else {
print "Loop: {$loop} - zoek op : .{$ext[$loop]}";
?> <script>
$.post('test.php', { p:'full', domain:dom, option:opt, loop:'<?php echo $loop; ?>'},
function(data){
$('#domresults2').css('display','block').html(data);
$('#domloading').css('display','none');
});
</script>
<?php }
}
}
?>
Within my index.php file I have an AJAX function that will call a function within another php file which should increment a number and return it whenever i call the AJAX function.
The problem is that the number never changes. I have tried lots of different things. Too many to list them all unfortunately.
My index.php file.
<?php
session_start();
$_SESSION['views'] = 0;
?>
<?php include 'blogFunction.php';?>
<script type="text/javascript">
function doSomething()
{
$.ajax({ url: '/blogFunction.php',
data: {action: 'test'},
type: 'post',
success: function(output) {
document.getElementById("blog").innerHTML = '';
document.getElementById("blog").innerHTML = output;
}
});
}
</script>
<div class ="blog" id = "blog"></div>
my blogFunction.php
<?php
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : blogreturn();break;
}
}
function blogreturn(){
$_SESSION['views'] = $_SESSION['views']+ 1;
echo "THIS number is:" .$_SESSION['views'];
}
?>
Right now the output is always '1' whenever i hit the button that calls the AJAX function.
Any help appreciated.
Live Code:here
Thank you all for the help so far. One problem down, a new problem appears.
Extended Functionality:
session_start();
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : blogreturn();break;
}
}
function blogreturn(){
$request_url = "http://retrovate.tumblr.com/api/read?type=posts";
$xml = simplexml_load_file($request_url);
$a = $_SESSION['views'];
$b = $_SESSION['views'] +4;
echo "A = ".$a;
echo "B = ".$b;
$_SESSION['views'] = $_SESSION['views']+ 1;
for ($i = $a; $i <= $b; $i=$i+1) {
echo '<h2>'.$xml->posts->post[$i]->{'regular-title'}.'</h2>';
echo '<br>';
echo $xml->posts->post[$i]->{'regular-body'};
echo '<br>';
echo '<br>';
}
}
The problem that lies here, is, I click my button once at my site
and it increments and shows the new content. I click again and it reverts back to 0. If I click the button numerous times fast, it seems to work. It seems that chrome is having this problem whereas Firefox is not.
Add session_start(); to blogFunction.php
Here's the properly working code...
index.php
<?php
session_start();
$_SESSION['views'] = 0;
?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js" />
<body>
<div class ="blog" id = "blog"></div>
<input type="button" value="Add to the count!" id="call_ajax"/>
<script type="text/javascript">
$('#call_ajax').click(function () {
$.ajax({ url: '/blogFunction.php',
data: {action: 'test'},
type: 'post',
success: function(output) {
document.getElementById("blog").innerHTML = '';
document.getElementById("blog").innerHTML = output;
}
});
});
</script>
</body>
blogFunction.php
<?php
session_start();
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : blogreturn();break;
}
}
function blogreturn(){
$_SESSION['views'] = $_SESSION['views']+ 1;
echo "THIS number is:" .$_SESSION['views'];
}
?>
Notice that I'm not including blogFunction.php in the index.php file! That's important.
The other way you had it, you were setting the variable to 0 each time the page loaded, which was how the function was called (if you used the console to call it).
I added a button for you to click to call the function via Ajax (per your conditions in the original question).
Hope that helps!
You need to call session_start () in your blogFunction.php file. It has to be called before any output to the brower. Probably best case would be to call it first in the script.
I think that you should first unset $_SESSION['views'] and than write again.
function blogreturn(){
$temp = $_SESSION['views'];
unset($_SESSION['views']);
$_SESSION['views'] = $temp + 1;
echo "THIS number is:" .$_SESSION['views'];
}