Autopopulate textarea from database based on dropdown selection - php

I am trying to autopopulate a textarea with values from a (wordpress) database based on the value selected in a select menu. Basically the select menu contains a list of teams and I wish to populate my textarea with names of the players from the selected team.
The problem is that I need to convert the selected text to a php variable in order to use it to query the database. Like so:
PHP
$usergroups = $mingleforum->get_usergroups();
$team_title = $_GET['usergroup'];
$team_id = get_page_by_title( $team_title );
$players = get_users( array (
'meta_key' => 'team-meta',
'meta_value' => $team_id
));
JS
jQuery(function(jQuery){
jQuery('#usergroup').change(function() {
jQuery.ajax({
type: "GET",
url: "http://localhost:8888/dev_wordpress/wp-admin/admin.php?page=mfgroups&mingleforum_action=usergroups&do=add_user_togroup",
data: { usergroup: jQuery(this).find(':selected').text() }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
UPDATE: corrected the url (based on #jterry 's comment) and no longer getting error (although it still isn't working)
I am getting the following error:
GET http://localhost:8888/dev_wordpress/wp-admin/wpf-addusers.php?usergroup=Coq+and+Bulldog 404 (Not Found)

For the points! :D
wpf-addusers.php doesn't exist at that path. Specify the absolute URI and you'll at least make it past the 404 error. Also, it looks like your url parameter has "" on both sides of the variable - you just need one on each side.
EDIT
To access the variable you're looking for (usergroup) to use in your PHP script, you can use $_GET['usergroup']. From there, you can use it as you see fit or insert it as the value of an input element.
If you use the value in an input element, be sure to use htmlentities to properly escape the value.

Related

Is there a way to grab the title of an unsaved post in Wordpress?

I'm working on a WordPress plugin which allows me to choose the proper upload folder regarding the custom post type, taxonomies terms and the title.
I can grab each kind of data when the post is saved, no problem. But how to grab for example a title of a post which hasn't been published?
I tried $_POST, by adding first a name in the title textarea field of WordPress (because it hasn't one) but this totally broke my upload filter with an internal error 500.
I have a partially working code. In a PHP file, I'm enqueuing this Ajax script:
function get_unposted_post_title( $hook ) {
if ( ($hook == 'post-new.php') || ($hook == "post.php" && $_GET['action'] == "edit") ) {
echo "<script>
function posturl(title, url) {
$.ajax({
type: 'POST',
url: url,
data: title,
success: function(title, url) {
console.log(title);
}
});
}
setInterval( function() {
var title = $('#post-title-0').val();
var url = '" .GIA_PLUGIN_URL. "test.php';
posturl(title, url);
}, 5000);
</script>";
}
}
add_action( 'admin_enqueue_scripts', 'get_unposted_post_title', 10, 1 );
Then, in the root of my plugin, I have created a test.php file:
<?php
$keys = array_keys($_POST);
if(isset($keys) && !empty($keys[0])) {
print_r( $keys[0] );
}
?>
This function displays the updated title in the console.log as expected.
However, I'm unable to grab $keys[0] without making the upload filter crashed. Uploaded files are properly moved with the updated path of my filter, except for the last folder which must have a sanitized version of the post title. I'm hooking into wp_handle_upload_prefilter and wp_handle_upload.
If you look at the provided code, I should be able to grab keys[0]... but the problem is that keys[0] give me 'name'... keys[1] give me 'action', keys[2] give me 'wp_nonce'. I don't know why I can't grab keys[0] correctly, it seems that $keys of my test.php isn't updated with a proper value for the key 0.
Why using Ajax if you can use direct MySQLI using the wp_db ?
You can retrieve it the same way as you currently doing it with published one.
If you grab it using MySQLI, there is a column called "post_status"
https://codex.wordpress.org/Post_Status

PHP - Text Field value based on selected value from List Box

may I know how can I setting the text field's value according to the selected value from List box?
Table in database
HTML form
For example:
If I choose "DIP" from the List Box then the Text Field will display "Diploma in Information Technology (Programming)" automatically since I setting the Text Field became disabled.
P/S: List Box function was done. I just need some guides to settle the Text Field
var code = $('#code').val();
$.ajax({
type: "POST",
data: {code: code},
url: 'get_name_list.php',
success: function(data) {
$('#text_field').val(data);
}
in get_name_list.php make a query for fetch program_name and return its value. you can get code from $_POST['code']. and in success you need to set value for that textbox.
You can do it using Javascript/Jquery. Take idea from this.
Example :
1.) $ProgInfo is array of prog_code and prog_name.
2.) On change dropdown call below function with parameter (prog_code)
3.) getProgName will return you prog_name
Javascript function :
function getProgName(prog_code=null){
var json_user = <?=json_encode($ProgInfo)?>;
if(json_user.hasOwnProperty(prog_code)){
return json_user[prog_code];
}else{
return null;
}
}
$('id or class of name').html(getProgName("Your prog_code"));

How to preload <options> and <select> with Jquery-option-tree plugin

I am using Jquery-option-tree plugin on a standalone website not based on Wordpress as in example 7 on the demo page, except that I am not passing a .txt file but a PHP page is generating the array of < options > to be passed to the plugin.
http://kotowicz.net/jquery-option-tree/demo/demo.html
This perfectly works: so let's say that the user wants to select a category for a new product, the plugin suits the purpose generating a nice: " Food -> fruit -> apples " upon user clicks. (see demo page ex. 7)
What instead if a product already exists with its categories assigned? I want to show it to the user when he edit that product, preloading the tree.
I have the ids path coming from database, so it would just be a matter of having the plugin to run without the user interact, using the value I pass. I saw this question: jQuery simulate click event on select option
and tried to simulate user' click with this (and other) methods with no luck.
$('#select')
.val(value)
.trigger('click');
Here the call to the function:
$(function() {
var options = {
empty_value: '',
set_value_on: 'each',
indexed: true, // the data in tree is indexed by values (ids), not by labels
on_each_change: '/js/jquery-option-tree/get-subtree.php', // this file will be called with 'id' parameter, JSON data must be returned
choose: function(level) {
return 'Choose level ' + level;
},
loading_image: '/js/jquery-option-tree/ajax-load.gif',
show_multiple: 10, // if true - will set the size to show all options
choose: ''
};
$.getJSON('/js/jquery-option-tree/get-subtree.php', function(tree) { // initialize the tree by loading the file first
$('input[name=parent_category_id]').optionTree(tree, options);
});
});
Here you can see the plugin:
https://code.google.com/p/jquery-option-tree/
I don't know that plugin, but looking at the examples there seems to be one that fits your need; Example 6 - AJAX lazy loading & setting value on each level change.
This would, in theory, just require some config options:
preselect: {'demo6': ['220','226']}, // array of default values - if on any level option value will be in this list, it will be selected
preselect_only_once: true, // prevent auto selecting whole branch when user maniputales one of branch levels
get_parent_value_if_empty: true,
attr: "id" // we'll use input id instead of name
If this doesn't fit you need though, you could initiate it from an event, like change, keyup, etc.
$(document).on('change', '#select', function() {
$('#nextSelect').val($(this).val());
})
$(document).on('change', '#nextSelect', function() {
$('#finalInput').val($(this).val());
})
Yes, you are right Mackan ! I saw that "preselect" option but I was initially unable to use it transferring the path from database to javascript, I ended up with my "newbie" solution to match the syntax:
preselect: {'parent_category_id': [0,'2','22']},
PHP
$category_path comes from DB query and is like "0,2,76,140,"
$path = explode(',', $category_path);
$preselect="";
foreach ($path as $value) {
$int = (int)$value;
if ($int != 0) $preselect.= "'". $int ."',";
else $preselect.= $int.","; // have to do this as ZERO in my case has to be without apostrophes ''
}
$preselect = "{'parent_category_id':[".$preselect."]}"
JS
var presel= <?php echo($preselect); ?>;
var options = {
preselect: (presel),
}
Any suggestion for a better code ?
Thanks a lot !!

JQuery PHP AJAX filter based on multiple checkbox array

I'm hoping someone can point me in the right direction. I'm primarily a PHP developer but I'm really trying to get my head around jquery and javascript more due to the increasing number of AJAX work requests we receive.
Basically I have a sidebar filter that works fine. It is based on 3 things. A group, category and sub category. So for example, Boots as the category, Leather (type) as a sub category and Black (colour) as tertiary filter. At the moment it works based on a GET form. However I want to use live filters instead so as they click a checkbox, it updates the results based on a query. I can write all the PHP for this but I'm struggling to get the data together by jQuery. I've looked at using jQuery .each and .change.
There are 3 groups of checkboxes and they are all based on arrays. So for example again: category[], subcategory[], tertiary[].
Thanks in advance for the help.
Some example HTML
<input id="$ProdCatLabel" class="side_filter_checkbox" name="ProdCatFil[]" type="checkbox" value="$ProdCat">
<input id="$ProdSubCatLabel" class="side_filter_checkbox" name="ProdSubCatFil[]" type="checkbox" value="$ProdSubCat">
<input id="$BrandingLabel" class="side_filter_checkbox" name="BrandFil[]" type="checkbox" value="$Branding">
My attempts:
var prodcats = $('side_filter_prodcats[name="ProdCatFil[]"]:checked')
.map(function() { return $(this).val() })
.get()
.join(",");
var prodsubcats = $('side_filter_prodsubcats[name="ProdSubCatFil[]"]:checked')
.map(function() { return $(this).val() })
.get()
.join(",");
$.ajax({
type: "POST",
url: "[ENTER PHP URL HERE]",
data: "ProdCats=" + prodcats + "ProdSubCats=" + prodsubcats,
success: function(msg) { $(".content_area").html(msg); }
});
Am I barking up the right tree here?
Ok let's say your checkboxes have the classes category, subcategory and tertiary. You could attach a click event handler to each group that calls the function to load in the correct data, passing the checkbox value and a class or data-attribute to the function as parameters.
// Your main DOM ready function
$(document).ready(function() {
// Checkboxes click function
$('input[type="checkbox"]').on('click',function(){
// Here we check which boxes in the same group have been selected
// Get the current group from the class
var group = $(this).attr("class");
var checked = [];
// Loop through the checked checkboxes in the same group
// and add their values to an array
$('input[type="checkbox"].' + group + ':checked').each(function(){
checked.push($(this).val());
});
refreshData(checked, group);
});
function refreshData($values, $group){
// Your $values variable is the array of checkbox values
// ie. "boot", "shoe" etc
// Your $group variable is the checkbox group
// ie. "category" or "subcategory" etc.
// Now we can perform an ajax call to post these variable to your php
// script and display the returned data
$.post("/path/to/data.php", { cats: $values, type: $group }, function(data){
// Maybe output the returned data to a div
$('div#result').html(data);
});
}
});
Here's an example of the checkbox click function in action: http://jsfiddle.net/F29Mv/1/

How does AJAX handle multiples instances of a variable?

I am currently editing a WordPress plugin, which allows you to filter posts by category, once a category is selected, the posts for that caregory are displayed as a checklist on the widget, the user can select the posts they wish to display in their sidebar/widget area of the theme.
I have taken the widget to the point that the user can select their post, the widget allows a single post to be selected, however if more than one is selected and the save button is pressed, the form returns only the last slected post.
After some searching, I have found the problem to be on the form return.
It is either to do with the update, or the way AJAX handles multiple instances of a variable.
the information posted to the server is as follows:
action save-widget
add_new
id_base single_post_super_widget
multi_number
savewidgets 9bc3d79f1c
sidebar lcp-sb
widget-height 200
widget-id single_post_super_widget-2
widget-single_post_super_widget[2][object_to_use] 5005
widget-single_post_super_widget[2][object_to_use] 4892
widget-single_post_super_widget[2][object_to_use] 4607
widget-single_post_super_widget[2][object_type] 72
widget-single_post_super_widget[2][paged] 1
widget-single_post_super_widget[2][tab] all
widget-single_post_super_widget[2][title_override]
widget-width 400
widget_number 2
Where object_to_use is the post(s) being selected.
the information being sent is defined here:
var theArgs = {
action: jQuery('input.widget_class:hidden', widgetDiv).first().val() + '-get-metabox',
widget: widgetDivId,
number: widgetNumber,
blog_id: jQuery(widgetInputBase + 'blog_id').val(),
object_type: jQuery(widgetInputBase + 'object_type').val(),
tab: currentTab,
paged: currentPage,
object_to_use: jQuery('input[type=checkbox][name$="[object_to_use]['+currentTab+']"]:checked', widgetDiv).first().val(),
title_override: jQuery(widgetInputBase + 'title_override').val(),
excerpt_override: jQuery(widgetInputBase + 'excerpt_override').val(),
searched: ('search' == currentTab) ? jQuery('input.quick-search', widgetDiv).first().val() : ''
};
and the jQuery.post action:
jQuery.post(
ajaxurl,
theArgs,
function( r ) {
jQuery('.ajax-feedback').css('visibility', 'hidden');
if ( r && r.length > 2 ) {
jQuery('div.widget-content', widgetDiv).html(r);
}
}
);
In relation to the question, widget-single_post_super_widget[2][object_to_use] is being posted multiple times, how does AJAX handle this? Does each post/variable have to be unique?
widget-single_post_super_widget[2][object_to_use] is being posted multiple times, how does AJAX handle this?
There is nothing Ajax specific about this. You just get multiple copies of the key in the data submitted to the server.
Does each post/variable have to be unique?
No.
In most server side environments, you can get all the data just by using the right function. For example with Perl's CGI.pm module, you just get the parameter in list context:
my #thing = $cgi->param('widget-single_post_super_widget[2][object_to_use]');
… and it will 'just work'.
PHP is special. If the name ends in [] then it will just create an array in $_POST and friends. If it doesn't, then it will discard all but the last item. (Unless I'm misremembering and it keeps the first instead).
You can use ajax using jQuery.. then you can pass multiple instances of variable :-
like this :-
if(roleId !='' && roleId != '16'){
jQuery('#user_id_div').hide();
jQuery('#loading_image').show().html("<label> </label> <img src='<?php echo $this->webroot; ?>img/ajax-loader.gif' alt='Loading...'>");
urlData = "<?php echo Router::url(array('controller' => 'users', 'action' => 'getmultipleVendors')) ?>" ;
postData = "vendorType=" + roleId;
jQuery.ajax({
url: urlData,
data: postData,
success: function(data) {
jQuery('#PromoCodeUserId').html(data);
jQuery('#user_id_div').show();
jQuery('#loading_image').hide();
}
});
in postdata field you can post many data as avariables..

Categories