Execute php function only when clicked (wordpress) - php

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
});
})

Related

jQuery scrollbar plugin not working on Ajax loaded content

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.

Using javascript function and variables in combination with PHP and MYSQL

On my page I have a search result that contains a list with users where each is followed by an "addfriend" button. Each row contains a username and userID. Meanwhile the ID of the user that requested the searchresult is stored in a Session variable.
When the addfriend-botton is clicked the following 2 things should happen:
Store the userID and $_SESSION['userID'] is a MySQL table which describes the relationship.
Do NOT refresh the page (this the core of my problem) but stay focussed and change the state of the button to e.g. "friend request send". I'm thinking of GetElementByID().style method.
I was thinking of this:
<a href="#" onClick="addFriend('<? echo $_SESSION['userID'];?>','<? echo $rij['userID']; ?>')">
which calls the javascript function addfriend
I was hoping to catch the two ID's like this:
<script>
function addfriend(id1, id2)
{
//server side php code where I use value of
//the client-side javascript variables: +id1+ and +id2+ .
}
</script>
Is this at all possible or I'm I thinking the wrong way? Any suggetions on how to accomplish this?
You are in the right way, inside your addFriend() function, you can call one php file (via AJAX) and send the IDS without refresh the page. I think better you work with Jquery in this case, something like this:
<script>
function addfriend(id1, id2)
{
$.ajax({
type: 'POST',
url: 'yourPHPfile.php',
data: { your_id_1:id1, your_id_2:id2 },
success: function(data){
if(data){
alert('Done!');
}
},
dataType: 'text'
});
}
</script>
And in your PHP File you can do this:
<?php
//receive Ids
$id1 = $_POST['your_id_1'];
$id2 = $_POST['your_id_2'];
//do something here
echo "OK!";
<?
to do this work you need download and add the jQuery plugin in your page, rather into head tag
<head>
<script type="text/javascript" src="jquery.js"></script>
</head>
Good work and don't give up! (:
You can do this using AJAX (asynchronous JavaScript and XML), which is really just a fancy term for "sending stuff to a server with JavaScript and getting a response back, without reloading the page". There's nothing special about AJAX; it just involves using plain old JavaScript to send an HTTP request.
Check out jQuery, a JavaScript library that handles most of the technical stuff for you. Specifically, look at its post() function, which allows you to send data to a PHP script using the $_POST system variable. There are lots of clear examples on that page.
Note that you don't need jQuery to use AJAX; jQuery is just a library that makes things easier. If you really want to learn how the JavaScript side of AJAX works, try following one of the many tutorials out there, such as Mozilla's or this one.
AJAX is the answer you're looking for.
It sounds like you already have a basic understanding of this, but to clarify, Javascript executes on the client side, and PHP executes on the server side. So you would have to make a call back to your server in order to interact with PHP/MySQL.
The purpose of AJAX is to do this without requiring a page refresh.

PHP - Execute a specific php code when clicking a link

I'm currently working on a website and I would like to be able to do the following:
when clicking one of the links from the sideMenu the only thing I would like to change would be the content of my contentMain div and nothing else(page layout/design/etc)
Could anybody give me some general pointers on how I could achieve this in php?
Thank You in advance :D
This is a client-side change that cannot be accomplished using PHP. PHP is evaluated on the server-side, so once the page is loaded for the user, it has no control over what the user sees (unless you use client-side code to call PHP).
To accomplish this, you will need to use Javascript and/or jQuery.
Reference: https://developer.mozilla.org/en/JavaScript/
jQuery: http://jquery.org/
iFrame, frameset or AJAX all work for your case depending on what you are actually trying to achieve.
For AJAX calls (the most modern way out of the three that relies on Javascript) you can use a library such as jQuery.
http://api.jquery.com/category/ajax/
You can use ajax for this one. Using jQuery to detect the click on the link or use normal JavaScript onClick function. Then do the things like you want.
<a href="" id="my_link">My link<a>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#my_link').click(function(){
jQuery.ajax({
url: 'ajax page need to be called',
success: function(data) {
//do your operations on success
}
});
});
});
</script>
You can get more details on :
jQuery
jQuery Ajax
Hope this helps you

php ajax within ajax

I have some ajax that loads php script output into a div. I would like the user then to be able to click on links in the output and rewrite the div without reloading the whole page. Is this possible in principle? Imagine code would look like:
html
<div id="displayhere"></div>
php1 output
echo 'ChangeToNew';
JS
function reLoad(par1,par2,par3) {
...
document.getElementById("displayhere").innerHTML=xmlhttp.responseText;
xmlhttp.open("GET","php2.php?par1="+par1 etc.,true);
xmlhttp.send();
php2
$par1 = $_get['par1'];
change database
echo ''.$par1.'';
Could this in principle work or is the approach flawed?
Thanks.
What you describe is standard, everyday AJAX. The PHP is irrelevant to the equation; the JS will simply receive whatever the server sends it. It just happens that, in your case, the server response is being handled by PHP. The JS and PHP do not - cannot - have a direct relationship, however.
So the principle is fine. What you actually do with it, though, will of course impact on how well it works.
Things to consider:
what will the PHP be doing? This may affect the load times
what about caching responses, if this is applicable, so the PHP doesn't have to compute something it's previously generated?
the UI - will the user be made aware that content is being fetched?
Etc.
I'm used to using jQuery so will give examples using it.
If you create your links as
Click Me
You could then write your code as
<script>
$("#do_this").live('click', function(){
var link_url = $(this).attr('href');
$.ajax({
url: link_url,
success: function(data) {
$('#displayhere').html(data);
}
return false;
};
</script>
If you use jQuery, make sure you use the .live('click', function(){}) method versus the .click(function(){}) method, otherwise it won't recognize dynamically created elements. Also make sure you do a return false.

Jquery(ajax) PHP search results not displaying in search_results div under form

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.

Categories