I've create a page that load 10 elements and at the bottom of the page I've placed the classic button "load more" to load 10 more elements.
The problem is with jQuery, the style given by :nth-child() property doesn't work for the next 10 elements and so on.
Is there a solution to solve this problem?
E.g.:
File main.js
$("#main_content > p:nth-child(3n+2)").addClass("small-product-wrapper");
$("#main_content > p:nth-child(3n+3)").addClass("small-product-wrapper");
File example.php
<script type="text/javascript">
$('#more_button').click(function(){
loaded_messages += 10;
$('#loading').ajaxSend(function() {
$("#loading").stop(true,true).fadeIn().delay(200).fadeOut();
});
var dati = "twitterpagination/get_messages/" + loaded_messages;
$.ajax({
url:'twitterpagination/get_messages/' + loaded_messages,
type: 'get',
data: dati,
cache: false,
success: function() {
$.get(dati, function(data){
$("#main_content").append(data);
});
if(loaded_messages >= num_messages - 10) {
$("#more_button").hide();
}
},
error: function() {
// do nothing
}
});
return false;
});
</script>
<div id="main">
<?php
foreach($latest_messages as $message) {
echo '<p>'.$message->message .'</p>';
}
?>
<div id="more_button">more</div>
</div>
File loaded by Ajax url:
<?php
foreach($latest_messages as $message) {
echo '<p>'.$message->message .'</p>';
}
?>
In the file loaded by ajax:
<?php
foreach($latest_messages as $message) {
echo '<p class="small-product-wrapper">'.$message->message .'</p>';
}
?>
Add the style to the returned P tag
You need to re-run those 2 jQuery lines right after the new html is added from your AJAX.
success: function() {
$.get(dati, function(data){
$("#main_content").append(data);
// here
$("#main_content > p:nth-child(3n+2)").addClass("small-product-wrapper");
$("#main_content > p:nth-child(3n+3)").addClass("small-product-wrapper");
});
}
This is because those original lines are run only once when the page is loaded.
When you load new content with Ajax the only way to have the style automatically assigned to it it's to give it a class and have that class style defined in css.
If you don't do that, you have to assign the style again in the callback function of the ajax call.
Related
I want to show a comments section always. Now a user has to click, to start the javascript code to display the content (onclick). a simple change to "onload" is not working. I tried it.
//Show reviews
function reviews_show(value) {
jQuery.ajax({
type:'POST',
url:'<?php echo site_root?>/members/reviews_content.php',
data:'id=' + value,
success:function(data){
if(document.getElementById('comments_content'))
{
document.getElementById('comments_content').innerHTML = data;
}
}
});
}
html code on .tpl page:
<li>Comments</li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="comments_content"></div> </div>
If you mean with always -> on page load -> then this is the answer:
document.addEventListener("DOMContentLoaded", function(event) {
var value='{ID}'; // use value variable for your ID here
jQuery.ajax({
type:'POST',
url:'<?php echo site_root?>/members/reviews_content.php',
data:'id=' + value, // or replace to => data:'id={ID}',
success:function(data){
if(document.getElementById('comments_content'))
{
document.getElementById('comments_content').innerHTML = data;
}
}
});
});
Edit: Of course this was just an example how to make the browser to execute the jQuery.ajax on Page Loaded Completed. I edited the code and put the var value='{ID}' for your example. Make sure that there is your ID inserted (as it was inserted before in your onclick="reviews_show({ID});".
I am submitting form data via Ajax and would like to display a message above the form on successful submit.
Currently the form does send the data successfully. It should render the feedback message on form submit <?php $this->renderFeedbackMessages(); ?> as defined in my config.php
Where am I going wrong? Possibly doing things in the wrong order due to first time working with mvc?
my config.php file I have the following defined;
define("FEEDBACK_BOOK_ADD_SUCCESSFUL", "Book add successful.");
my model;
public function addIsbn($isbn)
{
// insert query here
$count = $query->rowCount();
if ($count == 1) {
$_SESSION["feedback_positive"][] = FEEDBACK_BOOK_ADD_SUCCESSFUL;
return true;
} else {
$_SESSION["feedback_negative"][] = FEEDBACK_NOTE_CREATION_FAILED;
}
// default return
return false;
}
my controller;
function addIsbn()
{
// $_POST info here
header('location: ' . URL . 'admin/searchIsbn');
}
my searchIsbn.php;
<?php $this->renderFeedbackMessages(); ?>
<div>
//my html form here
</div>
<div id="result"></div>
<script>
$('#form').submit(function() {
event.preventDefault();
var isbn = $('#isbn_search').val();
var url='https://www.googleapis.com/books/v1/volumes?q=isbn:'+isbn;
$.getJSON(url,function(data){
$.each(data.items, function(entryIndex, entry){
$('#result').html('');
var html = '<div class="result">';
html += '<h3>' + entry.volumeInfo.isbn + '</h3>';
html += '<hr><button type="button" id="add" name="add">add to library</button></div>';
$(html).hide().appendTo('#result').fadeIn(1000);
$('#add').click(function(ev) {
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>admin/addIsbn',
data: {
'isbn' : isbn
}
});
});
});
});
});
</script>
No console error messages.
You are redirecting here:
header('location: ' . URL . 'admin/addIsbn');
remove it.
echo the success message here and add it to an HTML element's .html() API.
Your page will not be refreshed.
Your page is making the call to admin/addIsbn which is redirected to admin/searchIsbn. So you already have the output of renderFeedbackMessages() being sent to your function.
Use the success callback to output the results to the page:
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>admin/addIsbn',
data: {
'isbn' : isbn
},
success: function(data) {
$('#result').html(data);
}
});
The only way I could get this to work was to add an auto-refresh to my Ajax success function as follows;
window.location.reload(true);
Working however open to suggestions.
I create a gallery with Jquery and it worked fine, later on I decided to get the file from directory and not from tag.
I used AJAX and PHP, I get the images into the gallery div but the css class not influence the the gallery to make it work.
html
<div id="gallery-holder">
<!-- <img src="images/mainGallery/main-galery1.jpg" class="active" >
<img src="images/mainGallery/main-galery2.jpg" >
<img src="images/mainGallery/main-galery3.jpg" >
-->
</div>
Jquery
$(document).ready(function(){
$.ajax({
url: 'mainGallery.php',
success: function(data){
$('#gallery-holder').html(data);
}
}).error(function(){
alert('an alert occored');
}).success(function(){
// alert('success');
}).complete(function(){
// alert('complete');
});
slideSwitch();
});
function slideSwitch() {
var $gallery = $('#gallery-holder'),
$active = $gallery.find('img:visible'),
$next = $active.next().length ? $active.next() : $gallery.find('img').first();
setTimeout(function() {
$active.fadeOut('slow');
$next.fadeIn('slow', slideSwitch);
}, 2000);
};
PHP
<?php
$i=0;
foreach(glob('./images/mainGallery/*.*' ) as $filename){
if ($i==0){
echo '<img src="'.$filename.'" class="active">';
}
else echo '<img src="'.$filename.'">';
$i++;
}
?>
It's look like the HTML is not recognize the Active class form the AJAX.
No errors in the console.
please help...
thanks,
Cfir.
Move your function call inside the success callback, otherwise it will run before the elements have been added:
$(document).ready(function(){
$.ajax({
url: 'mainGallery.php',
success: function(data){
$('#gallery-holder').html(data);
slideSwitch(); //Initialize slider after elements are loaded into the DOM
}
);
});
Inferring from this: IE ignores styles for dynamically loaded content, I'd suggest you try and return something like <img src="images/mainGallery/main-galery1.jpg" id="displayimg"> from your PHP, and then do:
$('#gallery-holder').html(data);
$('#displayimg').addClass("active");
Try it.
I'm working with this code snippet plugin : http://www.steamdev.com/snippet/ for my blog
but the plugin doesn't work on page load.
It only works at first page refresh.
I load my content in a specific div with jquery.ajax request and i'm trying this :
$(window).on("load", function(){
$("pre.cplus").snippet("cpp",{style:"acid"});
$("pre.php").snippet("php",{style:"acid"});
});
I also tried to trigger the load event but i don't know if it is correct..
Another question : i build my html with php string like this example:
$string = '<pre class="cplus">
#include <iostream>
int main()
{
//c++ code
}
</pre>
<pre class="php">
<?php
function foo()
{
// PHP code
}
?>
</pre>';
echo $string; // ajax -> success
but the PHP snippet shows empty (the c++ is ok). Any other way (or plugin) to show php code snippet on my page?
Thank you.
SOLVED:
The problem isn't the plugin or Iserni suggestions.. i had a problem in page load (ajax)..
This is how i load the pages:
function pageload(hash) {
if(hash == '' || hash == '#php')
{
getHomePage();
}
if(hash)
{
getPage();
}
}
function getHomePage() {
var hdata = 'page=' + encodeURIComponent("#php");
//alert(hdata);
$.ajax({
url: "homeloader.php",
type: "GET",
data: hdata,
cache: false,
success: function (hhtml) {
$('.loading').hide();
$('#content').html(hhtml);
$('#body').fadeIn('slow');
}
});
}
function getPage() {
var data = 'page=' + encodeURIComponent(document.location.hash);
//alert(data);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
$('.loading').hide();
$('#content').html(html);
$('#body').fadeIn('slow');
}
});
}
$(document).ready(function() {
// content
$.history.init(pageload);
$('a[href=' + window.location.hash + ']').addClass('selected');
$('a[rel=ajax]').click(function () {
var hash = this.href;
hash = hash.replace(/^.*#/, '');
$.history.load(hash);
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
$('#body').hide();
$('.loading').show();
getPage();
return false;
});
// ..... other code for menus, tooltips,etc.
I know this is experimental , i have made a mix of various tutorials but now it works..
comments are much appreciated..
Thanks to all.
The PHP snippet seems empty because the browser believes it's a sort of HTML tag.
Instead of
$string = '<pre class="php">
<?php
function foo()
{
// PHP code
}
?>
</pre>';
you need to do:
// CODE ONLY
$string = '<?php
function foo()
{
// PHP code
}
?>';
// HTMLIZE CODE
$string = '<pre class="php">'.HTMLEntities($string).'</pre>';
As for the jQuery, it is probably due to where you put the jQuery code: try putting it at the bottom of the page, like this:
....
<!-- The page ended here -->
<!-- You need jQuery included before, of course -->
<script type="text/javascript">
(function($){ // This wraps jQuery in a safe private scope
$(document).ready(function(){ // This delays until DOM is ready
// Here, the snippets must be already loaded. If they are not,
// $("pre.cplus") will return an empty wrapper and nothing will happen.
// So, here we should invoke whatever function it is that loads the snippets,
// e.g. $("#reloadbutton").click();
$("pre.cplus").snippet("cpp",{style:"acid"});
$("pre.php").snippet("php",{style:"acid"});
});
})(jQuery); // This way, the code works anywhere. But it's faster at BODY end
</script>
</body>
Update
I think you could save and simplify some code by merging the two page loading functions (it's called the DRY principle - Don't Repeat Yourself):
function getAnyPage(url, what) {
$('.loading').show(); // I think it makes more sense here
$.ajax({
url: url,
type: "GET",
data: 'page=' + encodeURIComponent(what),
cache: false,
success: function (html) {
$('.loading').hide();
$('#content').html(hhtml);
$('#body').fadeIn('slow');
}
// Here you ought to allow for the case of an error (hiding .loading, etc.)
});
}
You can then change the calls to getPage, or reimplement them as wrappers:
function getHomePage(){ return getAnyPage('homeloader.php', "#php"); }
function getPage() { return getAnyPage('loader.php', document.location.hash); }
ok for the first issue I would suggest to
see what your JS error console saying
ensure correspondent js plugin file is loaded
and use the following code when you are using ajax (the key thing is "success" event function):
$.ajax({
url: 'your_url',
success: function(data) {
$("pre.cplus").snippet("cpp",{style:"acid"});
$("pre.php").snippet("php",{style:"acid"});
}
});
for the second issue lserni answered clearly
you need to use to jquery on load function like so:
$(function(){
RunMeOnLoad();
});
i am working on one buddy press theme and want to display unread messages count via ajax.
i have bellow code in function.php of my theme
<?php
function addMessageRefresh()
{
?>
<script type="text/javascript">
function getMessages(){
jQuery('#user-messages span').text("Unread Messages: (<?php echo messages_get_unread_count(); ?>)");
}
setInterval("getMessages()", 10000);
</script>
<?php
}
add_action( 'wp_head', 'addMessageRefresh');
?>
it worked.
but its only show unread count on page load, but if user receive any message this did’t update.
the main purpose of this script is to display total number of unread messages and it should update via ajax means if user receive any message, it should show total number of unread messages without reloading page.
Thanks
somehow it..
function getMessages(){
jQuery.ajax({
url: '../url.php'
dataType: 'html',
success: function (data) {
jQuery('#user-messages span').text("Unread Messages: " + data);
}}
)
}
../url.php code
<?php echo messages_get_unread_count(); ?>
There are several steps, that you need to do:
1) Place element which contain unread message count. This should be adde to your template.
<div id="unread_messages"></div>
2) Add javascript code which will update your count value.You can add this to your template or you can print it from wp_head/wp_footer hooks
<script type="text/javascript">
function update_unread_count() {
jQuery('#unread_messages').load(
'<?php echo admin_url('admin-ajax.php'); ?>',
{ 'action': 'get_unread_message_count' }
);
}
jQuery(document).ready(function() {
// update every 15 seconds, after page loaded
setInterval('update_unread_count()', 15000);
});
</script>
3) Register ajax request handler. You should add this lines into your functions.php theme file
function my_get_unread_message_count() {
echo messages_get_unread_count();
die();
}
add_action('wp_ajax_get_unread_message_count', 'my_get_unread_message_count');
Something like that.
Your issue lies within:
jQuery('#user-messages span').text("Unread Messages: (<?php echo messages_get_unread_count(); ?>)");
What is being done is when the page is being loaded PHP processes the messages_get_unread_count() function and uses that value to render the page. From there the generated JavaScript will be called at your interval but it will have a static value defined in your preprocessed markup.
You will need to have an AJAX call to a url that will return your message count.
This is the functionality to allow you to get the updated message count.
function add_message_count_js() {
?>
<script type="text/javascript">
//<![CDATA[
var msg_count;
function updateMessages() {
jQuery.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: {"action": "view_message_count"},
success: function(data) {
jQuery('#user-messages span').text("Unread Messages: "+data);
}
});
return false;
}
setInterval('updateMessages()', 10000);
//]]>
</script>
<?php
}
add_action('wp_head', 'add_message_count_js');
This will add the appropriate AJAX hooks.
add_action('wp_ajax_view_message_count', 'view_message_count');
add_action('wp_ajax_nopriv_view_message_count', 'view_message_count');
function view_message_count() {
if (is_user_logged_in())
echo messages_get_unread_count();
die();
}
Both of these snippets should go in your functions.php file.