Wordpress categories list with jquery load() - php

A "select" element is created by a wordpress plugin (PHP) and I want to add elements in it with .load() function of jQuery.
jQuery:
$("#ugc-input-post_category").load("../wp-content/themes/anim-theme/post-category.php");
post-category.php:
<?php
echo '<h1>TEST</h1>';
$categories = get_categories();
foreach ( $categories as $category ) :
echo '<option value="' . $category->term_id . '">' . $category->name . '</option>';
endforeach;
?>
The echo function that returns "TEST" works and the "h1" element appears in the "select" element, but not the different categories that should be generated by the loop. However, when I add the PHP code in the PHP code of a page, it works and the category list is generated. So I think it's an issue with the load() function.
Thanks a lot !

When the code is included to the normal page, WordPress use data derived from the page that was loaded through WordPress Main Loop, so they can know which data to take, based on the page you are displaying.
But when you took load from the separate file, they didn't have data prepared for them, so it's unable to display the data correctly.
So the next question is you want to use Ajax method to load the page or not?
If not, use PHP 'include' instead so it can generate date since server's load.
If using Ajax, write an Ajax function that return 'json' and use jQuery to display them.
Good luck

Related

If Custom field is something, then add a class to a div

I have a custom field in Wordpress of wilcity_belongs_to with a value of 21956. I am trying to get my php code to work, so that if the custom field's value is 21956 then it will run the Jquery code and add the class .hidden to a specific Div.
I do not get any errors running this code, although i do not see it echoing the Jquery either. What am i missing? Thanks
Updated Script so far:
global $post;
$meta_print_value = get_post_meta($post->ID,'wilcity_belongs_to',true);
if( $meta_print_value == '21956' ) {
echo "
<script type=\"text/javascript\">
$(document).ready(function() {
$('.wil-single-navimage1646724156466').addClass('hidden');
}
</script>
";
} else {
}
This is the custom field i am trying to refer to:
Custom Field
this probably happens because the moment the script is appended to the DOM the element with class .wil-single-navimage1646724156466 is not even present either because you still need to echo it or because the element in the document isn't ready yet
you need to wait until the element is present in the DOM then execute the jQuery code, this is usually done with $((function(){...}) that basically waits for the whole document to be ready before the content of the function is executed

How to get data from a php array and add it inside the page title attribute using jquery?

I want to use jquery so i can add dynamically the "store_name" data of the code bellow inside the page title attribute for seo purposes.
<?php
$store_info=array(
'store_id'=>$store_id ,
'phone'=>$data['phone'],
'store_name'=>$data['store_name'],
);
?>
I already tried to use this code:
<script src="http://code.jquery.com/jquery-1.11.0.min.js">
$(function(){
$(document).attr('title', $data['store_name']);
});
</script>
but didn't work at all. What in the world i'm doing wrong ?
People mentioned that already there is a similar question here but this isn't what i 'm looking for. In my question i want to pass in the title attribute, data from a php array as i described above.
It took me a moment to figure this out, and then it hit me:
Remove the src="http://code.jquery.com/jquery-1.11.0.min.js" inside your script tag, since that's ignoring everything inside the tag itself. You'll then need two script tags:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<?php
$store_info['store_name'] = 'new_title';
echo '<script type="text/javascript">'.
'$(function(){$(document).attr("title", "' .
$store_info['store_name'] .
'" );});</script>'
?>
From the w3.org docs:
If the src has a URI value, user agents must ignore the element's contents and retrieve the script via the URI.

Two problems regarding AJAX

I created a page which gets filled by a php databasequery (all rows are being read from the MySQL-table and written to the table in HTML). All 10 seconds the same PHP-script gets requested by jQuery AJAX and should refresh the current table content. The return-value of this function will then be used to change the table HTML-value.
There are some buttons in the table. When they're clicked, they toggle from on to off (or vice versa) and another PHP-file gets called with AJAX, which then controls 433MHz wireless sockets via shell commands. Purpose of these 10-seconds ajax-refresh is to synchronize the button with the actual state of the electrical socket (which is saved in the MySQL-database).
$(document).ready(function(){
$(".toggle").click(function() {
if($(this).hasClass("ein")) {
$(this).removeClass("ein");
$(this).html("aus");
$.post("various/executeCode.php", {transmitted:true, id:$(this).attr('id'), toggle:'0'}, function(result) {
});
} else {
$(this).addClass("ein");
$(this).html("ein");
$.post("various/executeCode.php", {transmitted:true, id:$(this).attr('id'), toggle:'1'}, function(result) {
});
}
});
});
window.setInterval("reloadPage()", 5000);
function reloadPage()
{
$.get('various/reloadPage.php', function(data) {
$("#content").html(data);
});
}
$stmt = $dbh->query("SELECT * FROM `funksteckdosen`");
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($row as $r)
{
echo "<tr>";
echo " <td>" . $r['name'] . "</td>";
echo " <td><button id='" . $r['id'] . "' class='toggle" . ($r['toggle'] == 0 ? "" : " ein") . "'>"
. ($r['toggle'] == 0 ? "aus" : " ein") . "</button></td>";
echo "</tr>";
}
Now I have the following problem: As soon as the page gets refreshed by AJAX the first time, the buttons stop working. Javascript doesn't execute the click()-function anymore. Why is that?
Problem 2:
The content of the table gets deleted and replaced by the new one. Am I somehow possible to fade new lines (or the button background-color) in, instead of just showing them? That would be the final touch.
I hope you understood my explanations.
The click handlers don't work anymore because the new buttons never had the handlers attached to them. When you attach a handler like this:
$(".toggle").click(function() {
What jQuery does is find all of the currently existing .toggle elements and, for each one, add that function as a handler. Since the new ones are added later via an AJAX call, they're not included in that set and, thus, never have that function attached to them.
The way jQuery address this is with the .on() function. The structure of using is it very similar:
$('body').on('.toggle', 'click', function() {
The difference here is the element which is actually getting the click event bound to the function. With this, the click event is actually being added to the body tag, which isn't changing from the AJAX call. Any unchanging common parent for the dynamic elements will work, 'body' and document are usually used as defaults since they're pretty top-level.
When any child element raises a click event, that event continues up all of the parent elements. So it eventually reaches a common parent, such as 'body'. The .on() function then also has a second selector as its first argument. That selector filters the originating elements of the click event before calling the function.
Benefits of using this approach include:
There's only one event handler function attached to a single common parent, instead of many attached to many elements, which can be a performance improvement on large or complex pages.
Child elements added to the common parent element later in the page's lifespan are still handled, since they will still send their click events to the parent regardless of when they were added. (This is the immediate benefit in your situation.)
As for fading in the content, if I understand the effect you're looking to achieve, you can try something like fading out what's already there, removing it, adding the new content, and then fading it in. Maybe something like this:
$.get('various/reloadPage.php', function(data) {
$('#content').fadeOut(400, function() {
$("#content").html(data);
$('#content').fadeIn();
});
});
There might be newer structures to accomplish this same thing with the relatively newer "promises" model, but essentially what this does is fade the content out and then include a call-back function to call when it's finished fading out. That call-back function replaces the HTML and then fades it back in. Depending on the structure of your HTML you might need to fade out/in a parent element instead of the one I'm targeting, but hopefully you get the idea here and can tweak it until it looks right.
Problem 1: The click event handler is bound to the initial toggle class elements but dynamically created events are not bound.
Try using live() or on() to bind dynamically created elements. See: Event binding on dynamically created elements?
Problem 2: #content is replaced when using html()
Try using append() to add data into an existing element. Using html() will replace the contents of the element.
I have chained a hide() and a fadeIn() to animate the append.
$('#content').append(data).hide().fadeIn(1000);

jQuery context menu filled with php content based on selection

When a user selects a word in a text on my website (PHP), and then right clicks, i want a jQuery context menu to come up, this can be done by using one of the already existing jQuery context menu plugins.
But besides the options like copy / paste / cut, etc. I also want something to be done with the selected word using PHP. Which, i think, is a little harder.
For example using this script:
$selection = //the selected word or text
$target = //fetch from MYSQL database
$output = array();
while ($row = //fetch $target) {
If ($selection == $row->input) { array_push($output,$row->output); }
}
echo '//menu '.print_r($output).''; // of course not print_r! Just for the example's sake.
Databse example:
(Sorry for the oversized image)
Ok so selecting the word 'lazy' in the example text, and then right clicking, the jQuery box should pop up showing the results from the database extracted by PHP.
Example:
Ok, so i know you can't just combine javascript with PHP and it can only be parsed, but i thought loading an iframe withing the menu, which does the database extraction would do the job by using javascript to set the iframe src containing the selected word in the url.
However, iFrames are not really a nice way to solve this.
The question: How can i do this effectively? Execute this script on right-click and show the database-related content in the menu?
I would need to know the plugin you're using to give you some code examples but, general, I would go about this like this:
There has to be a click handler on the items in the jQuery context menu. Use it to submit an AJAX request to the server when the "selection" term is clicked.
Make sure to give the user some feedback (a loader or spinner)
Put the results into an array server-side.
JSON encode the array and send it as the response (e.g. echo json_encode($output)
JSON.parse(response) on client-side and you now have a JS object with the results
Put those results in the context menu (again, how depends on the plugin you're using)
AJAX is a great way to do what you want.
Here is a simple AJAX example. Note that in the 2nd .PHP file, that is where you put your database lookup etc.
Whatever you echo from the 2nd script is received by the calling javascript (first script again) and can be inserted into your context menu on-the-fly. Here is another example with a very detailed, step-by-step explanation of the process at the bottom of the answer.
I think you have to use Ajax to get JSON from a PHP file, which you would process on the actual page.
I you create a PHP file called test.php, with the following in it:
<?php
echo json_encode(array('time' => time(), 'hour', date('H')));
?>
Then the Javascript:
<script>
$('#curr_menu_entry').click(function() {
$.getJSON('test.php', function(data) {
$.each(data, function(key, val) {
$('#curr_menu_entry').append('<li id="' + key + '">' + val + '</li>');
});
});
});
</script>
Would that work?

cakephp get all dropdown options from DB

I have a drop-down and drop-down options in separate tables. That's good but now I want to be able to retrieve all the options with the drop-down code. On this page I have all of the drop-downs and items. Let's say the drop-down code is dropdown1.
I'd like to be able to do
$this->Form->input('dropdownitem_id', array('options' => $dropdown['dropdown1']));
Is there a way to do this without a helper?
In the controller,
$dropdownitems = $this->OtherModel->find('list');
$this->set(compact('dropdownitems'));
In your view
$this->Form->input('dropdownitem_id');
The options for select will be populated automatically.
But I don't understand, what you meant by helper ?
1) why do you want to do it "without a helper"?
2) Yes, use normal PHP stuff - ie foreach() loop that echos HTML content to the page
Just look at what content the helper generates, and use PHP to mimic it.
<select name="whatever">
<?php
foreach($items as $item) {
echo '<option value=" . $item['id'] . '">' . $item['name'] . '</option>';
}
?>
</select>
(something like that - I wrote that quickly off the top of my head, but you should get the idea)
You should use containable behavior.
http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html
Then you would query the top level element.
After you have done so.
You must run a foreach loop still as Dave said and format the option.
Let me know if you need help with the containable, they are a life saver and your friend !
I created a custom helper to get the exact behavior I wanted.

Categories