I am using PDF Embedder to embed pdf into wp webpage.
I'd like it to embed pdf when a button is clicked.
When I add the pdf media PDF Embedder inserts shortcode in backend editor:
[pdf-embedder url="http://example.com/wp-content/uploads/securepdfs/2019/11/nameofpdf.pdf"]
I created a js button onlick function to execute this shortcode
<script>
function EmbedPDF(){
[pdf-embedder url="http://example.com/wp-content/uploads/securepdfs/2019/11/nameofpdf.pdf"];
}
</script>
However when clicking button I get error on console:
Uncaught SyntaxError: Unexpected token '<'
titleofpdf<br/>;
As previous poster mentioned PHP Shortcodes are excecuted on the server-side thus cannot be excecuted via direct Javascript, for this you can make an AJAX call (depending on the type of output you're expecting)
You could try something as follows (untested but i think youäll get the idea) :)
This code goes into your functions.php file:
<?php
// Load your custom js file
function my_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/custom.js', array('jquery') );
// Here we need to send the ajax_urladmin-ajax url as a variable to the external JS file since we can't use PHP to get the URI in Javascript
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
// Add a method for opeing the PDF
function loadPDF() {
$url = isset($_REQUEST["post_id"]) ? $_REQUEST["post_id"] : null;
if(!$url) // { } Handle invalid URL / Perform checks
echo do_shortcode('[pdf-embedder url="'.$url.'"]');
}
// Define our ajax hooks
// wp_ajax_nopriv_ = for visitors
// wp_ajax_ = for logged in users
add_action( 'wp_ajax_loadPDF', 'loadPDF' );
add_action( 'wp_ajax_nopriv_loadPDF', 'loadPDF' );
?>
This code goes into your custom js file:
jQuery( document ).ready() {
jQuery('.pdf-button').on('click', function() {
// Get the URL that should be loaded
var url = jQuery(this).data('url');
jQuery.ajax({
type: "post",
url : ajax_object.ajaxurl,
data : {action: "loadPDF", url: url},
success: function(data){
// Redirect the output to a container ie. div
jQuery('.my-container').html(data);
}
});
});
});
Example HTML:
<div class="btn pdf-button" data-url="http://example.com/wp-content/uploads/securepdfs/2019/11/nameofpdf.pdf">
</div>
<div class="my-container">
<!-- PDF Output -->
</div>
Related
I’m new to WP and not overly familiar with AJAX either but I’m trying to get a very simple AJAX call to work, I think I’m nearly there but I can’t get any results to return back from the AJAX call, I’ve stripped everything down to the bare bones to get it working and am just returning the string ‘This is AJAX data results’ from the PHP Ajax function but even that does not appear to be working. At the moment I get my test alerts…
alert('jquery step 1'); - Works OK
alert('jquery step 2'); - Works OK
alert('ajax result: '.response); - ** NOT DISPLAYED **
alert('jquery step 3'); - Works OK
I've created a custom plugin and custom js and php files as follows...
********* c4l-custom-functions.php ********
<?php
/**
* Plugin Name: C4L Custom Functions Plugin
* Description: This plugin contains C4l custom functions, scripts and css styles.
* Author: C4L
* Version: 1.0
*/
function c4l_custom_script_and_style_includer() {
wp_enqueue_script( 'c4l-js', plugins_url( 'js/c4l-custom-scripts.js' , __FILE__ ) );
wp_enqueue_style( 'c4l-css', plugins_url( 'css/c4l-custom-styles.css' , __FILE__ ) );
}
add_action( 'wp_enqueue_scripts', 'c4l_custom_script_and_style_includer' );
add_action( 'wp_ajax_wps_get_time', 'wps_get_time' );
add_action( 'wp_ajax_nopriv_wps_get_time', 'wps_get_time' );
function wps_get_time() {
// $format = $_POST['format'];
echo('This is AJAX data results');
//echo date($format);
die();
}
?>
********* c4l-custom-scripts.js ********
document.addEventListener("DOMContentLoaded", function(event) {
jQuery('#pulldown1').change(function(){
alert('jquery step 1');
var timeformat = 'U';
alert('jquery step 2');
jQuery.ajax({
type: "POST",
url: "admin-ajax.php",
data: { action: 'wps_get_time', format: timeformat },
success: function ( response ) {
alert('ajax result: '.response);
}
});
alert('jquery step 3');
});
});
Try changing the ajax function url with this:
ajaxurl = '<?php echo(admin_url('admin-ajax.php')); ?>';
I would like to pass a variable to a specific page. I found a simple example explaining how to use ajax with wordpress.
JavaScript:
jQuery(document).ready(function($) {
// We'll pass this variable to the PHP function example_ajax_request
var fruit = 'Banana';
// This does the ajax request
$.ajax({
url: ajaxurl,
data: {
'action':'example_ajax_request',
'fruit' : fruit
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
Piece of PHP to insert in functions.php
function example_ajax_request() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$fruit = $_REQUEST['fruit'];
// Let's take the data that was sent and do something with it
if ( $fruit == 'Banana' ) {
$fruit = 'Apple';
}
// Now we'll return it to the javascript function
// Anything outputted will be returned in the response
echo $fruit;
// If you're debugging, it might be useful to see what was sent in the $_REQUEST
// print_r($_REQUEST);
}
// Always die in functions echoing ajax content
die();
}
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
Unfortunately I cannot pass the variable. I inspected the code and I get this error:
Error: ajax_object is not defined
Do you maybe know another way to obtain the same result?
You are very near, but there is some little things missing…
What I mean in my comment, is that you need to use it this way using 'ajax-script' in both:
add_action('wp_enqueue_scripts', 'add_js_scripts');
add_js_scripts(){
wp_enqueue_script( 'ajax-script', get_template_directory_uri().'/js/script.js', array('jquery'), '1.0', true );
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
Changed $_REQUEST to $_POST:
function example_ajax_request() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_POST) ) {
$fruit = $_POST['fruit'];
// Let's take the data that was sent and do something with it
if ( $fruit == 'Banana' ) {
$fruit = 'Apple';
}
// Now we'll return it to the javascript function
// Anything outputted will be returned in the response
echo $fruit;
// If you're debugging, it might be useful to see what was sent in the $_POST
// print_r($_POST);
}
// Always die in functions echoing ajax content
die();
}
Added add_action( 'wp_ajax_nopriv_ … ):
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' ); // <= this one
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
For your jQuery script script.js file, there is 2 important missing little things:
jQuery(document).ready(function($) {
/* We'll pass this variable to the PHP function example_ajax_request */
var fruit = 'Banana';
/* This does the ajax request */
$.ajax({
url: ajax_object.ajaxurl, /* <====== missing here */
type : 'post', /* <========== and missing here */
data: {
'action':'example_ajax_request',
'fruit' : fruit
},
success:function(data) {
/* This outputs the result of the ajax request */
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
This should work now…
References:
Using AJAX With PHP on Your WordPress Site Without a Plugin
How to use Ajax with your WordPress Plugin or Theme?
You are using wp_localize_script wrong. In the PHP code, remove the wp_localize_script line.
Optionally you can (and should) add the following
// this line is for users who are not logged in
add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );
Everything is correct except you have to add
ajax_object.ajax_url rather than ajaxurl in url: parameter of $.ajax function as
jQuery(document).ready(function($) {
// We'll pass this variable to the PHP function example_ajax_request
var fruit = 'Banana';
// This does the ajax request
$.ajax({
url: **ajax_object.ajax_url**,
data: {
'action':'example_ajax_request',
'fruit' : fruit
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
copy and paste above script in place of your $.ajax function
If you want to see what is ajax_object.ajax_url then
alert it inisde your code and it will alert path to your admin ajax file
which is required for using ajax in wordpress
It is a Wordpress installation using Gravity Forms which I know pretty well, however what I am trying to do is get the value of a hidden input and use it in a PHP script to get more data about.
JS CODE: http://pastebin.com/5FFf4ESb
jQuery(function($){
$(document).bind('gform_post_render', function(event, form_id){
if (form_id == 1) {
var uploader = $("#gform_drag_drop_area_1_1");
var uploads = $("#gform_uploaded_files_1").val();
alert(uploads);
uploader.on("drop", function() {
$.ajax({
url: mp3_object.ajaxurl,
async: true,
type: "POST",
data: {
action : 'ajax_mp3',
files : uploads,
},
success: function(response) {
//results = jQuery.parseJSON(response);
alert(response);
}
});
});
}
});
});
PHP CODE: http://pastebin.com/H2Cd1Dfd
function enqueue_mp3_scripts_init($form, $is_ajax) {
if ( $is_ajax ) {
wp_enqueue_script( 'mp3-script', plugin_dir_url(__FILE__) . 'js/scripts.js', array('jquery'), 1.0 ); // jQuery will be included automatically
wp_localize_script( 'mp3-script', 'mp3_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); // setting ajaxurl
}
}
add_action('gform_enqueue_scripts', 'enqueue_mp3_scripts_init', 10, 2);
function ajax_mp3_func() {
if( isset($_POST['files']) ) {
echo $_POST['files'];
}
die(); // stop executing script
}
add_action( 'wp_ajax_ajax_mp3', 'ajax_mp3_func' ); // ajax for logged in users
add_action( 'wp_ajax_nopriv_ajax_mp3', 'ajax_mp3_func' ); // ajax for not logged in users
The issue I am having is that the file upload uses plupload AJAX request and it is performing asynchronously with my JS code so my code fires before the value of the hidden field var uploads is set and it returns empty before being sent via my AJAX request to the PHP File.
I don't know enough about AJAX to know how to isolate and run my AJAX request after the hidden value is set.
I'm trying to do a custom AJAX action on WordPress but it isn't working. I have the following form:
<form method='post' name='form-bid-<?php echo get_the_ID() ?>' class="bid-form">
<input type='submit' name='<?php echo get_the_ID()?>' value='Licitar' class='bidvalue'>
<?php wp_nonce_field('ajax-bid-nonce', $post->ID); ?>
</form>
The form is this way because it's generated inside a loop, one for every post on the site, therefore I use the post ID as the unique name for the input.
Then, I capture the form submit on a custom JavaScript file:
jQuery(document).ready(function($) {
// Perform AJAX bid on form submit
$('form.bid-form').on('submit', function(e) {
var action = 'ajaxbid';
var auction_id = e.target.name.substring('form-bid-'.length);
var security_container = "#".concat(auction_id);
var security = $(security_container).val();
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_bid_object.ajaxurl,
data: {
'action': action,
'id': auction_id,
'security': security
},
success: function(data) {
console.log(data);
}
});
e.preventDefault();
});
});
This part works, and it prints 0 on the console upon success.
Finally, I have a PHP file where I register the script and have the function I want to call upon the form submission:
function ajax_bid_init() {
wp_register_script('ajax-bid-script', get_template_directory_uri() .'/js/ajax-bid-script.js', array('jquery') );
wp_enqueue_script('ajax-bid-script');
wp_localize_script( 'ajax-bid-script', 'ajax_bid_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
// Enable the user with no privileges to run ajax_bid() in AJAX
add_action( 'wp_ajax_nopriv_ajaxbid', 'ajax_bid' );
}
add_action('init', 'ajax_bid_init');
function ajax_bid() {
// First check the nonce, if it fails the function will break
check_ajax_referer( 'ajax-bid-nonce', 'security');
echo json_encode(array('message'=>__('SUCCESS')));
die();
}
For now, all I wanted was the function to return that array and display it on console. However, the code never seems to run through here, and the AJAX response is always 0.
I have done a quite similar approach to both login and registration on the website and they both work. I've compared the 3 endless times and I cannot seem to find what I'm missing here.
Found the issue! I forgot to mention I was trying to do this with a logged user, so the problem was this line:
add_action( 'wp_ajax_nopriv_ajaxbid', 'ajax_bid' );
It should be this instead:
add_action( 'wp_ajax_ajaxbid', 'ajax_bid' );
I copied the first from my login and register forms, which made sense to be only available for non-logged users. The bids however are the exact opposite.
Just for future reference, you can register both (wp_ajax and wp_ajax_nopriv) for the same function if you want it to be executable for both logged and non-logged users.
I have searched the internet a lot for an answer to my question and have not found exactly what I was looking for. So the standard way, from what I have seen, to accomplish this is to use jQuery's submit and AJAX to send the data and redirect to another PHP page. However, I have multiple problems with this. First of all, AJAX. Regular AJAX does not work on Wordpress sites, from what I have seen. How do I get plain old regular AJAX to work? I have not seen a single good tutorial for this that is in plain English for Dummies. Second of all, the PHP redirect. I just want it to send to PHP already on the page. I just want data to go from my Javascript into my PHP already on the page. I don't need a redirect. So, my final question is, can those two problems be fixed in order to do it the traditional way? Or is there a better way to do it that circumvents these problems? I am a complete beginner, BTW- been doing web programming for less than five months. So please, for Dummies or Complete Idiot's language if you can. Here's the form I am submitting from:
<form method="post">
Search By File Name: <input type="text" name="searchterms" placeholder="search"></input>
<button type="submit" name="SearchSubmit">Display Results</button>
</form>
Here's the PHP I want to execute:
$submit=$_POST['SearchSubmit'];
$results=$_POST['searchterms'];
if(isset($submit))
{
//whole bunch of stuff, like sql queries and file generation
}
There are 3 part of code,
HTML where data want to show.
<div id="msg_alert"></div>
Jquery for ajax;
$('#msg_form').submit(function (event) {
event.preventDefault();
action = 'messaging_post';
user_id = $('#msg_form #user_id').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_auth_object.ajaxurl,
data: {
'action': action,
'user_id': user_id
},
success: function (data) { //alert(data.message);
if (data.log== true) {
$('#msg_alert').val(data.message);
}
else {
$('#msg_alert').val('There is an error');
}
}
});
});
Third is PHP:
add_action('init', 'ajax_review_loading');
function ajax_review_loading() {
wp_localize_script( 'ajax-auth-script', 'ajax_auth_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'redirecturl' => home_url(),
'loadingmessage' => __('Sending user info, please wait...')
));
add_action( 'wp_ajax_messaging_post', 'messaging_post' );
}
function messaging_post(){
/// Your work here.
echo json_encode(array('log'=>true, 'message'=> $htm));
die();
}
For working you must add wp_enqueue_script to ajax_review_loading function
add_action('init', 'ajax_review_loading');
function ajax_review_loading() {
wp_enqueue_script('ajax-auth-script', get_template_directory_uri() );
wp_localize_script( 'ajax-auth-script', 'ajax_auth_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'redirecturl' => home_url(),
'loadingmessage' => __('Sending user info, please wait...')
));
add_action( 'wp_ajax_messaging_post', 'messaging_post' );
}
function messaging_post(){
/// Your work here.
echo json_encode(array('log'=>true, 'message'=> $htm));
die();
}
You might need 2 php files, the one that generates the page that you are already seeing, let's call it "my_page.php", and the one that generates the data that you load in that first page without refreshing it, let's call it "livedata.php".
So for example if "my_page.php" generates the following html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
function refresh_data(start_at) {
$("#data_updates_go_here").empty(); // Clear previous contents of the div for refresh
$.getJSON("livedata.php?start_at=" + start_at,
function(json_returned) {
$.each(json_returned, function(key, value){
$("#data_updates_go_here").append(key + " = " + value + "<br />");
});
});
}
</script>
Data: <br/>
<div id="data_updates_go_here">
</div>
<input type=button onClick="refresh_data(1);" value="Refresh data at 1">
<input type=button onClick="refresh_data(3);" value="Refresh data at 3">
You can see that when you load "my_page.php", it won't display any data. inside of the div.
Now "livedata.php" on it's side will have to generate a json structure, as you can see above, it can receive parameters, so you can use them for instance, to limit a query to a database or for any other purposes that you need a parameter to be passed to your php. In the example, "livedata.php" should return a 'json' structure. For instance, your php code could be
<?php
header('Content-Type: application/json');
if ($_REQUEST['start_at'] == 1) {
echo json_encode(array('value1' => 'data1', 'value2' => 'data2'));
} else if ($_REQUEST['start_at'] == 3) {
echo json_encode(array('value3' => 'data3', 'value4' => 'data4'));
} else {
echo json_encode(array('value1' => 'data1', 'value2' => 'data2'));
}
?>
You can see how you can control the values refreshed by passing a different value for "start_at".