Wp-api 2 cookie authentication - javascript

So, I have a php page in wordpress (WP-Api 2):
<?php
/**
* Template Name: WP-Api
*/
add_action("wp_enqueue_scripts", "enqueue_");
function enqueue_() {
wp_localize_script( 'wp-api', 'wpApiSettings', array( 'root' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce( 'wp_rest' ) ) );
}
get_header(); ?>
<h1>oi</h1>
<script type="text/javascript">
jQuery.ajax( {
url: wpApiSettings.root + 'wp/v2/posts/1',
method: 'POST',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
data:{
'title' : 'Hello Moon'
}
} ).done( function ( response ) {
console.log( response );
} );
</script>
I want to run this example but the console says
Uncaught ReferenceError: wpApiSettings is not defined
What am I doing wrong? Thank you!

Take a look at the example here: https://codex.wordpress.org/Function_Reference/wp_localize_script
You need to wp_register_script and wp_enqueue_script or the JS variable will not be created.

Add the following code to functions.php and check if the user already logged in has the capabilities to POST (Create Products, Posting, Upload Media File, etc.)
/*Cookies Authentication*/
wp_localize_script( 'wp-api', 'wpApiSettings', array( 'root' => esc_url_raw( rest_url() ), 'nonce' => wp_create_nonce( 'wp_rest' ) ) );
wp_enqueue_script('wp-api');

Related

How to use function within class for ajax request

I've created a WordPress plugin for my custom Stripe Checkout integration.
I'm extending a WooCommerce class which then has the ajax initialisers and functions:
class WC_Stripe_Checkout_Gateway extends WC_Payment_Gateway {
public function __construct() {
add_action( 'wp_enqueue_scripts', array( $this, 'payment_scripts' ) );
add_action( 'wp_ajax_create_checkout_session', array( $this, 'create_checkout_session' ) );
add_action( 'wp_ajax_nopriv_create_checkout_session', array( $this, 'create_checkout_session' ) );
}
}
public function payment_scripts() {
// Load relevant JS on checkout page only.
if( is_checkout() ) {
// Enqueue Stripe JS
wp_enqueue_script( 'stripe_js', 'https://js.stripe.com/v3/' );
// and this is our custom JS in your plugin directory that works with token.js
wp_register_script( 'stripecheckout_js', plugins_url( '../scripts/stripe_checkout.js', __FILE__ ), array( 'jquery' ) );
wp_enqueue_script( 'stripecheckout_js' );
//
wp_localize_script( 'stripecheckout_js', 'stripejs_ajax', array(
// 'publishableKey' => $this->publishable_key
'url' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'stripe_checkout_session_nonce' ),
) );
}
}
I should be able to make an ajax request to create_checkout_session but I receive an error 400 in the console.
jQuery( function($) {
$("form.woocommerce-checkout").on('submit', function() {
$.ajax({
url: stripejs_ajax.url,
data: {
action: 'create_checkout_session',
nonce: stripejs_ajax.nonce
}
})
.done( function(response) {
if(response.type == 'success') {
console.log('level 1');
}
else {
console.log('level 2');
}
})
.fail( function(response) {
console.log(response);
});
});
});
Error:
https://example.test/wp/wp-admin/admin-ajax.php?action=create_checkout_session&nonce=5c6cf91687 400
Is it correct to have the function I want to ajax call within the class which then extends WC_Payment_Gateway, could this be causing any issues?

Wordpress ajax call in an admin menu page

I'm trying to use the data of an ajax call in my custom wordpress admin menu page.
The wp_localize_script is working fine:
wp_enqueue_script( 'ajax-function', plugin_dir_url( __FILE__ ) . 'JavaScript/ajax-function.js', array( 'jquery' ), $this->version,false );
wp_localize_script('ajax-function', 'WP_MY_AJAX',
array(
'security' => wp_create_nonce('wp-my-nonce'),
'success' => 'this is a success',
'error' => 'an error occurred'
)
);
If I click the button, my ajax fires and it has a status of 200.
jQuery(document).ready(function() {
let message = jQuery('.table-message');
jQuery('#ajax-test').on('click', function () {
let data = 111;
jQuery.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'get_edit_id',
security: WP_MY_AJAX.security,
edit_id: data
},
success: function ( response ) {
//Do something
},
error: function ( error ) {
jQuery('.error').remove();
message.after('<div class="error"><p>' + WP_ESCORT_AJAX.error + '</p></div>');
}
});
});
I end up in this function, which is located in my main plugin file.
function my_escort_get_edit_id() {
check_ajax_referer('wp-escort-nonce', 'security');
echo $_POST['edit_id']
die();
}
add_action('wp_ajax_get_edit_id', 'my_escort_get_edit_id');
add_action('wp_ajax_nopriv_get_edit_id', 'my_escort_get_edit_id');
However my goal is to work with the $_POST['edit_id'] in my admin menu page function:
function my_custom_admin_menu() {
add_menu_page(
__( 'My Menu', 'my-menu' ),
__( 'My Menu', 'my-menu' ),
'edit_posts',
'my-menu-slug',
'my_admin_page_function',
'dashicons-universal-access',
3 ) ;
}
add_action( 'admin_menu', 'my_custom_admin_menu' );
function my_admin_page_function() {
require_once __DIR__ . '/View/Admin/Partials/cover-menu-models.php';
requireModel('all');
$controller = new ModelController();
$modelQuery = $controller->modelQuery('all');
echo $controller->renderModelDataTables($modelQuery, 'all');
//I need the id here
}
How can I achive this?

Dynamically load WordPress post content into DIV using HTML select, query, and AJAX

I am trying to figure out how to use WordPress and AJAX to display content (title and ACF fields) from a single post object in a page template using a HTML <select> input with no button or submit. The single post would change each time a different option is selected. The page would need to display the most recent post by default in the div when the page is loaded.
I have included the code I have implemented so far.
My knowledge of AJAX is limited.
Any tips or suggestions?
functions.php
function theme_global_script() {
wp_enqueue_script( 'sendout-ajax', get_template_directory_uri().'/js/sendouts.js', array( 'jquery' ) );
wp_localize_script( 'sendout-ajax', 'frontEndAjax', array('ajaxurl' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce('ajax_nonce') ));
}
add_action( 'wp_enqueue_scripts', 'theme_global_script' );
add_action('wp_ajax_get_ajax_posts', 'get_sendout_posts');
add_action('wp_ajax_nopriv_get_ajax_posts', 'get_sendout_posts');
function get_sendout_posts() {
// Query Arguments
// Select unlimited published posts from category 101 and order by date
$args = array(
'post_status' => array('publish'),
'nopaging' => true,
'numberposts' => '-1',
'order' => 'DESC',
'orderby' => 'date',
'cat' => 101,
);
// The Query
$ajaxposts = new WP_Query( $args );
$response = '';
// The Query
// If query is has results, load the sendouts template part
if ( $ajaxposts->have_posts() ) {
while ( $ajaxposts->have_posts() ) {
$ajaxposts->the_post();
$response .= get_template_part( 'template-includes', 'sendouts' );
}
} else {
$response .= get_template_part( 'none' );
}
echo $response;
exit;
}
Sendout template part HTML
The $post->ID and $post->name would be returned from the WordPress query
<select id="" name="" class="sendout-select">
<option value="[$post->ID]">[$post-name]</option>
<option value="[$post->ID]">[$post-name]</option>
<option value="[$post->ID]">[$post-name]</option>
</select>
<div class="sendout-container">
<!-- Load Post object here -->
</div>
AJAX JavaScript
jQuery(document).ready(function($) {
$( ".sendout-select" ).change(function() {
$.ajax({
type: 'POST',
url: frontEndAjax.ajaxurl,
dataType: 'html',
data: {
action : 'get_sendout_posts'
},
success: function(response) {
console.log(response)
},
error: function(error) {
console.log(error)
}
});
});
});

(Wordpress / Ajax) ReferenceError: Can't find variable: ajaxobject

I'm working with Wordpress + Ajax and even using the proper hooks I get the error "ReferenceError: Can't find variable: ajaxobject". Of course there is some problem with my ajaxurl but I don't understand where since it seems well done to me. Can you help me?
In my functions.php
add_action( 'wp_enqueue_scripts', 'add_frontend_ajax_javascript_file', 11, 2 );
function add_frontend_ajax_javascript_file()
{
wp_localize_script( 'ajax-script', 'ajaxobject', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
my jQuery/AJAX file
var itemtitle = $('#itemtitle').val();
var itemdescription = $('#itemdescription').val();
jQuery.ajax({
method: 'post',
url : ajaxobject.ajaxurl, //Why???
dataType: "json",
data: {
'action':'update_portfolio_function',
'pid' : id,
'itemtitle' : itemtitle,
'itemdescription' : itemdescription,
},
success:function(data) {
// This outputs the result of the ajax request
alert("Coooool");
},
error: function(errorThrown){
console.log(errorThrown);
}
});
of course the update_portfolio_function looks like
add_action('wp_ajax_update_portfolio', 'update_portfolio_function' );
function update_portfolio_function(){
$id = $_REQUEST['pid'];
$title = $_REQUEST['itemtitle'];
$description = $_REQUEST['itemdescription'];
$attachment = array(
'ID' => $id,
'post_title' => $title,
'post_content' => $description
);
// now update main post body
wp_update_post( $attachment );
die();
}
Should I use init or no_priv?
You just need to use ajaxurl instead of ajaxobject.ajaxurl
like below
jQuery.ajax({
method: 'post',
url : ajaxurl,
dataType: "json",

jQuery does not hit the Ajax URL on Wordpress

I am trying to implement a poll plugin on wordpress. The jQuery onchange event is working very fine of the below script but doesn't call or display the ajax hit on network .
plugin index page
PHP :
function my_scripts_main() {
wp_enqueue_script(
'my_voter_script',
plugins_url( '/js/main.js' , __FILE__ ),
array( 'jquery' )
);
wp_localize_script( 'my_voter_script',
'myAjax',
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ),
'action'=>'my_poll_srt')
);
}
add_action( 'wp_enqueue_scripts', 'my_scripts_main' );
Plugin Short code Page :
add_action( 'wp_ajax_nopriv_my_poll_srt', 'my_poll_srt_callbck' );
add_action( 'wp_ajax_my_poll_srt', 'my_poll_srt_callbck' );
function my_poll_srt_callbck() {
global $wpdb;
$poll_id=$_POST['poll_id'];
$answer=$_POST['answer'];
$d=mktime(11, 14, 54, 8, 12, 2014);
$created= date("Y-m-d h:i:sa", $d);
/******* My Logic ****************/
echo json_encode(array('YES'=>$count_yes,
'NO'=>$count_no));
wp_die();
}
JS script :
jQuery(document).ready(function(){
jQuery("input[name=answer_srt]:radio").change(function (e) {
e.preventDefault();
// submit();
// $(this).closest("form").submit(function() {
// alert('Hello');
var poll_answer=$(this).val();
var poll_id=jQuery(this).closest("form").find('#poll_id_srt').val();
var vi=jQuery(this);
jQuery.ajax({
url: myAjax.ajaxurl,
type: 'POST',
data: {
action: myAjax.action,
answer:poll_answer,
poll_id:poll_id
},
// dataType: 'html',
success: function(response) {
var obj = JSON.parse(response);
// console.log(obj);
jQuery(vi).closest('form').find('#poll_sht').html('YES='+obj.YES+' NO='+obj.NO);
}
// });
});
});
});
In the code above there are no errors in console panel.
If I put alert() inside the script its working fine but its not hitting admin-ajax.php file. What to do now ? Where am I wrong please help me ?
Your action URL should contain query string of action.
e.g
The action URL is like this
http://localhost/wordpress/wp-admin/admin-ajax.php?action=my_poll_srt

Categories

Resources