I use ExtJS 1.0.1 (in magento)
I would like to get all checked nodes on form submit. And I stucked here:
tree.html (initialization):
tree<?php echo $this->getId() ?> = new Ext.tree.TreePanel.Enhanced('<?php echo $_divId ?>', {
animate: false,
loader: categoryLoader,
enableDD: false,
containerScroll: true,
rootVisible: '<?php echo $this->getRoot()->getIsVisible() ?>',
useAjax: true,
currentNodeId: <?php echo (int) $this->getCategoryId() ?>,
addNodeTo: false
});
On submit function:
function submit()
{
console.log(tree'.$this->getId().');
// got html code <div id="treeoptions_fieldset992cb0dd9a7da511e5596a229a5386d5_select_catalogb0f2cd4faa4f13b72f0df314bdc222ec" class="tree x-tree"><ul class="x-tree-root-ct x-tree-lines" id="ext-gen5859">...</ul></div>
var checked_nodes = tree'.$this->getId().'.getChecked();
// got an error Uncaught TypeError: Object #<HTMLDivElement> has no method 'getChecked'
}
Magento uses prototypeJS in admin panel.
The question is how to address to checked_nodes to run getChecked()?
Based on some Googling on the Tree function of EXTJS try this
var checked_nodes = tree'.$this->getId().'.select(".x-grid-row-selected");
console.log(checked_nodes);
the .select() method finds all the children nodes that match the selected CSS selector
get works!
I created the object after treegetId() ?> init:
function av_OkButton()
{
var tree = null;
this.onPress = function()
{
var ids = this.tree.getChecked();
}
this.getTree = function()
{
return this.tree;
}
this.setTree = function(treeObj)
{
this.tree = treeObj;
return this;
}
}
okButton = new av_OkButton;
okButton.setTree(tree<?php echo $this->getId() ?>);
And then created submit button:
Cannot understand what the difference between I did and what I have now but it works for me
Related
I've got a complicated little problem here.
I'm building a WordPress plugin where I select a "parent" post (of a custom type that I made called 'step') and then an AJAX function shows a new select bar with all of the children of that parent. I do this by outputting the new and elements in the PHP file that's called in the AJAX function. This works, but now I want to repeat the process to run a function from the same JQuery file when this new outputted element is added to the page. (See Javascript code)
Main php plugin file (in a folder within the plugin directory):
<?php
/*
Plugin Name: n8jadams Step by Step Plugin (WIP)
Plugin URI:
Description:
Author: Nathan James Adams
Author URI: http://nathanjamesadams.com
Version: 0.0.1a
*/
//Exit if accessed directly
if(!defined('ABSPATH')) {
exit;
}
//My custom post type, it works fine
require_once(plugin_dir_path(__FILE__).'n8jadams-step-funnel-cpt.php');
require_once(plugin_dir_path(__FILE__).'n8jadams-ajax.php');
//Add my javascript
function n8jadams_init_javascript() {
wp_register_script('n8jadams_javascript', plugin_dir_url(__FILE__).'n8jadams-scripts.js', array('jquery'),'1.1', false);
wp_enqueue_script('n8jadams_javascript');
}
add_action('wp_enqueue_scripts', 'n8jadams_init_javascript');
//Adds a plugin menu to the wordpress sidebar
function n8jadams_add_plugin_menu() {
add_menu_page('', 'Steps Settings', 4, 'steps-settings', 'n8jadams_steps_settings', '');
}
add_action('admin_menu', 'n8jadams_add_plugin_menu');
//The actual function for the menu page
function n8jadams_steps_settings() {
//Access the database and the tables we want
global $wpdb;
$posts = $wpdb->prefix.'posts';
//Get the user id
$user = wp_get_current_user();
$userid = $user->ID;
//Initialize javascript (it works here!)
n8jadams_init_javascript();
/* Get all the parents */
$parentsquery = "
SELECT `ID`, `post_title`
FROM $posts
WHERE `post_author` = $userid
AND `post_parent` = 0
AND `post_status` = 'publish'
AND `post_type` = 'step'
";
$parentsarray = $wpdb->get_results($parentsquery);
?>
<h4>My Forms:</h4>
<select id="parentselect">
<option id="-1"> - Select Your Step Form - </option>
<?php
//output the parents
for($i=0;$i<sizeof($parentsarray);$i++) {
echo '<option id="'.$parentsarray[$i]->ID.'">'.$parentsarray[$i]->post_title.'</option>';
}
?>
</select>
<div id="displayChildren"></div>
<?php
}
?>
Javascript (n8jadams-scripts.js):
(function($){
$('#parentselect').change(function(s) {
var thisID = s.target[s.target.selectedIndex].id;
var outputDisplay = document.getElementById('displayChildren');
if(thisID != '-1') {
$.ajax({
type: 'POST',
url: 'admin-ajax.php',
data: {
action: 'n8jadams_get_children',
id: thisID
},
success: function(response){
if(response == "") {
outputDisplay.textContent = "This form has no children. Add them in the sidebar menu of this step form.";
} else {
outputDisplay.innerHTML = response;
}
},
error: function(errorThrown) {
alert(errorThrown);
}
});
} else {
outputDisplay.textContent = '';
}
});
// I want this function to work
/*
$('#childselect').change(function(t) {
console.log("test");
});
*/
})(jQuery);
PHP file called by AJAX (n8jadams-ajax.php):
<?php
function n8jadams_get_children() {
//Get the id of the parent
$parent_post_id = $_POST['id'];
//Sanitize the input (Added after question was answered)
$parent_post_id = preg_replace("/[^0-9]/","",$parent_post_id);
//Access database
global $wpdb;
$posts = $wpdb->prefix.'posts';
$user = wp_get_current_user();
$userid = $user->ID;
$childrenquery = "
SELECT `ID`, `post_title`,`post_content`
FROM $posts
WHERE `post_parent` = $parent_post_id
AND `post_status` = 'publish'
AND `post_type` = 'step'
AND `post_author` = $userid
";
//Retrieve the children associated with this parent
$childrenarray = $wpdb->get_results($childrenquery);
//Initialize Javascript (it doesn't work here!)
n8jadams_init_javascript();
if(!empty($childrenarray)) { ?>
<h4>My Steps:</h4>
<select id="childselect">
<option id="-1"> - Select Your Step - </option>
<?php
//output the children of the parent
for($i=0;$i<sizeof($childrenarray);$i++) {
echo '<option id="'.$childrenarray[$i]->ID.'">'.$childrenarray[$i]->post_title.'</option>';
} ?>
</select>
<?php wp_die();
}
}
add_action('wp_ajax_n8jadams_get_children', 'n8jadams_get_children');
add_action('wp_ajax_nopriv_n8jadams_get_children', 'n8jadams_get_children');
?>
Screenshot of Plugin Menu
I cannot figure out why my javascript file isn't working in the PHP file that's called by AJAX. Maybe the vast wisdom of the StackOverflow can help me. Thanks for the help in advance. :)
You are hooking into wp_enqueue_scripts, which is only run for the frontend of Wordpress (the part the average visitor sees). If you want to load a script into wp-admin, the backend of Wordpress, use the admin_enqueue_scripts action.
Since this code does not work in /wp-admin/, you don't need to use admin_enqueue_scripts. I guess the whole problem would be that you are attaching a handler to $('#childselect'), while no such element exists on the page at that time. Use deferring with $(..).on(..):
$(document).on('change', '#childselect', function(e) {
//Black magic
});
Side note: As already mentioned in the comments, the following part contains an unsanitised variable which will allow an attacker to perform sql injections.
$childrenquery = "
SELECT `ID`, `post_title`,`post_content`
FROM $posts
WHERE `post_parent` = $parent_post_id
AND `post_status` = 'publish'
AND `post_type` = 'step'
AND `post_author` = $userid
";
Use WP_Query if at all possible. If this is only used from the backend of Wordpress, don't use wp_ajax_nopriv_*, because users that are not logged in into your site have no right to use that anyway.
I have this function which gets a value from a slider and I need to send it to the server. I call the function which gets the parameter and works fine but the post function is not working inside.
How is it possible to call a jQuery function inside another function? Is there a better way to do this?
function process_decision(slider_value) {
var selectedData = {};
selectedData['pick_pack_point'] = slider_value;
selectedData['gameID'] = <?php echo $booxuser->game->id?>;
selectedData['teamID'] = <?php echo $booxuser->team->id ?>;
selectedData['roundID'] = <?php echo $booxuser->game->getRoundToBePlotted() ?>;
$.post('index.php',
{
'option': 'com_maximulation',
'task': 'max_decision_pickpack.pickpack',
'data': selectedData,
'<?php echo JSession::getFormToken(); ?>': '1'
},
function (response) {
var response_data = JSON.parse(response);
document.getElementById("loanResultDiv").innerHTML = response_data['data']['first'];
},
'text'
);
}
Try using jQuery instead of $, if there is another library imported, the $ could be conflicted.
I use Pickadate.js and JQuery Form Plugin. I have date and time pickers seperately. What I want to do is to disable times in timepicker according to value of datepicker. So, I am trying to get the JSON data into picker.set("disable", [ ]);. I can console.log the plain text but it remains aimless.
I tried a lot and have come across these solutions in that question. But I couldn't launch them. (I adapted pickadate functions and classes to pickatime's.)
// Javascript
$(document).ready(function() {
$("input").click(function() {
$(".datepicker").pickadate({
format: 'yyyy-mm-dd',
formatSubmit: 'yyyy-mm-dd',
min: true,
max: false
});
var $input = $(".timepicker").pickatime({
format: 'HH:i',
formatSubmit: 'HH:i',
formatLabel: 'HH:i'
});
$('.datepicker').change(function() {
$('#form').ajaxSubmit({
target: '#check_result',
url: 'check.php',
success: function showResponse(responseText, $form) {
var picker = $input.pickatime('picker');
picker.set("disable", [
console.log(responseText)
]);
}
});
return false;
});
});
});
// PHP (check.php)
<?php
// Database connection done.
$date = mysqli_real_escape_string($con, $_POST['date']);
$match_query = mysqli_query($con, "SELECT * FROM booking WHERE DATE(time) = '$date'");
$disabled_times = array();
if ($result = $match_query) {
while ($row = mysqli_fetch_assoc($result)) {
$disabled_times[] = $row['time'];
}
mysqli_free_result($result);
}
echo implode($disabled_times);
?>
Can you post an example of the json being returned from your php?
According to the docs (http://amsul.ca/pickadate.js/api/#method-get-disable)
your json should be something like this: [2,30], [4,30], [9,0]
If your json is correct, be sure it is not being passed to the timepicker as a string. Try something like:
var json = JSON.parse(responseText);
picker.set("disable", [ json ]);
UPDATE:
I guess with the following code, your json will return properly:
...
$time = explode(',', $row['time']);
$time[0] = (int)$time[0];
$time[1] = (int)$time[1];
$disabled_times[] = $time;
...
echo json_encode($disabled_times);
I am extremely new to WordPress customisation world and I am working on a task, where I am supposed to assign the content of specific page of WordPress to the JS variable, I am able to fetch the content of the page i need and I can also see in the chrome console tab the content of the page being assigned to the variable, however i am stuck at the error
Uncaught SyntaxError: Unexpected token <
Here is the code I wrote, I am not sure if this is the right way to do things in WordPress but it does seem to give me the result I need so any correction on this approach is also welcome
<script>
jQuery(document).ready(function ($) {
var intern = '<?php
$internPageId = jobboard_option('intern_tab_page');
$the_query = new WP_Query('page_id='.$internPageId);
while ($the_query->have_posts()) :
$the_query->the_post();
the_content();
endwhile;
wp_reset_postdata()?>';
var company = '<?php
$companyPageId = jobboard_option('company_tab_page');
$the_query = new WP_Query('page_id='.$companyPageId);
while ($the_query->have_posts()) :
$the_query->the_post();
the_content();
endwhile;
wp_reset_postdata()
?>';
$('#intern-content').click(function () {
console.log(intern);
$('div.tabs-content').html(intern);
});
$('#company-content').click(function () {
$('div.tabs-content').html(company);
console.log(company);
});
});
</script>
As you can see the code does seem to pull the text of the page but with an error.
What am i doing wrong?
Check this out
<?php
$internPageId = jobboard_option('intern_tab_page');
$post_me = get_post($internPageId);
$excerpt = $post_me->post_content;
$companyPageId = jobboard_option('company_tab_page');
$post_me2 = get_post($companyPageId);
$excerpt2 = $post_me2->post_content;
?>
<input type="hidden" id="intern_tab_page" value="<?php echo $excerpt;?>">
<input type="hidden" id="company_tab_page" value="<?php echo $excerpt2;?>">
<script>
jQuery(document).ready(function ($) {
var intern = $('#intern_tab_page').val();
var company = $('#company_tab_page').val();
$('#intern-content').click(function () {
console.log(intern);
$('div.tabs-content').html(intern);
});
$('#company-content').click(function () {
$('div.tabs-content').html(company);
console.log(company);
});
});
</script>
I got a javascript function and i want to retrieve values from sql
SQL SELECT * FROM db_menu_config returns
ID : 1
parent : menu
icon_path : codebase/imgs/
xml : common/getMenu.php
Javascript
function doOnLoad() {
menu = new dhtmlXMenuObject('menu');
menu.setIconsPath('codebase/imgs/');
menu.enableDynamicLoading('common/menu.inc.php', true);
}
I want to replace 'menu', 'codebase/imgs/' and 'common/menu.inc.php' with variables from sql in order to run and be able to modify it from database without changing the script.
Update
$(document).ready(function () {
$.getJSON('common/json.menu.php', function (data) {
$.each(data, function( key, val ) {
menu = new dhtmlXMenuObject(val.parent);
menu.setIconsPath(val.icon_path);
menu.enableDynamicLoading(val.xml);
});
});
});
The only problem is that if i add another record (a second), it will not work. its now right.
Get your values in PHP then echo them in your JS like this:
function doOnLoad()
{
menu = new dhtmlXMenuObject('<?php echo $parent; ?>');
menu.setIconsPath('<?php echo $icon_path; ?>');
menu.enableDynamicLoading('<?php echo $xml; ?>', true);
}