How to load wp ajax for not logged users? - php

I understand I should be using wp_ajax_nopriv as per the doc says
but I am not sure how tho.
On the front end I do:
var ajaxscript = { ajax_url : '<?php echo admin_url("admin-ajax.php"); ?>' };
$.ajax({
url: ajaxscript,
type: 'post',
dataType: 'json',
data: { action: 'data_fetch', dates: datesSearch },
success: function(data) {
...
}
});
I know I could define the url in function like:
function myAjaxUrl() {
echo '<script type="text/javascript">
var ajaxurl = "' . admin_url('admin-ajax.php') . '";
</script>';
}
add_action('wp_head', 'myAjaxUrl');
And that would make the ajax call on the front end like:
$.ajax({
url: ajaxurl...
But how would I use the wp_ajax_nopriv in order to be able to access wp-ajax for not logged in users?

All you need to do is just register your function to a hook named as wp_ajax_nopriv_{your_function_name}
So, for your case, add_action( 'wp_ajax_nopriv_data_fetch', 'data_fetch' ); should do the trick.
Registering an ajax function in WordPress:
1. Registering an ajax function in WordPress: You can add this in the theme functions.php file.
// Simple Ajax function
add_action( 'wp_ajax_nopriv_simple_ajax_func', 'simple_ajax_func' );
add_action( 'wp_ajax_simple_ajax_func', 'simple_ajax_func' );
function simple_ajax_func() {
echo json_encode(array('success' => true));
wp_die();
}
2. Calling that ajax function from JavaScript:
var ajax_url = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
jQuery.ajax({
url : ajax_url,
type : 'post',
data : {
action : "simple_ajax_func",
},
success : function( response ) {
console.log('Success');
}
});

you misunderstand the wp_ajax action.
You must create a PHP function inside your theme using the wp_ajax filter.
add_action( 'wp_ajax_foobar', 'my_ajax_foobar_handler' );
add_action( 'wp_ajax_nopriv_foobar', 'my_ajax_foobar_handler' );
// This is the function that you will fire when your ajax code hits the admin_url('admin-ajax.php')
function my_ajax_foobar_handler() {
// Make your response and echo it.
// Don't forget to stop execution afterward.
wp_die();
}
So, for the WP admin ajax understand that need to fire this function, you must pass it inside your ajax request.
//Note that the action here is what cames after the wp_ajax PHP function
var my_php_ajax_action_name = 'foobar'
$.ajax({
url: ajaxurl,
type: 'post',
dataType: 'json',
data: { action: my_php_ajax_action_name, dates: datesSearch },
success: function(data) {
// ...
}
});

Related

Can not pass variable from jquery to php

I want to pass a variable from jquery to PHP on the same page (I am using WordPress).
I tried using using ajax post like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("li.year-item a").click(function(){
$post = $(this);
$.ajax({
type : "POST",
url: "https://example.com/exhibition/",
data: {yearValue: $($post).attr("value")},
success: function (data) {
console.log(data);
}
})
});
});
</script>
and I get the post variable below the script tag:
<?php var_dump($_POST['yearValue']); ?>
but the var_dump result is null..
I have no idea.. anyone can help me? thanks in advance :)
In Wordpress you should use the built in Ajax mechanism.
$.ajax({
type : "POST",
url: "https://your-site.com/wp-admin/admin-ajax.php",
data: {
action: 'retrieve_yearvalue',
yearValue: $($post).attr("value"),
test: 'Test is ok'
},
success: function (data) {
console.log(data);
}
})
On PHP-Side:
add_action( 'wp_ajax_retrieve_yearvalue', 'my_year_retrieve_function' );
add_action( 'wp_ajax_nopriv_retrieve_yearvalue', 'my_year_retrieve_function' );
function my_year_retrieve_function() {
$yearValue = $_REQUEST['yearValue'];
$test = $_REQUEST['test'];
$response = array(
'recieved_year' => $yearValue,
'test_data' => $test
);
wp_send_json( $response );
}

POST /wp-admin/admin-ajax.php 400 (bad request)

I have written a jQuery function using jsPDF to convert a form to PDF, I have then added an ajax command with the intention of saving the generated PDF to the server.
However, when I click submit, the page appears to be completing an action. but, when I look at console I see:
POST website.com/wp-admin/admin-ajax.php 400 (bad request)
and I cannot figure out where my code has went wrong.
I have registered my JS and used wp_localize in functions.php:
function ASAP_scripts() {
wp_register_script('js-pod', get_stylesheet_directory_uri() . '/js/POD.js', array('jquery'),'1.1', true);
wp_enqueue_script('js-pod');
wp_localize_script( 'js-pod', 'jspod',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'ASAP_scripts' );
I have also added my ajax commands again in functions.php
add_action( 'wp_ajax_my_ajax_request', 'so56917978_upload_callback' );
add_action( 'wp_ajax_nopriv_my_ajax_request', 'so56917978_upload_callback' );
function so56917978_upload_callback() {
if ( ! empty( $_POST['data'] ) ) {
$data = base64_decode($_POST['data']);
file_put_contents( "get_stylesheet_directory_uri() . '/POD/pod.pdf' ", $data );
echo "success";
} else {
echo "No Data Sent";
}
die;
}
My jQuery:
function sendToServer() {
html2canvas(document.getElementById("product_sheet"), {
onrendered: function(canvas)
{
console.log("#submit clicked");
var img = canvas.toDataURL("image/png");
var doc = new jsPDF('p', 'pt', 'a4');
doc.addImage(img, 'JPEG',20,20);
var file = doc.output('blob');
var pdf = new FormData(); // To carry on your data
pdf.append('mypdf',file);
$.ajax({
url: '/wp-admin/admin-ajax.php', //here is also a problem, depends on your
data: {
action: 'so56917978_upload', // Action name.
data: pdf,
},
dataType: 'text',
processData: false,
contentType: false,
type: 'POST',
}).done(function(data){
console.log(data);
});
}
});
}
Any help in solving this would be great. I have seen similar questions on here but I feel as though I have covered all the bases which they discuss and genuinely cannot see my issue
Update...
Update...
I have changed MY JS slightly, it seems to work better and more as expected, however, I am still getting `no data sent. So the ajax request seems to be working. but, it appears that there may be something in the PHP which is stopping it from completing?
JS
function sendToServer() {
html2canvas(document.getElementById("product_sheet"), {
onrendered: function(canvas)
{
console.log("#pdfsubmit clicked");
function html() {
var img = canvas.toDataURL("image/png");
var doc = new jsPDF('p', 'pt', 'a4' );
doc.addImage(img, 'JPEG', 20, 20);
var pdf = doc.output('blob');
$.ajax({
url: jspod.ajax_url,
type: 'post',
async: false,
contentType: 'application/json; charset=utf-8',
data:{
data: pdf
action:'so56917978_upload'
},
dataType: 'json'
});
}
});
}
}
PHP:
add_action( 'wp_ajax_so56917978_upload', 'so56917978_upload' );
add_action( 'wp_ajax_nopriv_so56917978_upload', 'so56917978_upload' );
function so56917978_upload() {
if ( ! empty( $_POST['action'] ) ) {
$data = base64_decode($_POST['action']);
file_put_contents( get_template_directory() . '/POD/pod.pdf' , $data );
echo "success";
} else {
echo "No Data Sent";
}
die();
}
You have few errors in the code.
In the JS code, url needs to be jspod.ajax_url. Also, the action needs to be my_ajax_request.
Not sure why you have double quotes in file_put_contents function. Also you might want to use get_template_directory function to get the path rather than URI?
Hope it helps.
just change you action hooks with the name which you have used in ajax request action: 'so56917978_upload'
add_action( 'wp_ajax_so56917978_upload', 'so56917978_upload' );
add_action( 'wp_ajax_nopriv_so56917978_upload', 'so56917978_upload' );
also it will be good if you use localize variable instead of hard coding the url in ajax url: '/wp-admin/admin-ajax.php' although it has nothing to do with your problem but its good practice.
EDIT -
you also need to append action in FormData and then in ajax you need to pass that pdf object in data object so basically your code will look like this
pdf.append('action', 'so56917978_upload');
$.ajax({
url: jspod.ajax_url, //here is also a problem, depends on your
data: pdf,
dataType: 'text',
processData: false,
contentType: false,
type: 'POST',
}).done(function (data) {
console.log(data);
});
where pdf.append('action', 'so56917978_upload'); will append the action in your FormData object.
data: pdf, and this field in ajax will hold you pdf data object.

Wordpress make Ajax call to my theme

This is my situation: I have a slide, like the image below, that needs to be responsive. This slide was created from scratch and its working fine, however it's not responsive.
In order to be responsive I need to know the width of the screen of the user so instead of showing 4 slides, I show 3, 2 and 1 (if its a phone).
With that said, I need my slider to be loaded through ajax and I will pass through params the user screen width.
My theme folder is structured this way:
wp-contents/themes/my-theme
...functions.php
...header.php
...footer.php
...index.php
...single.php
I need to make a Ajax call to functions.php to a function that I have created. So I added the following:
add_action('wp_ajax_posts_list', 'my_ajax_posts_list_handler');
function my_ajax_posts_list_handler()
{
echo 'hello, width: ' . $_POST['width'];
wp_die();
}
In the footer.php file I added some testing javascript code:
$(function()
{
var width = $(window).width();
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>'; // Dunno what is this..
$.ajax(
{
url: ajaxurl,
data:
{
action: 'wp_ajax_posts_list',
width: width
},
type: 'GET',
success: function(response)
{
console.log(response);
}
});
});
My problems:
The URL being executed is this http://localhost/wordpress/wp-admin/admin-ajax.php?action=wp_ajax_posts_list
The URL response code is 400
The URL responde value is '0'
The action is actually called post_list. wp_ajax_ is just a prefix. You also should add the same action with prefix wp_ajax_nopriv_ otherwise it wil not work when you are logged out. I also see you do type: 'GET' in your javascript but use $_POST in your PHP. Do one of the two.
add_action('wp_ajax_posts_list', 'my_ajax_posts_list_handler');
add_action('wp_ajax_nopriv_posts_list', 'my_ajax_posts_list_handler');
function my_ajax_posts_list_handler()
{
echo 'hello, width: ' . $_POST['width'];
wp_die();
}
Here the JS:
<script>
$( function () {
var width = $( window ).width();
// var ajaxurl = "http://localhost/wordpress/wp-admin/admin-ajax.php"
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
$.ajax( {
url: ajaxurl,
data: {
action: 'posts_list',
width: width
},
type: 'POST',
success: function ( response ) {
console.log( response );
}
} );
} );
</script>

Success not being returned from ajax post

AJAX Post is not returning success call in wordpress. I have the following code and I can get to the first dialog box in testing, but no mater what I do its not getting to the second. It's not finding the function in functions.php even though I have it declared.
jQuery(document).ready(function(){
jQuery("#send_btn").click(function(){
var datastring = $("#redemmpointsForm").serialize();
var points = $('#points').val();
var comments = $('#comments').val();
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {"action": "redeempoints", "points":points},
success: function(response) {
if(response.type == "success") {
alert('do i get here');
}
else {
// Do something else
}
}
});
});
}); //Modal event Ends
functions.php file
wp_localize_script( 'inkthemes', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));
function functionRedeempoints() {
die();
return true;
}
add_action("wp_ajax_functionRedeempoints", "functionRedeempoints");
add_action("wp_ajax_nopriv_functionRedeempoints", "functionRedeempoints");
Ok so i treid the following
jQuery(document).ready(function(){
jQuery("#send_btn").click(function(){
var points = jQuery('#points').val();
var comments = jQuery('#comments').val();
var allData = {
action: 'functionRedeempoints',
points: points,
comments:comments
}
var data = JSON.stringify(allData);
alert( data);
jQuery.ajax({
type : "post",
dataType : 'json',
url : myAjax.ajaxurl,
data : data,
success: function(response) {
if(response.success) {
alert('do i get here');
}
else {
// Do something else
}
}
});
});
}); //Modal event Ends
And iN MY FUCNTIONS php Its like its not fidning the php function.
wp_localize_script( 'inkthemes', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php')));
function functionRedeempoints() {
wp_send_json_success(true);
}
add_action("wp_ajax_redeempoints", "functionRedeempoints");
add_action("wp_ajax_nopriv_redeempoints", "functionRedeempoints");
The problem is that your function functionRedeempoints does not return anything that the ajax call can handle.
It just dies even before the return statement.
Also a return by the PHP end will never actually be interpreted by the JS. JS can only read from the http request, so you need to actually write to it by an echo statement.
Wordpress provides a convenient way of handling this for you:
What you need would be something like:
function functionRedeempoints() {
wp_send_json_success(true);
}
This already takes care of stopping execution and properly JSON encoding your response.
Also the correct response handling on the JS side is a little different than in your example code.
You can find the details on this here:
https://codex.wordpress.org/Function_Reference/wp_send_json_success
But what it boils down to is that the success is encoded in the result.success property of the response.
Hence you want your check to be
if(response.success)
instead of if(response.type == "success")
With these changes your example should work though :)
Working example ( in plugin form) based on your code:
Put this in hello.php in the plugins folder
<?php
/*
Plugin Name: Ajax demo
*/
function test_load_js() {
wp_register_script( 'ajax_demo', plugins_url( 'hello.js' ), array( 'jquery' ) );
wp_localize_script( 'ajax_demo', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'ajax_demo' );
}
function functionRedeempoints() {
wp_send_json_success( true );
}
add_action( "wp_ajax_functionRedeempoints", "functionRedeempoints" );
add_action( "wp_ajax_nopriv_functionRedeempoints", "functionRedeempoints" );
add_action( "init", "test_load_js" );
if ( ! defined( 'DOING_AJAX' ) ) {
echo '<input type=button value="send" id="send_btn">';
}
Put this in hello.js in the plugins folder
jQuery(document).ready(function () {
jQuery("#send_btn").click(function () {
var points = jQuery('#points').val();
var comments = jQuery('#comments').val();
var data = {
action: 'functionRedeempoints',
points: points,
comments: comments
};
alert(JSON.stringify(data));
jQuery.ajax({
type: "post",
dataType: 'json',
url: MyAjax.ajaxurl,
data: data,
success: function (response) {
if (response.success) {
alert('do i get here');
}
else {
// Do something else
}
}
});
});
});
Hope this helps you to get a start here, works just fine when you click the button that should appear on the upper left of your admin screen ( zoom in ;) )

AJAX (admin_url('admin-ajax.php');?action=) Not Found

So for my AJAX tabs I have the following script:
<script>
jQuery(document).ready(function() {
jQuery('.royal_private_menu a').click(function(e) {
e.preventDefault();
var tab_id = jQuery('this').attr('id');
jQuery.ajax({
type: "GET",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'my_tab_menu', id: tab_id}),
success: function(data){
jQuery('#private_menu_'+tab_id).html(data);
},
error: function(data)
{
alert("Error!");
return false;
}
});
});
});
</script>
I got following error with url: "wp-admin/admin-ajax.php" and the error is example.com/wp-admin/admin-ajax.php?action=my_tab_menu 404 Not found.
Then I changed it to the following and got the same error: url: "admin_url('admin-ajax.php')" then, example.com/admin_url('admin-ajax.php');?action=my_tab_menu 404 Not found.
What is going on and what am I doing wrong?
Thanks
EDIT
Here is my files:
So I feel like I am really close to getting Ajax working but I am getting an error:
Here is php:
<div class="royal_private_menu">
Items
Received Order
My orders
Points
Setting
</div>
<div id="private_menu"> <!--Default page -->
<?php get_template_part('page-parts/03_private_items'); ?>
</div>
<div id="private_menu_received_order_id"> </div>
<div id="private_menu_my_orders_id"> </div>
<div id="private_menu_points_id"> </div>
<div id="private_menu_setting_id"> </div>
<script>
jQuery(document).ready(function() {
jQuery('.royal_private_menu a').click(function(e) {
e.preventDefault();
var tab_id = jQuery('this').attr('id');
jQuery.ajax({
type: "GET",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
dataType: 'html',
data: ({ action: 'my_tab_menu', id: tab_id}),
success: function(data){
jQuery('#private_menu_'+tab_id).html(data);
},
error: function(data)
{
alert("Error!");
return false;
}
});
});
});
</script>
And in my function.php:
function my_tab_menu() {
$template_part_path = 'page-parts/03_private_' . $_GET['id'];
get_template_part($template_part_path);
}
add_action('wp_ajax_my_tab_menu', 'my_tab_menu');
add_action('wp_ajax_nopriv_my_tab_menu', 'my_tab_menu');
And here is my file names:
03_private_items.php
03_private_my_orders.php
03_private_points_id.php
03_private_received_order_id.php
03_private_setting_id.php
EDIT 2
I changed the success to alert("Success!"); and I got the Success alert. So everything is working except it is not fetching any data from other php files. What am I missing?
EDIT 3
With console.log(data);, this is the script that I see in the console:
jQuery(document).ready(function() {
jQuery('.royal_private_menu a').click(function(e) {
e.preventDefault();
var tab_id = jQuery('this').attr('id');
jQuery.ajax({
type: "GET",
url: "http://example.com/wp-admin/admin-ajax.php",
dataType: 'html',
data: ({ action: 'royal_private_tab', id: tab_id}),
success: function(data){
jQuery('#private_menu_'+tab_id).html(data);
console.log(data);
},
error: function(data)
{
alert("Error!");
return false;
}
});
});
});
Then I changed it to the following and got the same error: url: "admin_url('admin-ajax.php')" then, example.com/admin_url('admin-ajax.php');?action=my_tab_menu 404 Not found.
If the URL contains the literal string admin_url('admin-ajax.php'); then that means you PHP isn't being parsed.
Try:
url: "<?php echo admin_url('admin-ajax.php'); ?>",
You can also use wp_localize_script to set the ajax URL when you enqueue a script:
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 ) );
https://codex.wordpress.org/AJAX_in_Plugins#Separate_Javascript_File
In this case you would set the URL like this:
url: ajax_object.ajax_url,
The advantage of doing it this way is that you don't have to inline your javascript; you can just enqueue a JS file like you normally would.
From the comments:
So, when I went to example.com/wp-admin/admin-ajax.php I get "0" on a blank page. And that is exactly what is shown on the console on the ajax tab page. Is it normal?
Getting a 0 result either means your hook is not attached to the action or your hook generates no output and fails to exit.
In your JS, you're setting your action like this:
action: 'royal_private_tab'
In your PHP your declaring your hooks like this:
add_action('wp_ajax_my_tab_menu', 'my_tab_menu');
add_action('wp_ajax_nopriv_my_tab_menu', 'my_tab_menu');
You need to either use royal_private_tab or my_tab_menu in both places, ex:
add_action('wp_ajax_royal_private_tab', 'my_tab_menu');
add_action('wp_ajax_nopriv_royal_private_tab', 'my_tab_menu');
Also, you should exit at the end of your hook:
function my_tab_menu() {
$template_part_path = 'page-parts/03_private_' . $_GET['id'];
get_template_part($template_part_path);
exit;
}

Categories