I'm building a wordpress plugin for a cookie notice, i want the cookies to be created with PHP. And the button in the notice bar is supposed to run a php function, ajax is not really working with me right now.
My ajax request is being processed as far as i know, in the network tab it shows admin-ajax.php with status 200, but it just won't call the actual function.
this is my code
Main plugin file
function setAjaxCallbacks(){
add_action('wp_ajax_accepted', 'accepted');
add_action('wp_ajax_nopriv_accepted', 'accepted');
}
add_action('init', 'setAjaxCallbacks');
function accepted(){
die('test');
echo 'LOLALLES';
global $wpdb;
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
wp_die('0 ', 400);
echo '<script>
alert("jhwgvbht ij")
</script>';
wp_die();
}
isset($_COOKIE['cookieBar']) or setCookieBar();
function setCookieBar()
{
if (!is_admin()){
add_action('wp_enqueue_scripts', 'enqueue_script_custom');
function enqueue_script_custom()
{
wp_enqueue_style('CookieBarStyle', plugin_dir_url(__FILE__) . 'css/styles.css');
wp_enqueue_script('ajax-script', plugins_url('/js/my_query.js', __FILE__), array('jquery'));
wp_localize_script('ajax-script', 'ajax_object',
array('ajaxurl2' => 'https://wordpressjip.jmulder.dt2/wp-admin/admin-ajax.php', 'we_value' => 1234));
wp_print_scripts('ajax-script');
}
?>
<div class="cookieBar" id="cookieBar" style="display: block">
<p align="center"></p>
<button id="submitCookies" class="submitCookies" name="accepted">Accepteer</button>
</div>
<?php
}
}
my_query.js
jQuery(document).ready(function ($) {
jQuery(".submitCookies").click(function (event) {
event.preventDefault();
jQuery.ajax({
url: ajax_object.ajaxurl2,
type: 'POST',
data: {
action: 'accepted',
whatever: 1234
},
succes: function (response) {
return response;
}
})
})
});
Function named "accepted" is inside another function, that's why it is not working. You need to learn how ajax is working in wordpress. Please go through following link. It will teach you how to use ajax in wordpress https://medium.com/techcompose/how-to-use-ajax-precisely-in-wordpress-custom-themes-dc61616720a8
Following code may help you:
<?php
function setAjaxCallbacks()
{
add_action('wp_ajax_accepted', 'accepted');
add_action('wp_ajax_nopriv_accepted', 'accepted');
}
add_action('init', 'setAjaxCallbacks');
function accepted()
{
echo 'LOLALLES';
global $wpdb;
$whatever = intval($_POST['whatever']);
$whatever += 10;
echo $whatever;
exit;
}
add_action('wp_enqueue_scripts', 'enqueue_script_custom');
function enqueue_script_custom()
{
wp_enqueue_style('CookieBarStyle', plugin_dir_url(__FILE__) . 'css/styles.css');
wp_enqueue_script('ajax-script', plugins_url('/js/my_query.js', __FILE__), array('jquery'));
wp_localize_script(
'ajax-script',
'ajax_object',
array('ajaxurl2' => 'https://wordpressjip.jmulder.dt2/wp-admin/admin-ajax.php', 'we_value' => 1234)
);
wp_print_scripts('ajax-script');
}
function setCookieBar()
{
if (!is_admin()) {
if (! isset($_COOKIE['cookieBar'])) {
?>
<div class="cookieBar" id="cookieBar" style="display: block">
<p align="center"></p>
<button id="submitCookies" class="submitCookies" name="accepted">Accepteer</button>
</div>
<?php
}
}
}
add_action( 'wp_footer', 'setCookieBar' );
Related
I'm creating a custom block inside a plugin. It's a drop down selector of categories for posts. I'm simply trying to update the query of a query loop block on the same page. However I'm not sure how to access the query of the query loop block.
I've tried the above however getting the blockId of the block doesn't seem to be possible on the front end. Does anyone know how i can reference the query loop block from a front end js file?
plugin.php
function tapacode_selector_ajax_callback() {
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'wp-tapacode-nonce' ) ) {
die ( 'Busted!' );
}
$category = intval( $_POST['category']);
$query_args = array(
'cat' => $category
);
$query = new WP_Query( $query_args );
wp_send_json( $query->posts );
wp_die();
}
add_action( 'wp_ajax_tapacode_selector', 'tapacode_selector_ajax_callback' );
add_action( 'wp_ajax_nopriv_tapacode_selector', 'tapacode_selector_ajax_callback' );
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
function my_enqueue() {
wp_register_script( 'ajax-selector-script', plugins_url( '/selector.js', __FILE__ ), array( 'wp-blocks', 'wp-editor', 'wp-element', 'jquery' ), '1.0', true );
wp_enqueue_script( 'ajax-selector-script' );
// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'ajax-selector-script', 'ajax_object',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'wp-tapacode-nonce' )
) );
}
another plugin.php file
<p <?php echo get_block_wrapper_attributes(); ?>>
<?php wp_dropdown_categories(); ?>
</p>
selector.js
document.addEventListener('DOMContentLoaded', setupCategorySelector, false);
function setupCategorySelector() {
document.getElementById('cat').onchange = function () {
// if value is category id
if (this.value !== '-1') {
if (typeof wp !== 'undefined' && wp.data) {
const blockId = document.querySelector('.wp-block-tapacode-category-selector').getAttribute('data-block-id');
const queryBlock = wp.data.select('core/block-editor').getBlock(blockId);
queryBlock.setAttributes({ categories: this.value });
queryBlock.update();
}
I'm developing an elementor widget as a plugin. The font view js working fine but the backend (Elementor edit page) js are not working. I'm using hooks (admin_enqueue-scripts, wp_enqueue_scripts, elementor/editor/before_enqueue_scripts, elementor/elements/categories_registered, elementor/widgets/widgets_registered, elementor/editor/after_enqueue_scripts, elementor/frontend/init). Which is perfect the js loading for elementor font page. Now, My js effects are not working on Elementor edit page. How can I solve the problem?
The enqueue code:- `public function bwdic_admin_editor_scripts() {
add_filter( 'script_loader_tag', [ $this, 'bwdic_admin_editor_scripts_as_a_module' ], 10, 2 );
}
public function bwdic_admin_editor_scripts_as_a_module( $tag, $handle ) {
if ( 'bwdic_the_compare_editor' === $handle ) {
$tag = str_replace( '<script', '<script type="module"', $tag );
}
return $tag;
}
private function include_widgets_files() {
require_once( __DIR__ . '/widgets/bwdic-compare.php' );
}
public function bwdic_register_widgets() {
// Its is now safe to include Widgets files
$this->include_widgets_files();
// Register Widgets
\Elementor\Plugin::instance()->widgets_manager->register_widget_type( new Widgets\BWDMEcompare() );
}
private function add_page_settings_controls() {
require_once( __DIR__ . '/page-settings/image-compare-manager.php' );
new Page_Settings();
}
// Register Category
function bwdic_add_elementor_widget_categories( $elements_manager ) {
$elements_manager->add_category(
'bwd-image-compare-category',
[
'title' => esc_html__( 'BWD Image Compare', 'bwd-image-compare' ),
'icon' => 'eicon-person',
]
);
}
public function bwdic_all_assets_for_the_public(){
wp_enqueue_script( 'bwdic_compare_the_main_js', plugin_dir_url( __FILE__ ) . 'assets/public/js/custom.js', array('jquery'), '1.0', true );
$all_css_js_file = array(
'bwdic_compare_main_css' => array('bwdic_path_define'=>BWDIC_ASFSK_ASSETS_PUBLIC_DIR_FILE . '/css/style.css'),
);
foreach($all_css_js_file as $handle => $fileinfo){
wp_enqueue_style( $handle, $fileinfo['bwdic_path_define'], null, '1.0', 'all');
}
}
public function bwdic_all_assets_for_elementor_editor_admin(){
wp_enqueue_script( 'bwdic_compare_the_main_js_admin', plugin_dir_url( __FILE__ ) . 'assets/public/js/custom.js', array('jquery'), '1.0', true );
$all_css_js_file = array(
'bwdic_compare_admin_icon_css' => array('bwdic_path_admin_define'=>BWDIC_ASFSK_ASSETS_ADMIN_DIR_FILE . '/icon.css'),
);
foreach($all_css_js_file as $handle => $fileinfo){
wp_enqueue_style( $handle, $fileinfo['bwdic_path_admin_define'], null, '1.0', 'all');
}
}
public function __construct() {
// For public assets
add_action('wp_enqueue_scripts', [$this, 'bwdic_all_assets_for_the_public']);
// For Elementor Editor
add_action('elementor/editor/before_enqueue_scripts', [$this, 'bwdic_all_assets_for_elementor_editor_admin']);
// Register Category
add_action( 'elementor/elements/categories_registered', [ $this, 'bwdic_add_elementor_widget_categories' ] );
// Register widgets
add_action( 'elementor/widgets/widgets_registered', [ $this, 'bwdic_register_widgets' ] );
// Register editor scripts
add_action( 'elementor/editor/after_enqueue_scripts', [ $this, 'bwdic_admin_editor_scripts' ] );
$this->add_page_settings_controls();
}`
So i just found out about the jquery auto complete and i would like to add it to my web-page. I want to hook it up to my php code so i can search my sql database. However Whenever i try to run my auto complete,it doesnt seem to find the php array im passing ( im just trying to get an array to work for now) . Can someone help?
Jquery Code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#tags" ).autocomplete({
source: "test.php"
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
PHP code
<?php
$data[] = array(
'c++','Java','JavScript',"c#" );
echo json_encode($data);
?>
This is an updated version of your answer which should resolve the deprecated SQL driver and the injection issue. You need to replace the SECOND_COLUMNNAME with your actual column's name. Aside from that I think this should work.
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=DB','username','password');
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
if(empty($_REQUEST['term']))
exit();
//require_once('connect.php'); connection to db is in this file so connection is not needed
$query = 'SELECT name, SECOND_COLUMNNAME FROM locations
WHERE name
LIKE ?
ORDER BY id ASC
LIMIT 0,10';
$stmt = $dbh->prepare($query);
$stmt->execute(array(ucfirst($_REQUEST['term']) . '%'));
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = array(
'label' => $row['name'],
'value' => $row['SECOND_COLUMNNAME']
);
}
echo json_encode($data);
flush();
Links:
http://php.net/manual/en/pdo.prepared-statements.php
http://php.net/manual/en/pdo.connections.php
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
How can I prevent SQL injection in PHP?
Also not sure if there was anything else inside connect.php, you might need to bring that back.
The array pattern used here should be as below.
<?php
$data = array(
array("value"=>'C++'),
array("value"=>'Java'),
array("value"=>'Javascript'),
array("value"=>'C#'),
);
echo json_encode($data);
If you're using PHP >= 5.4:
$data = [
[ 'value' => 'C++' ],
[ 'value' => 'Java' ],
[ 'value' => 'Javascript' ],
[ 'value' => 'C#' ]
];
echo json_encode( $data );
Here's a working example of my autocomplete code:
function get_data(type, target, min_length )
{
$(target).autocomplete({
source: function( request, response ) {
var submit = {
term: request.term,
type: type
};
$.ajax({
url: '/request/get',
data: { thisRequest: submit},
dataType: "json",
method: "post",
success: function( data ) {
response($.map( data.Data, function( item ) {
return {
label: item.label,
value: item.label
}
}));
}
});
},
minLength: min_length
})
}
<?php
$data = array(
'c++',
'Java',
'JavScript',"c#" );
echo json_encode($data);
?>
So i want with Pratik Soni advice and did a search. Here is the php code if anyone wants to use it
<?php
// Connect to server and select databse.
$dblink = mysql_connect('localhost','username','password') or die(mysql_error());
mysql_select_db('DB');
?>
<?php
if(!isset($_REQUEST['term']))
exit();
require('connect.php');
$term =
$query = mysql_query('
SELECT * FROM locations
WHERE name
LIKE "'.ucfirst($_REQUEST['term']).'%"
ORDER BY id ASC
LIMIT 0,10', $dblink
);
$data = array();
while($row = mysql_fetch_array($query, MYSQL_ASSOC)){
$data[] = array(
'label' => $row['name'],
'value' => $row['name'],
);
}
echo json_encode($data);
flush();
I have this simple wordpress menu that I want to load in div element.
<?php
$menuParameters = array(
'theme_location' => 'sidebar-menu',
'container' => false,
'echo' => false,
'items_wrap' => '%3$s',
'depth' => 0,
);
echo strip_tags(wp_nav_menu( $menuParameters ), '<a>' );
?>
I'm using modernizr and jQuery load() to load the php file into the div element when a certain media query is detected.
jQuery(document).ready(function($){
if(Modernizr.mq('only all and (max-width:600px)')) {
$('#content-wrapper').removeClass('col-4-5');
$("#trending-Container").load( 'wordpress/wp-content/themes/test_theme/navbar-mobile.php' );
}
});
This works if just use some html or if just echo some string but when I use a wordpress function like above or something like the_title() I get a 500 internal server error.
Any ideas?
I suppose you should no directly access any file in your theme for security reasons.
Register your function in funcitons.php in your theme and then call that function_name as refereed over here enter link description here
jQuery(document).ready(function($) {
var data = {
action: 'my_action',
whatever: ajax_object.we_value // We pass php values differently!
};
// We can also pass the url value separately from ajaxurl for front end AJAX implementations
jQuery.post(ajax_object.ajax_url, data, function(response) {
alert('Got this from the server: ' + response);
});
});
and register your action in functions.php
<?php
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {
if( 'index.php' != $hook ) return; // Only applies to dashboard panel
wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery'));
// in javascript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'ajax-script', 'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
}
// Same handler function...
add_action('wp_ajax_my_action', 'my_action_callback');
function my_action_callback() {
global $wpdb;
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
die();
}
I'm trying to pass a variable to a javascript file from a plugin. Here is my plugin code:
<?php
/**
* #package JS Test
* #version 1.0
*/
/*
Plugin Name: JS Test
Description: JS Test.
*/
add_action('init', 'my_init');
add_action( 'wp', 'test_js' );
function my_init() {
wp_enqueue_script( 'jquery' );
}
function test_js() {
wp_register_script ('testjs', plugins_url('jstest.js', __FILE__));
wp_enqueue_script ('testjs');
$my_arr = array('my array',
'name' => 'Test',
);
$my_json_str = json_encode($my_arr);
$params = array(
'my_arr' => $my_json_str,
);
wp_enqueue_script('my-java-script');
wp_localize_script('my-java-script', 'php_params', $params);
}
Here is the jstest.js file:
jQuery(document).ready(function() {
alert ('test');
var my_json_str = php_params.my_arr.replace(/"/g, '"');
var my_php_arr = jQuery.parseJSON(my_json_str);
alert(php_params);
});
What I get is this error in JavaScript:
ReferenceError: php_params is not defined
Anybody see what I'm doing wrong?
You Don't need to enqueue a script just for your localized parameters you can use your testjs for that, here is a quick plugin i cooked up to test:
<?php
/*
Plugin Name: PHP to JS
Plugin URI: http://en.bainternet.info
Description: wordpress passing variable to javascript
http://stackoverflow.com/questions/12761904/wordpress-passing-variable-to-javascript
Version: 1.0
Author: Bainternet
Author URI: http://en.bainternet.info
*/
add_action('init', 'my_init');
add_action( 'wp', 'test_js' );
function my_init() {
/wp_enqueue_script( 'jquery' );
}
function test_js() {
wp_register_script ('testjs', plugins_url('jstest.js', __FILE__));
wp_enqueue_script ('testjs');
$my_arr = array('my array',
'name' => 'Test',
);
$my_json_str = json_encode($my_arr);
$params = array(
'my_arr' => $my_json_str,
);
wp_localize_script('testjs', 'php_params', $params);
}
add_action('wp_footer','footertestjs');
function footertestjs(){
?>
<script>
jQuery(document).ready(function() {
alert ('test');
var my_json_str = php_params.my_arr.replace(/"/g, '"');
var my_php_arr = jQuery.parseJSON(my_json_str);
alert(php_params);
});
</script>
<?php
}
as you can see here the wp_localized_script uses the same script as you enqueue and not a fake script.