Hello everyone I am trying to use ajax in my custom plugin for wordpress but got an issue in my console showing 400 bad request in admin-ajax
JS scripts
public static function register_script(){
wp_enqueue_script('ajaxscript', substr(plugin_dir_url(__FILE__), 0, -10) . '/assets/js/register-post.js', array( 'jquery', 'json2' ), '1.0.0', true );
wp_localize_script( 'ajaxscript', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ),'nonce' => wp_create_nonce('ajaxnonce') ) );
}
Ajax
function signup(){
// alert("working");
jQuery('#registration').on('submit', function(e) {
var data = jQuery("#registration").serialize();
e.preventDefault();
// e.stopPropagation(); // only neccessary if something above is listening to the (default-)event too
jQuery.ajax({
type: 'POST',
url: my_ajax_object.ajax_url,
processData: false,
data: {
action: 'register_ajax_request&nonce='+ my_ajax_object.nonce,
data: data
},
dataType: 'json',
success: function(response) {
if(response.success === true) {
// jQuery("#vote_counter").html(response.vote_count)
}else {
// alert("Your vote could not be added")
}
}
});
});
}
Registration Function
<?php
add_action('wp_ajax_register_ajax_request', 'ajax_handle_request');
add_action('wp_ajax_nopriv_register_ajax_request', 'ajax_handle_request');
function ajax_handle_request(){
if (isset($_POST['register_trigger'])){
$nonce = $_POST['nonce'];
print_r($nonce);
exit();
}
}
Location of the registration.php is plugindirectory/inc/pages/. This is not a function.php like the wordpress theme.
Sorry I just forgot to include a php file that the action is looking for.
Related
add_action( 'wp_footer', function () { ?>
<script type='text/javascript' id='ajax'>
const ajaxUrl = "<?php echo admin_url('admin-ajax.php'); ?>";
async function httpRequest(url = '', data = {}, method = 'POST') {
const response = await fetch(url, { method: method,
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Cache-Control': 'no-cache',
},
body: new URLSearchParams(data)
});
return response.text();
}
document.querySelector('#roll-title-btn').addEventListener('click', async function() {
const searchTerm = document.getElementById('roll-title');
if (searchTerm.value.trim().length) {
const result = await httpRequest(ajaxUrl, { action: 'filter_ajax', 'roll-title': searchTerm.value });
console.log(result);
}
})
</script>
<?php } );
add_action( 'wp_ajax_nopriv_filter_ajax', 'filter_ajax' );
add_action( 'wp_ajax_filter_ajax', 'filter_ajax' );
function filter_ajax() {
echo "TESTING";
wp_die();
}
Whenever I am trying to send an HTTP request it is throwing 400 bad requests and prints 0 as result. Trying to implement a filter plugin but the above code snippets aren't working at all. I have tried multiple solutions from StackOverflow but none worked.
Here I am sharing my working code which I was developed by today so you can check here.
//First I enqueue script using action in function.php file
wp_enqueue_script( 'custom-js', get_stylesheet_directory_uri().'/assets/js/custom.js', array(), '1.0.0', 'true' );
//Then I localize custom js for admin ajax
wp_localize_script( 'custom-js', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
//I choose action and javascript object "my_ajax_object"
//Now I create custom.js as per mentioned above path
$(function(){
$('#capture').click(function(){
//capture is button id.
//here is the ajax call
var value = '123';
jQuery.ajax({
type: "post",
dataType: "HTML",
url: my_ajax_object.ajax_url,
data : {action: "my_ajax_object","value":value},
success: function(msg){
console.log(msg);
}
});
});
});
//Now I wrote ajax function
add_action( 'wp_ajax_nopriv_my_ajax_object', 'my_ajax_object' );
add_action( 'wp_ajax_my_ajax_object', 'my_ajax_object' );
function my_ajax_object()
{
$value = $_POST['value'];
$response = '<p>value is '.$value.'<p>';
return $response;
wp_die();
}
I want the user to be able to upload html files using ajax from my custom editor block. Wordpress requires all ajax go through admin-ajax.php. My js code is in an external file registered and enqueued in Wordpress. Here is a Wordpress Codex instruction from https://codex.wordpress.org/AJAX_in_Plugins:
Separate JavaScript File
The same example as the previous one, except with the JavaScript on a separate external file we'll call js/my_query.js. The examples are relative to a plugin folder.
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);
});
});
With external JavaScript files, we must first wp_enqueue_script() so they are included on the page. Additionally, we must use wp_localize_script() to pass values into JavaScript object properties, since PHP cannot directly echo values into our JavaScript file. The handler function is the same as the previous example.
<?php
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {
if( 'index.php' != $hook ) {
// Only applies to dashboard panel
return;
}
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 ) );
}
Here is my PHP:
if (isset ( $_POST["test"] ) ){
echo 'test working';
}
if ( isset ( $_FILES["renee_wip_upload"] ) ){
echo 'test2';
}
And here is my js function:
function fileSubmit(e) {
e.preventDefault();
if(typeof(files2) !== "undefined"){
//ajax using post() works fine which means the php side is OK
renee_wip_ajax_object.braft_wip_upload_value = 'test';
var data2 = {
'action': 'renee_wip_block_ajax',
'test': renee_wip_ajax_object.braft_wip_upload_value
};
jQuery.post(renee_wip_ajax_object.ajax_url, data2, function(response) {
console.log('response test: ', response);
}).fail(function(response) {
console.log('Error: ' + response.responseText);
});
//It seems $_FILES never gets populated
data = new FormData();
data.append('action', 'renee_wip_block_ajax');
for (var i = 0; i < files2.length; i++) {
var file = files2[i];
data.append('renee_wip_upload[]', file, file.name);
}
jQuery.ajax({
success: function(data){
console.log('data: ', data);
},
error: function(err){
throw err;
},
type: "post",
url: renee_wip_ajax_object.ajax_url,
data: data,
dataType: "html",
enctype: 'multipart/form-data',
processData: false,
contentType: false,
}).done(function(msg){
console.log('done: ', msg);
}).fail(function(err){
throw err;
});
}
}
Man, I am blind as hell. It was: data.append('braft_wip_upload[]', file, file.name); but should be: data.append('renee_wip_upload[]', file, file.name); I even corrected the mistake in edit, but forgot to do it in my code.
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.
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 ;) )
I want to send an AJAX request in WordPress which tracks my clicks. So far, I have added this in my functions file:
add_action('init', 'my_script_enqueuer');
function my_script_enqueuer() {
wp_register_script("history_script", get_template_directory_uri() . '/js/history_script.js', array('jquery'));
wp_localize_script('history_script', 'myAjax', array('ajaxurl' => get_template_directory_uri().'/functions.php'));
wp_enqueue_script('jquery');
wp_enqueue_script('history_script');
}
add_action("wp_ajax_history_trace", "history_trace");
function history_trace() {
echo 'fasfasgasgas'; die;
}
And this in my js file :
jQuery(document).ready( function() {
jQuery("#searchsubmit").click( function() {
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "history_trace"},
success: function(response) {
if(response.type == "success") {
alert('success')
}
else {
alert("false")
}
}
})
})
})
But in my console, the request appears in red, and there is no response. Please Help!
In WordPress, use the following url to process AJAX requests:
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) )
It's also important to localize a script after it has been enqueued.