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.
Related
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>
I just want to know if it is possible to execute a PHP post request with ajax by click on a form submit button that does not have any text input. Say i have a form
<form action="connecting.php" id="connect" method="post" enctype="multipart/form-data">
<input type="submit" name="userconnect" id="userconnect" value="connect">
</form>
And i want to execute this block of php code on submit button
connecting.php
<?php
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['userconnect']))
{
$my_id = htmlspecialchars($_SESSION['log_id'], ENT_QUOTES, 'UTF-8');
$user_id = (int) htmlspecialchars($_SESSION['userid'], ENT_QUOTES, 'UTF-8');
$rand_num = rand();
$hsql =<<<EOF
SELECT COUNT(hash) as count FROM connect WHERE (user_one = '$my_id' AND user_two = '$user_id') OR (user_two = '$my_id' AND user_one = '$user_id');
EOF;
$hret = $db->querySingle($hsql);
if ($hret == 1)
{
echo "<script>alert('You are already connected to this user')</script>";
}
else
{
$usql = $db->prepare("INSERT INTO connect (user_one, user_two, hash) VALUES (:my_id, :user_id, :rand_num)");
$usql->bindValue(':my_id', $my_id, SQLITE3_INTEGER);
$usql->bindValue(':user_id', $user_id, SQLITE3_INTEGER);
$usql->bindValue(':rand_num', $rand_num, SQLITE3_TEXT);
$uret = $usql->execute();
if (!$uret)
{
echo "Error connecting";
}
else
{
echo "Connection Sucessful";
}
}
}
This is the ajax request i am trying to use
$("#connect").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "connecting.php",
data: $(this).serializeArray(), //the data is an issue cause of no text input in for
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(response) {
}
});
});
This doesn't work because there is no data in the form for ajax to send but all data are in the PHP file. How do i execute the php file with ajax. Is there any way?
You dont have to send a POST request to a PHP script in order for it to execute. You can send a normal GET to a URL that executes a PHP script and send you back the JSON data you are looking for. That way, you dont have to send data with the post request and you can still run your PHP script.
Edit*
Another thing you can do is add a hidden ID field or some random text and send that with the POST as data. You dont have to do anything with it, it could just be a time stamp, but it will send the POST request. This is of course overhead and not my kind of programming, but an option nonetheless.
Yes it is possible.... you need to harness a click event...
for example if you had a div element like so:
<div id='mybutton'>click me</div>
then you could use code like this to do literally whatever you want when the button is clicked.:
$('#mybutton').on('click',function(){
$.post...
});
BONUS INFO:
You could also hijack the form submit event like so:
$('#form#myform').on('submit',function(e){
e.preventDefault(); //stop before page is reloaded with post headers
$.post...
});
You don't actually need a form event though, you can just $.get to a php url and return the html or json it generates. just check out the jquery documentation on $.get()
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 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".