Google style page loading , Bulk records not on onload, display some and fetch remain in back? - ajax

I'm developing a web application,after login the user is redirected to the inbox page,
where he will find many widgets, each with hundreds of records.
So it is taking too much time to open inbox page after login success.Very much performance issue.
So i want to display some(5-10) records in each widget
and after the page loads in the backend(user doesn't know) the request will be processing still and fetch the records and append them to the widget records.
Eg. If you open google images and search for cricket, it will display the page with images and if you scroll down only you will come to know the ajax request going and appending the response to the web page,
But it is not waiting till the entire page is loaded.
I must develop my application in the same way.
Any idea is Highly Appreciated and sample code too.

This should work for you, Mr.Chowdary.
You would need something to handle your requests in the backend. Since you did NOT specify whether you used Java or PHP or Python or whatever, I used PHP - its what I know best :D
PSEUDO CODE (loadmore.jsp)
Begin
widget = URL(widget) //the widget id or name
page = URL(page) //the page being retrieved
switch (widget)
{
case "widget1":
data_for_widget1 = paginated_query1(page)
print data_for_widget1
break
case "widget2":
data_for_widget2 = paginated_query2(page)
print data_for_widget2
break
default :
print "Invalid Widget"
break
}
End
PHP Version
<?php
if (isset($_GET['page'])) {
$widget = $_GET['page'];
$page = $_GET['page'];
switch ($widget) {
case "MyWidget1": //dynamic example
$manyManyItems; //A massive array of items
$pages = array_chunk($manyManyItems, 5); //break it up into chunks of 5 items
if( array_key_exists ($pages[$page]) )
for ($i = 0; $i < count($pages[$page]); $i++) { //load those chunks
echo '<div class="item">'.$pages[$page][$i].'</div>';
}
else {
echo "zero"; //code word that tells ajax that there is nothing more to load
}
break;
case "MyWidget2": //manual example
if($page==1) { //loads the first chunck manually
echo '<div class="item">dynamic content 1</div>';
echo '<div class="item">dynamic content 2</div>';
echo '<div class="item">dynamic content 3</div>';
}
elseif($page==2) { //loads the next batch
echo '<div class="item">dynamic content 1</div>';
echo '<div class="item">dynamic content 2</div>';
echo '<div class="item">dynamic content 3</div>';
}
else
echo "zero"; //code word that tells ajax that there is nothing more to load
break;
default:
echo "zero"; //code word that tells ajax that there is nothing more to load
}
}
?>
HTML
Each widget could look like this
<div id="MyWidget1" class="widget" data-widgetPage="0">
<div class="item">default content</div>
<div class="item">another default content</div>
...
<div class="loadmoreajaxloader" style="display:none;"><center>Loading...</center></div>
</div>
Javascript
<script type="text/javascript">
$(".widget").scroll(function()
{
if($(this).scrollTop() == $(this).height() - $(this).height())
{
var nextPage = eval($(this).attr("data-widgetPage") + 1);
$(this).find('.loadmoreajaxloader').show();
$.ajax({
url: "loadmore.php?widget="+$(this).attr("id")+"&page="+nextPage,
success: function(html)
{
if(html != "zero")
{
$(this).append(html);
$(this).('.loadmoreajaxloader').hide();
}else
{
$(this).find('.loadmoreajaxloader').html('<center>No more posts to show.</center>');
}
}
});
$(this).attr("data-widgetPage", nextPage);
}
});
</script>
Success with the app.

I got to know the following answer suits my requirement from the following site.. Jquery endless scrolling

Related

Can't get wordpress ajax form to submit

I am porting an application to WordPress. It uses a form to select what attributes the customer is looking for in an Adult Family Home via checkboxes and drop-downs. It re-searches the database on each onchange and keyup. Originally I had the application standalone in PHP, but when I migrated it to WordPress I started having issues.
Currently in WP I have the code conditionalized ($DavesWay == 1) to do ajax the normal no-WordPress-way and ($DavesWay == 0) to do it the WordPress-way.
In the non-WordPress-way, the ajax works fine EXCEPT that I get a WP header and menu between the search form and the results-div that Ajax puts the data in. I get no errors from WP or in the JS console. In the WP-way The search form displayed, but nothing happens when I check any of the checkboxes. The JS console displays
POST http://localhost/demo4/wp-admin/admin-ajax.php 400 (Bad Request)
But I don't see any way to tell exactly what it is complaining about. How should I troubleshoot this?
Troubleshooting = Examine the HTML output, lots of echos and exits in PHP code, look at JS console.
function submitPg1(theForm) {
// Used with onChange from "most" form elements, but not on those that change the page
// rather than the select criteria. Such as rowsPerPage, pageNumber etc.
setById("pageNo", "1"); // set inital page
mySubmit();
}
function mySubmit(theForm) { // The actual ajax submit
// DO NOT set page number
jQuery.ajax({ // create an AJAX call...
data: jQuery("#asi_search_form").serialize(), // get the form data
type: jQuery("#asi_search_form").attr("method"), // GET or POST
url: jQuery("#asi_search_form").attr("action"), // the file to call
success: function (response) { // on success..
jQuery("#result").html(response); // update the DIV
}
})
}
function setById(id, value) { // Used to set vales by Id
x = document.getElementById(id).value;
x.value = value;
}
// 1st submit with blank selection
jQuery(document).ready(function () { submitPg1(this.form) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Code fragments: (from the displayed page source)
<div id="asi_container" class="asi_container" >
<noscript><h2>This site requires Javascript and cookies to function. See the Help page for how to enable them.</h2></noscript>
<div id="searchForm">
<form id="asi_search_form" name="asi_search_form" method="post" action="http://localhost/demo4/wp-admin/admin-ajax.php">
<input type="hidden" name="action" value="asi_LTCfetchAll_ajax" style="display: none; visibility: hidden; opacity: 0;">
<table id="greenTable" class="asi_table" title="The Green areas are for site administration, not typical users">
<tbody>
PHP code:
$DavesWay = 0;
if ($DavesWay == 1){ //echo "Daves Way Setup"; // Dave's way, which works but prints the menu twice
if( $operation == "submit"){
require("asi_LTCfetchAll.php"); // for each onchange or onkeyup
}else{
add_filter( 'the_content', 'asi_tc_admin', '12' ); // Initial page refresh # must be >12
}
}else{
// The WordPress way that I could't get to work -- asi_LTCfetch never gets called
function asi_LTCfetchAll_ajax(){
//echo "<br /> Goto to Submit function"; // DEBUG
require($asi_plugin_dir . "/includes" . '/asi_LTCfetchAll.php');
}
add_action( "wp_ajax_asi_LTCfetchAll_ajax", "asi_LTCfetchAll_ajax" ); // admin users
add_action( "wp_ajax_nopriv_asi_LTCfetchAll_ajax", "asi_LTCfetchAll_ajax" ); // non-logged in users
add_filter( "the_content", "asi_tc_admin", "12" ); // Initial page refresh # must be >12
}
Try changing the JavaScript to the way WordPress recommends it in their documentation:
var data = {
'action': 'my_action',
'whatever': 1234
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
I suggest trying following URL: https://codex.wordpress.org/AJAX_in_Plugins
Also you can use the plugin: https://wordpress.org/plugins/ajax-search-lite/

cakephp ajax function issue

I have 2 functions in "events" (index, event_ajax)controller in my cakephp(2.5) web site. I'm trying to load HTML block to 'index.ctp' page by calling to 'event_ajax' function using ajax. When I call to this function it shows nothing. Look at 'net' tab in firebug it shows internal server error and 'net'->'Response' tab I can see whole layout is loaded.
I'm little confuse about in this scenario, can any one give a little explanation for following questions??? thanks in advance :)
Is it possible to call actions in same controller using ajax function ??
How 'Response' tab shows layout when '$this->layout' is set to NULL ??
when type url 'example.com/events/event_ajax', output data still '$this->autoRender=false'. how can this happen ??
this is my 'event_ajax' action.
public function event_ajax($x=1) {
$this->layout = NULL;
$this->autoRender = false ;
$contName = $this->Page->conName($x);
$latestContEvents = $this->Page->latestContEvent($x);
$internal = '';
if (!empty($latestContEvents)){
foreach ($latestContEvents AS $latestContEvent){
$internal .= '<li class="pull-left"> <div class="content-wrapper">'..... //do something
}
else {
$internal = '<p> No events found for this continent</p>';
}
$ContEvents = '<div class="carousel events-location-carousel">'.$internal.'</div> ';
return $ContEvents;
// return json_encode($ContEvents);
}
Try with
$this->layout = 'ajax';

wordpress ajax pagination breaks after 10 pages

Can someone help me with ajax pagination please, i'm on it 2 days already and can't figure it out. I have Load More style pagination, this is the code, preety classic(down below).
Everything works as planing except when the placeholder reaches page 10. Then, hell break loose and nothing is loading anymore. The button still works untill maxpages is reached and so the button gets removed, but nothing happens with more than 10 placeholders. The website i'm currently using this scriptand the place you can test yourself is this: http://filmhdonline.com/category/toate-filmele/
I would appreciate someone having an ideea what i'm talking about. Thanks in advance.
jQuery(document).ready(function() {
// The number of the next page to load (/page/x/).
var pageNum = parseInt(pbd_alp.startPage);
// The maximum number of pages the current query can return.
var max = parseInt(pbd_alp.maxPages);
// The link of the next page of posts.
var nextLink = pbd_alp.nextLink; pageNum++;
//Load more videos translation
var more = pbd_alp.more;
//Loading videos translation
var loading = pbd_alp.loading;
/**
* Replace the traditional navigation with our own,
* but only if there is at least one page of new posts to load.
*/
if(pageNum <= max) {
// Remove the traditional navigation.
jQuery('.pagination').remove();
// Insert the "More Posts" link.
if( jQuery('#content').find('ul.listing-videos').length == 1 ){
jQuery('#content ul.listing-videos').append('<li class="more-posts pbd-alp-placeholder-' + pageNum + '"></li>');
jQuery('#content').append('<p id="pbd-alp-load-posts" class="pagination">' + more + '</p>');
}
}
/**
* Load new posts when the link is clicked.
*/
jQuery('#pbd-alp-load-posts a').click(function() {
// Are there more posts to load?
if(pageNum <= max) {
// Show that we're working.
jQuery(this).text(loading);
jQuery('.pbd-alp-placeholder-'+ pageNum).load(nextLink + ' #content ul.listing-videos li',
function() {
//jQuery('.pbd-alp-placeholder-'+ pageNum).children('li').unwrap();
console.log(pageNum);
jQuery(this).children().hide();
$newContent = jQuery(this).children().unwrap();
$newContent.fadeIn('fast');
// Update page number and nextLink.
pageNum++;
nextLink = nextLink.replace(/\/page\/[0-9]?/, '/page/'+ pageNum);
**// Add a new placeholder, for when user clicks again.
jQuery('#content ul.listing-videos').append('<li class="more-posts pbd-alp-placeholder-'+ pageNum +'"></li>');**
// Update the button message.
if(pageNum <= max) {
jQuery('#pbd-alp-load-posts a').text('Vezi mai multe');
} else {
jQuery('#pbd-alp-load-posts a').remove();
}
}
);
} else {
jQuery('#pbd-alp-load-posts a').append('.');
}
return false;
});
});
For ajax pagination in wordpress, You can use the plugin like https://wordpress.org/plugins/wp-pagenavi/.
OR
<div id="content">
<?php
$new_query = new WP_Query();
$new_query->query('post_type=post&showposts=1'.'&paged='.$paged);
?>
<?php while ($new_query->have_posts()) : $new_query->the_post(); ?>
<?php the_title(); ?>
<?php endwhile; ?>
<div id="pagination">
<?php next_posts_link('« Older Entries', $new_query->max_num_pages) ?>
<?php previous_posts_link('Newer Entries »') ?>
</div>
</div><!-- #content -->
<script>
jQuery(function($) {
$('#content').on('click', '#pagination a', function(e){
e.preventDefault();
var link = $(this).attr('href');
$('#content').fadeOut(500, function(){
$(this).load(link + ' #content', function() {
$(this).fadeIn(500);
});
});
});
});
</script>
I Have the same problem.
If it still happening, replace:
nextLink = nextLink.replace(/\/page\/[0-9]?/, '/page/'+ pageNum);
to
nextLink = nextLink.replace(/\/page\/[0-9]*/, '/page/'+ pageNum);
Problem in wrong regex [0-9]? match only single number from 1 to 9. From 10 it takes only 1. Instead [0-9]* match from 0 to infinity. So, it breaks after 9 (form 0 to 9), because next 10 and it's take fore use only 1.

AJAX Div Refresh with PHP

I am trying to refresh some elements on my page every so often. I know theres a million topics on here about that and I have tried to get mine working, but here is what I need to refresh..
This is the code that gets generated when the page loads:
<div id="galleria">
<?php
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
$totalImgs = count($a);
$imgUsed = array();
for ($j = 0; $j < 100; $j++)
{
do
{
$randIndex = mt_rand(0, $totalImgs);
}
while ($imgUsed[$randIndex] === TRUE);
$imgUsed[$randIndex] = TRUE;
echo "<img src='" . $dir . '/' . $a[$randIndex] . "' />";
}
?>
</div>
I would like to automatically refresh this every 10 seconds but not reload the page. I have read up on ajax and it seems this is possible but I cannot seem to get it to work.
All this is doing is showing the galleria div, and loading the 100 images inside the div. Then the galleria script takes over and displays it nicely. Will AJAX work better or JQuery?
Thank you for your help!
"Will AJAX work better or jQuery?" -- AJAX is a technique, jQuery is a library. As it turns out, jQuery has an excellent API for AJAX.
Let's call this bit of PHP "galleria.php". On original page load, it is inserted into the parent PHP page using good ol' <?php include('galleria.php')?>. Now the end user is seeing the full initialized page.
To update it, you have a number of AJAX options available, but the easiest is to include jQuery on your page and then you can use .load() in a script:
var updateGallery = setInterval(function() {
$('#someDiv').load('galleria.php');
}, 10000);
There's room for tweaking... maybe galleria.php doesn't include the <div id="galleria">, which is set on the page. In which case you would load right into #galleria instead of #someDiv and save yourself an unnecessary container. Maybe you cache the $('#someDiv') object by declaring it in a different scope so that it can be re-used. But this is the general gist.
Use setInterval function with ajax call.
http://jquery-howto.blogspot.com/2009/04/ajax-update-content-every-x-seconds.html
As I wrote here you can fill a div with a jQuery ajax call.
<html>
<head>
<script type="text/javascript">
function refresh_gallery(){
$.ajax({
type: "POST",
url: "generate_gallery.php", // your PHP generating ONLY the inner DIV code
data: "showimages=100",
success: function(html){
$("#output").html(html);
}
});
}
$(function() {
refresh_gallery(); //first initialize
setTimeout(refresh_gallery(),10000); // refresh every 10 secs
});
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>

jquery ajax codeigniter

I wanted to ask, why does the response from a ajax request using the native ajax not post or get return my entire page? is there anything I should know? I have looked at the documentation on jquery.com and nothing is mentioned of something like that unless i'm looking else where. Can I get any help on why that keeps happening?
This is the function that handles the validation of the form in question.
joe
function showsupport()
{
$this->form_validation->set_rules('supportername','Your Name','trim|required|max_length[20]|xss_clean');
$this->form_validation->set_rules('supporteremail','Email Address','trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('pledgedate','Pledge Date','trim|required|xss_clean');
$this->form_validation->set_rules('messagetxt','Your Message','trim|required|xss_clean');
if($this->form_validation->run() == FALSE)
{
echo validation_errors();
} else {
$this->load->model('support_m');
$name = $this->input->post('supportername');
$email = $this->input->post('supporteremail');
$date = $this->input->post('pledgedate');
$msg = $this->input->post('messagetxt');
$qry = $this->support_m->storepledge($name,$email,$date,$msg);
if($qry){
//$this->template->write_view('content','thanks');
//$this->template->render();
$datamsg['supportmsg'] = 'Message Added Successfully';
}else{
echo 'There was an error inserting into db';
}
}
}
This is the view with the form generated.
<?php
$formdata = array('id'=>'suppform');
echo form_open('homepage/showsupport',$formdata);
$namedata = array('name'=>'supportname','id'=>'supportname','size'=>'30','max_length'=>'25','value'=>set_value('supportname'));
echo '<label for="supportername">Your Name:'.form_input($namedata).'</label><br /><br />';
$emaildata = array('name'=>'supporteremail','id'=>'supporteremail','size'=>'30','max_lenth'=>'25','value'=>set_value('suppoteremail'));
echo '<label for="supporteremail">Email Address:'.form_input($emaildata).'</label><br /><br />';
$pledgedata = array('name'=>'pledgedate','id'=>'pledgedate','size'=>'30','max_length'=>'20','value'=>set_value('pledgedate'));
echo '<label for="pledgedate">Today\'s Date:'.form_input($pledgedata).'</label><br /><br />';
$msgdata = array('name'=>'messagetxt','id'=>'messagetxt','col'=>'2','rows'=>'8');
echo '<label for="messagetext">Your Pledge:'.form_textarea($msgdata).'</label><br />';
$submitdata = array('name'=>'submitbtn','id'=>'submitbtn','value'=>'Send');
echo '<label for="submitbutton">'.form_submit($submitdata).'</label><br />';
echo form_close();
?>
</div>
<div id="errorsechoed"><?php echo validation_errors();?></div>
The html of the retured page is dumped in the div #errorsechoed
$('#suppform').submit(function(eve){
eve.preventDefault();
$.ajax({
type: 'POST',
cache: false,
url: 'homepage/showsupport',
data: $('#suppform').serialize(),
beforeSend: function(){
$('#supportform').block({message:'<h4> Processing...</h4>'})
},
complete: function(){
},
success: function(html){
$('#errorsechoed').text(html);
}
});
});
I have been trying to get this figured out and I think I have made some progress, here is what I have:
a) the template library from William Colin works where regions are specified and so only a particular region will be refreshed all the time and not the only page. As a result it sort of works differently from other standard setups for codeigniter. This is definitely getting in the way of jquery getting a response from the server. It gets the bits of template library (i.e. regions) and renders it out which ends up rebuilding the whole page again.
b) When you run the form_validation library, Template doesn’t allow you to just load a view the normal way in codeigniter, rather you do this by running:
$this->template->write_view('contentregion','viewname'); //writes the view
$this->template->render(); //renders the view on screen.
so if this is not done if validation fails, the error messages spat out by the formvalidation library just never seem to get to the view.
I have tried a lot of permutations of using functions that come with this library and still am just able to render out another page of my site. confused
CONCLUSION:
I think this template library is great but it needs some updating so these issues are met. I will have to look at other templating systems when I have to do a site with a lot of ajax required. Hope Mr. William can see this and help look into this.
Thanks community for an avenue to say what I have learned. Hope this is useful to someone.
It's because you are setting the datatype in the postback to be of type 'html':
"html": Returns HTML as plain text;
included script tags are evaluated
when inserted in the DOM.
if you just want to show that the request succeeded or failed you can have #errorsindicated populated like so:
success: function(){
$('#errorsechoed').html('<h4> Request Successfull...</h4>');
}
error: function(){
$('#errorsechoed').html('<h4> Request Failed...</h4>');
}
you can get more detailed information on the error if you want. See the error option section of the jQuery ajax documentation: http://api.jquery.com/jQuery.ajax/

Resources