The problem is this:
I have a simple, two fields form which I submit with Ajax.
Upon completion I reload two div's to reflect the changes.
Everything is working perfect except a jQuery plugin. It's a simple plugin that can be called with simple
function(){
$('.myDiv').scrollbars();
}
It's simple and easy to use, but it doesn't work on Ajax loaded content. Here is the code I use to post form and reload div's:
$(function() {
$('#fotocoment').on('submit', function(e) {
$.post('submitfotocoment.php', $(this).serialize(), function (data) {
$(".coment").load("fotocomajax.php");
}).error(function() {
});
e.preventDefault();
});
});
I've tried creating a function and calling it in Ajax succes:, but no luck. Can anyone show me how to make it work ? How can that simple plugin can be reloaded or reinitialized or, maybe, refreshed. I've studied a lot of jQuery's functions, including ajaxStop, ajaxComplete ... nothing seems to be working or I'm doing something wrong here.
If you're loading elements dynamically after DOM Document is already loaded (like through AJAX in your case) simple binding .scrollbars() to element won't work, even in $(document).ready() - you need to use "live" event(s) - that way jQuery will "catch" dynamically added content:
$(selector).live(events, data, handler); // jQuery 1.3+
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+
$(document).on(events, selector, data, handler); // jQuery 1.7+
Source: jQuery Site
Even if I am totally against using such plugins, which tries to replicate your browser's components, I'll try to give some hints.
I suppose you are using this scrollbars plugin. In this case you may want to reinitialize the scrollbars element, and there are many ways to do this. You could create the element again like in the following example
<div class="holder">
<div class="scrollme">
<img src="http://placekitten.com/g/400/300" />
</div>
</div>
.....
$('.scrollme').scrollbars();
...
fakedata = "<div class='scrollme'>Fake response from your server<br /><img src='http://placekitten.com/g/500/300' /></div>";
$.post('/echo/html/', function(response){
$('.holder').html(fakedata);
$('.scrollme').scrollbars();
});
If you want to update the contents of an already initialized widget instead, then things gets more complicated. Once your plugin initialize, it moves the content in some custom wrappers in order to do its 'magic', so make sure you update the correct element, then trigger the resize event on window, pray and hopefully your widget gets re-evaluated.
If it doesn't help, then try to come up with some more details about your HTML structure.
I want to thank everyone of you who took their time to answer me with this problem I have. However, the answer came to me after 4 days of struggle and "inventions" :), and it's not a JS or Jquery solution, but a simple logic in the file.
Originally, I call my functions and plugins at the beginning of the document in "head" tag, like any other programmer out here (there are exceptions also ).
Then my visitors open my blog read it and they want to post comments. But there are a lot of comments, and I don't want to scroll the entire page, or use the default scroll bars, simply because they're ugly and we don't have cross browser support to style that, just yet.
So I .post() the form with the comment, and simply reload the containing all of them. Naturally .scrollbars() plugin doesn't work. Here come the solution.
If I put this :
<script>$('.showcoment').scrollbars();</script>
in the beginning of my loaded document (with load() ), will not work, because is not HTML and it's getting removed automatically. BUT !!! If i do this:
<div><script>$('.showcoment').scrollbars();</script></div>
at the same beginning of loaded document, MAGIC .... it works. The logic that got me there I found it in the basics of javascript. If your script is inside an HTML element, it will be parsed without any problem.
Thank you all again, and I hope my experience will help others.
If I understand you correctly, try this:
var scrollelement = $('.myDiv').scrollbars();
var api = scrollelement.data('jsp');
$(function () {
$('#fotocoment').on('submit', function (e) {
$.post('submitfotocoment.php', $(this).serialize(), function (data) {
$(".coment").load("fotocomajax.php");
api.reinitialise();
}).error(function () {
});
e.preventDefault();
});
});
reinitialise - standart api function, updates scrolbars.
Related
For one of my wordpress site php files, I have the following code:
<div class="tabs">
Items
</div>
<div class="section" id="tab1">
<?php get_template_part('page/tab1'); ?>
</div>
So, it will call the tab1.php file into the div id="tab1"section.
However, I want to make it so that the get_template_part is only executed or called when the Items tab is clicked.
What would be the jQuery to call or execute the get_template_part function?
EDIT:
So, what I am trying to achieve is similar to Ajax. Since the get_template_part function won't be called till the "Items"tab is clicked, the browser does not have to call unnecessary files and slow down the page.
Let me know if you think this is the best way to do it.
Thanks!
Though the idea behind is already illustrated by Raphael in his answer, I intervene to add some details.
the best way to use AJAX with Wordpress is to use its built-in way of handling it, and that by sending requests to wp-admin/admin-ajax.php( I know the “admin” part of the file name is a bit misleading. but all requests in the front-end (the viewing side) as well as the admin can be processed in admin-ajax.php, with a lot of benefits, especially for security. And for the server-side code php that will be executed, it should be placed in functions.php.
Your jQuery code will look something like:
$(document).ready(function() {
$('.tabs a').click(function(e) {
e.preventDefault();
var tab_id = $(this).attr('id');
$.ajax({
type: "GET",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'yourFunction', id: tab_id}),
success: function(data){
$('#tab'+tab_id).html(data);
},
error: function(data)
{
alert("Error!");
return false;
}
});
});
});
infunctions.php of your theme (or directly in your plugin file), add:
add_action('wp_ajax_yourFunction', 'yourFunction');
add_action('wp_ajax_nopriv_yourFunction', 'yourFunction');
and define in the same file yourFunction callback function like this:
function yourFunction() {
// get id
// your php code
die();
}
For the javascript part, take a look at ajax() and its shorthand get(). And for the best practices using AJAX with Wordpress, there are many tutorials on the web (I will be back to give one). Good luck
Edit:
As it is mentionned by Karl, you can use .load() instead of ajax(), It should be noted that .load() is just a wrapper for $.ajax(). It adds functionality which allows you to define where in the document the returned data is to be inserted. Therefore really only usable when the call only will result in HTML. It is called slightly differently than the other as it is a method tied to a particular jQuery-wrapped DOM element. Therefore, one would do: $('#divWantingContent').load(...) which internally calls .ajax().
But my original answer is on how to organize php code respecting Wordpress best practices.
You can't really call a PHP function from javascript because by the time the browser sees the page, the PHP has already executed (or in your case, not executed )
The only way for you to do what you want is to spin the PHP function off into a separate script and then call that file using AJAX. Have the script echo HTML, and then insert the HTML into the tab1 div in the AJAX callback.
I think the easiest solution for you would be to use the jQuery load() function. It is the easiest way to achieve what you describe. The only issue that when someone clicks the header, there will be a delay to get the subitems as they do not exist yet (which would be the case for any situation where you delay the load.
HTML:
<div class="tabs">
Items
</div>
<div class="section" id="tab1"></div>
JS:
$(function () {
//wait for the page to finish loading
$('#items_id').click (function (e){
//watch for the items header to be clicked
e.preventDefault();
//prevent it from opening a link
$('#tab1').load('tab1.php');
//load the tab1.php file, or whatever file INTO the div
});
})
I know this has been asked on SO a lot, but I have trawled through the posts for a few hours now and nothing works.
I'm working on a Wordpress blog where the prev/next buttons on a single post page have to load the prev/next post by Ajax. I have written the code (jQuery Ajax) all fine (I think - if you want to improve it, be my guest!), but in each post there a few bits of jQuery that need to work. However, after I click either of the prev/next buttons to move between posts, the jQuery won't work (it works absolutely perfectly when the page is first loaded). I know this is due to the content not being 'connected' to the JS anymore but I'm not sure what to do about it.
Here is my code:
$(".page-feed").on('click', '.post-nav>a', function() {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
var link = $(this).attr('href'); // get the value of the href attribute on the links
$(".post-content").html("Loading...");
$.get(link, function(result) {
$result = $(result);
$content = $result.find(".post-content");
$(".post-content").replaceWith($content);
}, 'html');
});
I know that you're probably going to ask what I've already tried, but if I'm honest, not a lot that would be worth putting here.
The code above is located right at the top of a file called script.js, with all the other JS below it (which doesn't currently work after the Ajax call). The script is started by the standard $(document).ready(function() { statement.
Thanks for any help :)
First, you need to accept the event object as an argument.
$(".page-feed").on('click', '.post-nav>a', function(event) {
Next, by using the jQuery event object, you can simplify the next line because event is normalized by jQuery to work cross-browser.
event.preventDefault();
Now, as far as it working on the first click but not after, that's likely because .page-feed is a dynamic element. You'll need to instead select an element that is an ancestor of .post-content. document is a decent replacement, but it would be better if you picked one more local.
$(document).on('click', '.post-nav>a', function(event) {
(Not sure if I missed an already similar answered question…)
On click of a button, I'm loading various images from a database via PHP/MySQL and appending it to the body (the actual images are of course not stored in the database, the correct selection of the images is based on a posted variable).
My goal is to display a loading indicator after pressing the button and hiding the indicator after all the image data has completely loaded and displayed. This may be an easy to solve callback issue but I'm just getting started with AJAX. :)
The following is the code I currently managed to come up with. I'm guessing the load() function is not really the right one here?
Thanks for your help!
$("#somebutton").click(function(){
alert("fetching…");
$.post('loadmore.php', {
somevariable: somevariable
},
function(data){
$("body").append(data);
$(window).load(function(){
alert("finished loading…");
});
});
});
The function you have with the finished loading... alert is a success callback, so it gets executed once the AJAX call has finished. This means you don't need to use $(window).load.
Also, you can use the html method on an element to change its contents and display a message.
Something like this would work fine:
$("#somebutton").click(function(){
$('#divID').html('Loading...');
$.post('loadmore.php', {
somevariable: somevariable
},
function(data){
$("body").append(data);
$('#divID').html('');
});
});
Read the docs http://api.jquery.com/jQuery.ajax/
Use the success callback to append the body and then the complete and error callbacks to clear things up correctly.
$("#somebutton").click(function(){
alert("fetching…");
$.post('loadmore.php', {
somevariable: somevariable
})
.success(function(data){$("body").append(data)})
.error(function(){alert("oh dear")})
.complete(function(){alert("finished loading…")});
});
Remember to always have a fallback for removing the loader - nothing worse than just having a loader and no way to remove it from the page and continue using the application / web site.
I managed to solve my problem by reading and tweaking the code in the following article.
The function load() with the equation containing the self-explanatory variables [imagesLoaded >= imageCount] did the trick.
Know when images are done loading in AJAX response
I'm facing an interesting problem where everything works flawlessly. I console.log every step and it plays out just the way it should. But! I have a #div into what I .load(a-file.php). Now that "a-file.php" includes HTML mark-up as well, more specifically certain links that I'd like to make "active" onload.
Scenario; page load happens, Javascript loads and loads a file into the div. That div now has tabs and I'd like the first tab to be in an "active" state which requires me to addClass('active');. But the following seems to have no effect
$('#content').load('file.php'); // works.
$('#content a[rel="weird-page"]').addClass('active'); // does not work.
Any kind of help, even remotely nailing it, is appreciated.
change to:
$('#content').load('file.php', function() {
$('#content a[rel="weird-page"]').addClass('active');
});
jQuery load() works asynchronously and therefore your addClass() method is being called before load() has completed.
Using the load() callback function it will ensure your content has loaded:
$('#content').load('file.php', function() {
$(this).find('a[rel="weird-page"]').addClass('active');
});
shameless-plug-warning: I wrote a blog post about jQuery callback functions which you might find useful.
For a website I'm making for school, I'm trying my hand at using Jquery extensively for the first time, and even though I managed quite a bit so far, I'm stuck at two (most likely related) problems.
I'm aware that the upcoming case is somewhat long, but I feel it's necessary to submit all relevant code for everyone reading this to get a good image of what is happening.
Basically, the website is one index.html file, with the CSS thrown in, a few buttons, and one div with the ID content. I use this code to make this work:
<script type="text/javascript">
if ($('#content').innerHTML == " "){
$(document).ready(function(){
$('#content').load('main_text.html');
});
}
</script>
<script type="text/javascript">
function loadContent(elementSelector, sourceURL) {
$(""+elementSelector+"").load(""+sourceURL+"");
}
</script>
Then there is one content page, named search.html, which only contains a form that submits a search string to a search.php page (through ajax) that should then place the search results immediately back into a div called search_results in that same search.html file. The jquery that I use for this:
<script type='text/javascript'>
$(document).ready(function(){
$("#search_results").slideUp();
$("#search_button").click(function(e){
e.preventDefault();
ajax_search();
});
$("#search_term").keyup(function(e){
e.preventDefault();
ajax_search();
});
});
function ajax_search(){
$("#search_results").show();
var search_val=$("#search_term").val();
$.post("Functions/search.php", {search_term : search_val}, function(data){
if (data.length>0){
$("#search_results").html(data);
}
})
}
</script>
The issue that I'm having is as followed:
Before I had the first line of code: if ($('#content').innerHTML == " "){; implemented, I would open the site, main_text.html would nicely be loaded in, I could navigate to other subpages fine. But typing in something in the form field in search.html did not display any results (just typing should already trigger the function). When I hit the search button on this form, instead of seeing query results, the main_text.html file load again in the #content div. This made me assume that perhaps, somehow, that the code:
$(document).ready(function(){
$('#content').load('main_text.html');
});
was being called again unwanted. Hency why I implemented that check for whether innerHTML existed.
However, now, when I first load the page, the #content div does not load any initial content at all. (The section on the webpage just becomes black, like my page background) I have to click any button to get some content loaded again in my main content div. Also, when I now go back to the search.html, the typing anything to get results, like previously, still does not work. If I now hit the search button, I get the initial result again of what I'd see when I just opened the page: a blacked out #content div.
So somehow, the biggest issue is in the fact that the jquery to get results from my PHP do not seem to work. My problem with the content.innerhtml check might well be obsolete if the issue with the searchresults not displaying in the #search_result div on the search.html is fixed.
Anyone have any idea's what I could do to fix this. Or otherwise, what other approaches I could take for the kind of website I'm making. Since I'm trying to learn jquery here, better approaches are always appreciated, I'd rather learn myself doing this the right way and all. :)
Thanks for your time.
Few things to note here:
<script type="text/javascript">
if ($('#content').innerHTML == " "){
$(document).ready(function(){
$('#content').load('main_text.html');
});
}
</script>
<script type="text/javascript">
function loadContent(elementSelector, sourceURL) {
$(""+elementSelector+"").load(""+sourceURL+"");
}
</script>
In the above, you are testing to see if there is a space in the innerHTML of the element with an id of content.
jQuery uses .html() or .text() to make comparisons against the data being held within a container, so if you want to maintain using jQuery principles, change this line. Going along the same thought process, you are preparing an IF statement on an element before the document is actually ready and loaded.
You should move the document.ready function to the outside of the if statement. This will allow you to ensure that the element is available at DOM, and you can indeed perform checks against this element.
<script type="text/javascript">
$(document).ready(function(){
if ($('#content').html("")){
$('#content').load('main_text.html');
}
});
</script>
Also, while being readily provided and fully functional, I would recommend starting off using $.ajax instead of $.get / $.post. I have personal preferences as to why I think this, but I won't go into that, it's just that, personal.
$.ajax({
url: "Functions/search.php",
type: 'POST',
data: "search_term="+search_val,
success: function(data){
if (data.length>0){
$("#search_results").html(data);
}
});
Lastly, you should be using the GET method and NOT the POST method. Based on REST/SOAP practices, you are retrieving data from the server, and not posting data to the server. It's best practice to follow those two simple ideas. This isn't because web servers will have a difficult time interpreting the data; but, instead, it's to prepare you for working on larger scale application deployment, or future team-environments. This way everyone on the team has an expectation as to what method will be used for what purpose.
Anyway, long story short, you also leave semicolons off of the end of your closing }) brackets. While this is not an issue, nor will it cause flaws in your development, coding is all about uniformity. You've used the closing ; everywhere else, so try and maintain that same uniform design.
Best of luck.