Wordpress Media Uploader register & enqueue javascript correctly - javascript

I have the following function to open the Wordpress Media Uploader within the main php file of a Wordpress plugin. The problem is getting the javascript to fire:
function media_uploader_enqueue() {
wp_enqueue_media();
wp_register_script( 'media-uploader', plugins_url( 'media-lib-uploader.js' , __FILE__ ), array( 'jquery', NULL, false ) );
wp_enqueue_script( 'media-uploader');
}
add_action( 'admin_enqueue_scripts', 'media_uploader_enqueue');
and the following in media-lib-uploader.js
jQuery(document).ready(function($){
var mediaUploader;
$('#upload_image_button').click(function(e) {
e.preventDefault();
if (mediaUploader) {
mediaUploader.open();
return;
}
mediaUploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
}, multiple: false });
mediaUploader.on('select', function() {
var attachment = mediaUploader.state().get('selection').first().toJSON();
$('#background_image').val(attachment.url);
});
mediaUploader.open();
});
});
This is the html for the settings page:
<input type="text" id="background_image" name="background_image" value="<?php echo get_option('background_image'); ?>" /><input id="upload_image_button" class="button" type="button" value="Upload Image" />
I cannot find the error within the code. I have even tried;
wp_deregister_script
Have I registered and enqueued the javascript correctly? Or is there a problem with the javascript itself?

Fixed the issue once I defined this function ahead of all others in my main plugin php file. Simple!

Related

How to upload a file to Wordpress database from a custom Gutenberg block?

I am looking to create a custom Gutenberg block with javascript that has an input that will let you upload a file of any format, and then store it in the database so I can show it on the front-end inside html a tag to be downloaded.
Here is the code inside my index.js inside my block folder (I know it is not good code. it is just for demo purposes)
wp.blocks.registerBlockType('sab/upload-block', {
title: 'Upload Block',
icon: 'lightbulb',
category: 'common',
attributes: {
url: 'string', default: '',
},
description: 'Add downloadable files to your post.',
example: { attributes: {}},
edit: function (props) {
function fileDecoder(identifier) {
const input = document.querySelector(`#${identifier}`);
const fReader = new FileReader();
fReader.readAsDataURL(input.files[0]);
fReader.onloadend = function(event) {
setAttribute({url: event.target.result})
}
}
return (
<>
<label>Upload a file</label>
<input id='upload-file' type="file" onChange={() => props.fileDecoder('upload-file')} />
</>
)
},
save: function () {
return null
}
})
And here is the code inside my index.php
<?php
/*
Plugin Name: Upload Block
Description: Add downloadable files to your post.
Version: 1.0
Author: XYZ
*/
if( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
// file inside my inc folder that creates the markup
require_once plugin_dir_path(__FILE__) . 'inc/generateUploadBlockHTML.php';
class UploadBlock {
function __construct() {
add_action('init', array($this, 'assets'));
}
function assets() {
register_block_type(__DIR__, array(
'render_callback' => array($this, 'theHTML')
));
}
function theHTML($attributes) {
if (isset($attributes)) {
// IDEALLY UPLOAD THE FILE HERE SO I CAN JUST USE IT ELSEWHERE, BUT I DO NOT KNOW HOW TO DO IT
return <a href="$attributes['data']['url]" download="file">
} else {
return NULL;
}
}
}
$uploadBlock = new UploadBlock();
I tried using just javascript to achieve this but I believe i need to upload the file on Wordpress database so I can use it in my other templates.

WP wp_ajax_function is not calling PHP function

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' );

CHALLENGE: Load Gravity Forms via AJAX - Change working PHP solution to Gutenberg code

I had the need to load a Gravity Form through Ajax on a push of a button (in PHP/Wordpress), and thanks to Steven Henty, I've found his solution to fix my issue. Modified it at little to open my form in a modal (lity modal), and it works!
However.... Now I started to migrate my site to the new Gutenberg editor in Wordpress. So I need a system that can do the same from a Gutenberg block (javascript) code.
I can code some, but I am not hardcore, so would love if anyone could tell me how to implement this former (PHP based) 'system', for instance to a (javascript based) Gutenberg Button-block, that implements this code. Here is the code for the current (working) button:
button.php
// Hook up the AJAX ajctions
add_action('wp_ajax_nopriv_gf_button_get_form', 'gf_button_ajax_get_form');
add_action('wp_ajax_gf_button_get_form', 'gf_button_ajax_get_form');
// Add the "button" action to the gravityforms shortcode
// e.g. [gravityforms action="button" id=1 text="button text"]
add_filter('gform_shortcode_button', 'gf_button_shortcode', 10, 3);
function gf_button_shortcode($shortcode_string, $attributes, $content)
{
$a = shortcode_atts(array(
'id' => 0,
'text' => 'Open',
'button_class' => '',
'button_style' => ''
), $attributes);
$form_id = absint($a['id']);
$curr_lang = ICL_LANGUAGE_CODE;
if ($form_id < 1) {
return '<div>Missing the ID attribute.</div>';
}
gravity_form_enqueue_scripts($form_id, true);
$ajax_url = admin_url('admin-ajax.php');
$html = sprintf('<button id="gf_button_get_form_%d" class="gf_button_get_form %s" style="%s"><div class="gf_button_get_form-label">%s</div></button>', $form_id, $a['button_class'], $a['button_style'], $form_id, $a['text']);
$html .= "<script>
(function (SHFormLoader, $) {
$('#gf_button_get_form_{$form_id}').click(function(){
$.ajaxSetup({
beforeSend: function() {
$('.spinner_{$form_id}').addClass('active');
},
complete: function() {
$('.spinner_{$form_id}').removeClass('active');
var fieldsWithHiddenLabels = $('.gfield.hidden-label');
if (fieldsWithHiddenLabels.length) {
fieldsWithHiddenLabels.each(function(){
if($(this).hasClass('gfield_contains_required')){
$(this).find('.ginput_container label').prepend('<span class=\"gfield_required\">*</span>');
}
});
}
}
});
$.get('{$ajax_url}?lang={$curr_lang}&action=gf_button_get_form&form_id={$form_id}',function(response){
lity(response);
if(window['gformInitDatepicker']) {gformInitDatepicker();}
});
});
}(window.SHFormLoader = window.SHFormLoader || {}, jQuery));
</script>";
return $html;
}
function gf_button_ajax_get_form() {
$form_id = isset($_GET['form_id']) ? absint($_GET['form_id']) : 0;
gravity_form($form_id, true, false, false, false, true);
die();
}
I am using the excellent create-guten-blocks as boilerplate, and my template block file looks like this:
form-button.js
import './style.scss';
import './editor.scss';
const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
registerBlockType( 'my-blocks/form-button', {
title: __( 'Form Button' ),
icon: heart,
category: 'common',
keywords: [
__( 'my-blocks — Form Button' )
],
edit: function( props ) {
return (
<div className={ props.className }>
<p>— Hello from the backend.</p>
<p>
CGB BLOCK: <code>configit-blocks</code> is a new Gutenberg block
</p>
<p>
It was created via{ ' ' }
<code>
<a href="https://github.com/ahmadawais/create-guten-block">
create-guten-block
</a>
</code>.
</p>
</div>
);
},
save: function( props ) {
return (
<div>
<p>— Hello from the frontend.</p>
<p>
CGB BLOCK: <code>configit-blocks</code> is a new Gutenberg block.
</p>
<p>
It was created via{ ' ' }
<code>
<a href="https://github.com/ahmadawais/create-guten-block">
create-guten-block
</a>
</code>.
</p>
</div>
);
},
} );
Hope this makes sense. This is my second post on Stackoverflow, so please let me know if you need more details ... Really hope one of you skilled people can handle this. Thanks!

jQuery load() internal server error with wordpress

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();
}

wordpress passing variable to javascript

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.

Categories

Resources