how to call wordpress function on click in a custom plugin - php

I've been having a go at creating a custom plugin (simplified code below).
I have my plugin file (counter.php) which has 2 function in it called
displayCount() {
// output count and a link to add 1
echo 'Add One';
}
AND
addOne() {
$count = $count + 1;
}
My question is what to I replace XXX with or how do I call addOne function from my post page?

You're attempting to modify the PHP on the user's end, but unfortunately all PHP has already run when the user is able to click the link. PHP is a server side language, Javascript is a client-side language. In order to pass data back and forth, you'll need Ajax.
However, it looks like what you're trying to do could be done with pure Javascript. Something like this:
<div id="counter"></div>
Add one
<!-- INCLUDE JQUERY HERE (or elsewhere on page, perhaps head) -->
<script type="text/javascript">
// Create global JS var to track the count.
var counter = 0;
// On document ready we need to assign a click event.
// We use document ready to be sure that we select all
// initial elements when the page is loaded.
jQuery('document').ready(function()
{
// On counter-add click...
jQuery('.counter-add').click(function()
{
// Increment counter
counter++;
// Output counter value
jQuery('#counter').text(counter);
});
});
</script>
Here is a working JSBIN copy.

Related

jQuery Accordions Using Dynamic Post ID Classes

I have jQuery drop down accordions on each post in my loop, and I want to trigger them individually on click. They work by checking div classes, so I've made sure that each class is dynamically named based on the post-ID. I've also created a variable to generate the name of class used in the script...
This is my code:
<script type="text/javascript">
var post_ID = ".show-dts.<?php the_ID();?>";
$(post_ID).click(function() {
if($('.show-more-dts').css('height') != '1px'){
$('.show-more-dts').stop().animate({height: '1px'}, 200);
$(this).text('Show details');
}else{
$('.show-more-dts').css({height:'100%'});
var xx = $('.show-more-dts').height();
$('.show-more-dts').css({height:'1px'});
$('.show-more-dts').stop().animate({height: xx}, 400);
// ^^ The above is beacuse you can't animate css to 100% (or any percentage). So I change it to 100%, get the value, change it back, then animate it to the value. If you don't want animation, you can ditch all of it and just leave: $('.show-more-snippet').css({height:'100%'});^^ //
$(this).text('Hide Details');
}return false;
}); </script>
Checking the page source, I can see that the jQuery code is creating the correct class names using the variable, but I'm not quite there, because when any of the accordions are clicked, all them are triggered together still.

Can JS be used to display a new dropdown already filled by php mysql?

I know that PHP is server-side and JS is client side, I've done some research but haven't exactly found what I was looking for.
So what I'd like to know is if it is possible to use Javascript to display PHP code?
Scenario:
I have a drop down list already on the page being updated from a database
(quick example)
php while($row...) {
<option><?php echo $row["number"]; ?></option>
}
and I am using Javacript to display a new drop down list when a button is clicked
<script language="javascript">
var i = 1;
function changeIt()
{
my_div.innerHTML = my_div.innerHTML +"<br><select><option name='mytext'+ i></option></select>"
i++;
}
</script>
This works but what I'd like to be able to do is have this new drop down list appear pre filled.
Is this possible to have these 2 items work together?? If so how? Or would this require a page reload each time since php loads before it reaches the user (and how again..)?
Any help or guidance would be greatly appreciated.
This example uses jQuery to make an ajax call to your-script.php, which in turn returns the html for a select list:
$(document).ready(function() {
// event handler for click on the button control
$('#your-button').click(function() {
// make ajax request
$.ajax({
url:"your-script.php",
success:function(e) {
// insert html for the select control
$('#control-panel').html(e);
}
});
});
});
<div id="control-panel">replace this with select control</div>
<input type="button" id="your-button" />
Here is the contents of the your-script.php file:
<?php
print '<select><option value="1">1</option></select>';
?>
You can load data from the server using ajax. A good and very common way to do so it to use jQuery to do it.
Check out this example: jQuery Ajax Tutorial

load more jquery function that i want

i am using MVC and my design for my website is that there is header and body and footer,
every page in my website will have the same header and the same footer, but with different body
and for ever page there is a JS file contains the jquery calls
and for many many pages when it is opening, jquery call works and get data from database using ajax and put that data in that page
my question is : sense the jquery calls begins with $(document).ready, so when i open any page, all the jquery call starts, i don't want that, but i want just the jquery for that page which is opening to be loaded
example
this jquery just for a page
$(document).ready(function(){
$.getJSON("http://localhost/Mar7ba/Cell/getAllCountries/TRUE",function(data){
var select = $("#countrySelector");
var options = '';
for(var i=0;i<data.length;i++){
options += "<option>"+data[i]+"</option>";
}
select.html("<option>Select Source</option>"+options);
});
});
and this jquery for another page , but it is loaded when i load the first page
$(document).ready(function(){
$.getJSON("http://localhost/Mar7ba/Type/getAllTypes/TRUE",function(data){
var options = '';
options+="<option>Select Type</option>";
for(var i=0;i<data.length;i++){
options += "<option>"+data[i]+"</option>";
}
$("#addPlace #apTypeSelect").html(options);
});
});
Test for the existence of the elements you're operating on, before you fire off the AJAX method. For instance, in your first example:
$(document).ready(function(){
var select = $("#countrySelector");
if (select.length) { // must test .length; 'select' always exists even if it's empty
$.getJSON("http://localhost/Mar7ba/Cell/getAllCountries/TRUE",function(data){
var options = '';
for(var i=0;i<data.length;i++){
options += "<option>"+data[i]+"</option>";
}
select.html("<option>Select Source</option>"+options);
});
}; // end if
});
If you don't want a script to run on a page then either:
Don't put it on the page in the first place or
Wrap it in a conditional that checks if running it would be appropriate for the current page
I think if you will put all the startup functions of all pages in document.ready then function will become too lengthy and readability will be effected. You should write different start-up function for each page and call them from page on loading , in this your code will remain simpler e.g.
In js file
function InitialFunctionOfPage1()
{//define all prerequisites}
function InitialFunctionOfPage2()
{//define all prerequisites}
and in each page you can relevant function on document.ready , ample for page 1
$(document).ready(function()
{
InitialFunctionOfPage1();
}

Load div from another page within an AJAX loaded page

I'm using jQuery address to enable loading specific content from other pages
and to change the URL in the address bar.
I'm working on a little Social Network alike website, so I'm reading out the IDs
of the posts table of my MySQL database via PHP. I want to use the possibilities of jQuery and AJAX to read everything out dynamically.
I found out, that I have to use live() (which turned out to be old), delegate() (which
also turned out to be old in 1.7.1) or on() (which turns out to be the best possibility
to make events work inside of dynamically loaded content via jQuery + AJAX).
I also read somewhere, that I can't use load() or get() to load new content from another
page inside of an already loaded content, because it doesn't "bubble" (I don't even know
what that means).
What do I have to do to load new content within an AJAX loaded page?
Here's a snippet I tried to work with (included on the loaded page):
<?php
if(exist('`posts`')) {
$load = mysql_query('SELECT `id` FROM `posts` ORDER BY `id` DESC LIMIT 10');
while($row = mysql_fetch_object($load)) {
?>
<script type="text/javascript">
$('body').on('body', 'load', function() {
$.get('getpost.php', { pid: <?= $row->id ?> }, function (data) {
$('#posts').html($('#post_<?= $row->id ?>', data).html()).show();
});
$('#posts').off('load');
});
</script>
<?php
}
}
else {
?>
<div align="center">No posts yet.</div>
<?php
}
?>
getpost.php is my file from which I can get the div_$row->id so that it appears on the start page.
PLUS (Just adding for your knowledge) I want the content to load the content without
a mouseover, click or blur event.
Thanks.
You want to use ".live()" if you want a particular event mapping to be applied dynamically to any new DOM elements which match its selector. Alternatively, you can attach the behavior to each chunk of content loaded.
Write and develop your ajax load independently of your DB lookup to make things simpler. The following snippet triggers another ajax call after each element loads.
<?php
$id = 'div'.mt_rand();
$counter = isset($_REQUEST['counter']) ? $_REQUEST['counter'] : 0;
$next = $counter + 1;
echo <<<END
<div id="{$id}">{$counter}
<script>
$(function() {
$.ajax('/url?counter={$next}', function(html) {
$(html).appendTo($('#{$id}').parent()); // or whatever your favorite method is for adding a sibling
});
});
</script>
</div>
END;
?>
Am I the only one who thinks that this approach is completely wrong? You're making an ajax request for each post, this could end up in making way too much requests, heavily slowing down the loading time. I can't see any reason why you don't want to directly write the posts' HTML inside the PHP while loop.

Include Jquery script in .js page

Sorry if title is not too clear but I think it's about right. NEhow, what I would like to do is a bit like (well is to a certain extent) building a widget with JQuery (pref), PHP & CSS.
What I would really like to happen is for a "member" of my site to simply paste 2 lines of code in their HTML to load the widget. Something like this:
<script type="text/javascript" src="http://www.mydomain.com/script.js"></script>
Then to display the widget something like this <div id="displaywidget"></div>
OK that bit is "easy" and ok. But how do I include JQuery or "something" to generate the widget in script.js
What I mean is "displaywidget" - the ID of the widget div will be the name of a php file on my server so essentially script.js will need to load displaywidget.php into the div displaywidget.
I think I use document.getElementById('displaywidget') to get the div but how do I then "write/insert/load" displaywidget.php inside the div?
Thinking as I write "pure" java can do "most of what I want i.e. document.getElementById('displaywidget'), BUT I would prefer to also "include" Jquery.js as I would like some aspects of the widget to use JQuery. Example being the JQuery UI date function.
Sorry if I am rambling a bit but trying to think as I go along. My "real" problem is I am not too sure on "pure" javascript i.e. getting the div to display/load displaywidget.php
Suggestions please. (Oh if I am barking up the wrong tree please feel free to tell me - nicely:) )
Thanks in advance
I think I use document.getElementById('displaywidget') to get the div but how do I then "write/insert/load" displaywidget.php inside the div?
You're looking for the AJAX behaviors inside of jQuery which would make the call to the php page and then push the data into the div.
You should be loading jQuery early on in the process, right up front in your head element. Once its loaded it will be cached so no worries of its on every page. No real overhead incurred.
Once jQuery is installed you can call one of many AJAX functions related to obtaining data and popluation elements. Theres $.load(), $.ajax(), and a few others that escape me unless I go and check out their docs section.
You can do all of this without jQuery, but its more code and you have to control for browser differences.
You can load jquery into script.js, just copy and paste it after or before whatever javascript lives in script.js.
So if script.js is:
//start of file
alert('ex');
//end of file
Make it:
//start of file
alert('ex')
Copy and pasted Jquery source
//end of file
After a bit more "trawling & thought" I found this code:
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src","http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
script_tag.onload = scriptLoadHandler;
script_tag.onreadystatechange = function () { // Same thing but for IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
/******** Our main function ********/
function main() {
jQuery(document).ready(function($) {
******* Load CSS *******/
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "style.css"
});
css_link.appendTo('head');
/******* Load HTML *******/
var jsonp_url = "http://al.smeuh.org/cgi-bin/webwidget_tutorial.py?callback=?";
$.getJSON(jsonp_url, function(data) {
$('#example-widget-container').html("This data comes from another server: " + data.html);
});
});
}
})(); // We call our anonymous function immediately
writtend by Alex Marandon and found here http://alexmarandon.com/articles/web_widget_jquery/ - works a treat, exactly what I wanted, including/installing JQuery into a .js file

Categories