While sending post request using ajax it is showing error - ajax

I am using this code for sending ajax request but it is showing 400 Bad request error. anyone please tell me the error in this. i am totally stucked.
Thanks.
function bulk_setup_post_type()
{
wp_enqueue_style( 'customstyle', plugins_url( 'admin/css/custom.css' , __FILE__ ) );
wp_enqueue_script( 'customjs', plugins_url( 'admin/js/custom.js' , __FILE__ ) );
wp_localize_script('customjs', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));
}
add_action('wp_register_scripts', 'bulk_setup_post_type');
add_action('wp_ajax_extract_upload_data', 'extract_upload_data');
add_action('wp_ajax_nopriv_extract_upload_data', 'extract_upload_data');
function abc(file){
if(file!='')
{
jQuery.ajax({
url : ajax_object.ajax_url,
type : 'POST',
data : {
action : 'extract_upload_data',
path : file,
},
success : function( response ) {
//console.log(response);
alert(response);
}
});
}
else{ alert('File ' + file + 'not found.');}
}

I believe your URL contains no domain name

Related

How to get update ACF fields from AJAX form data

I can send the data to admin-ajax.php and see that the data exists via my dev tools, however, I cannot seem to be able to take that data and update an ACF field, or perhaps my function to do that is not running.
Here is my PHP:
// define the actions for the two hooks created, first for logged in users and the next for logged out users
add_action( 'wp_ajax_add_dog_to_favorites', 'add_dog_to_favorites' );
add_action( 'wp_ajax_nopriv_add_dog_to_favorites', 'login_to_add_to_favorites' );
// define the function to be fired for logged in users
function add_dog_to_favorites() {
// nonce check for an extra layer of security, the function will exit if it fails
if (!wp_verify_nonce( $_REQUEST['nonce'], 'add_dog_to_favorites_nonce' )) {
exit('Woof Woof Woof');
}
// Get the post_id and user_id value from the form and update the ACF form "test_field".
$post_id = $_REQUEST["post_id"];
$userID = $_REQUEST('user_id');
$current_field = get_field('test_field', $userID);
update_field('test_field', $post_id, $userID);
if ($current_field === false) {
$result['type'] = 'error';
} else {
$result['type'] = 'success';
}
// Check if action was fired via Ajax call. If yes, JS code will be triggered, else the user is redirected to the post page
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
} else {
header("Location: " . $_SERVER['HTTP_REFERER']);
}
// don't forget to end your scripts with a die() function - very important
die();
}
// define the function to be fired for logged out users
function login_to_add_to_favorites() {
echo 'You must log in to like';
die();
}
// used here only for enabling syntax highlighting. Leave this out if it's already included in your plugin file.
// Fires after WordPress has finished loading, but before any headers are sent.
add_action( 'init', 'enqueue_add_dog_to_favorites_script' );
function enqueue_add_dog_to_favorites_script() {
// Register the JS file with a unique handle, file location, and an array of dependencies
wp_register_script( 'add_favorites_script', plugin_dir_url( __FILE__ ) . 'add_favorites_script.js', array('jquery') );
// localize the script to your domain name, so that you can reference the url to admin-ajax.php file easily
wp_localize_script( 'add_favorites_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
// enqueue jQuery library and the script you registered above
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'add_favorites_script' );
}
and my JS:
jQuery(document).ready( function() {
jQuery(".not-favorite").click( function(e) {
e.preventDefault();
post_id = jQuery(this).attr("data-post_id");
nonce = jQuery(this).attr("data-nonce");
user_id = jQuery(this).attr("data-user_id");
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "add_dog_to_favorites", post_id : post_id, nonce: nonce, user_id : user_id},
success: function(response) {
if(response.type == "success") {
console.log('success!');
}
else {
alert("Your like could not be added");
}
}
});
});
});
I have a console.log('success!'); line that should trigger if successful, but it is not triggering. The failure alert is also not triggering, which leads me to believe the function is not running at all? I feel like it's pretty close to working, but just can't get there.
Any help would be greatly appreciated!
Update: Ok. I found that the function is actually exiting because of the nonce verification:
if (!wp_verify_nonce( $_REQUEST['nonce'], 'add_dog_to_favorites_nonce' )) {
exit('Woof Woof Woof');
}
I have tried commenting this block of code out to see what would happen and I get a critical error.
Update: Fixed an error in my code that allows it to work without the nonce check.
$userID = $_REQUEST('user_id'); needs to be $userID = $_REQUEST['user_id'];
I still will need to get the nonce check working, but progress is being made. If anyone knows why that is not working, that would wrap this up!

Saving blob image in laravel's controller

In my Laravel 5/vuejs 2.6 I upload an image with the vue-upload-component and am sending a requested image blob
I try to save it with the controller code like :
if ( !empty($requestData['avatar_filename']) and !empty($requestData['avatar_blob']) ) {
$dest_image = 'public/' . Customer::getUserAvatarPath($newCustomer->id, $requestData['avatar_filename']);
$requestData['avatar_blob']= str_replace('blob:','',$requestData['avatar_blob']);
Storage::disk('local')->put($dest_image, file_get_contents($requestData['avatar_blob']));
ImageOptimizer::optimize( storage_path().'/app/'.$dest_image, null );
} // if ( !empty($page_content_image) ) {
As result, I have an image uploaded, but it is not readable.
The source file has 5 Kib, the resulting file has 5.8 Kib and in the browser's console I see the blobs path as
avatar_blob: "blob:http://local-hostels2.com/91a18493-36a7-4023-8ced-f5ea4a3c58af"
Have do I convert my blob to save it correctly?
MODIFIED :
a bit more detailed :
In vue file I send request using axios :
let customerRegisterArray =
{
username: this.previewCustomerRegister.username,
email: this.previewCustomerRegister.email,
first_name: this.previewCustomerRegister.first_name,
last_name: this.previewCustomerRegister.last_name,
account_type: this.previewCustomerRegister.account_type,
phone: this.previewCustomerRegister.phone,
website: this.previewCustomerRegister.website,
notes: this.previewCustomerRegister.notes,
avatar_filename: this.previewCustomerRegister.avatarFile.name,
avatar_blob: this.previewCustomerRegister.avatarFile.blob,
};
console.log("customerRegisterArray::")
console.log(customerRegisterArray)
axios({
method: ('post'),
url: window.API_VERSION_LINK + '/customer_register_store',
data: customerRegisterArray,
}).then((response) => {
this.showPopupMessage("Customer Register", 'Customer added successfully ! Check entered email for activation link !', 'success');
alert( "SAVED!!::"+var_dump() )
}).catch((error) => {
});
and this.previewCustomerRegister.avatarFile.blob has value: "blob:http://local-hostels2.com/91a18493-36a7-4023-8ced-f5ea4a3c58af"
where http://local-hostels2.com is my hosting...
I set this value to preview image defined as :
<img
class="img-preview-wrapper"
:src="previewCustomerRegister.avatarFile.blob"
alt="Your avatar"
v-show="previewCustomerRegister.avatarFile.blob"
width="256"
height="auto"
id="preview_avatar_file"
>
and when previewCustomerRegister.avatarFile.blob is assigned with uploaded file I see it in preview image.
I show control with saving function in first topic but when I tried to opened my generated file with kate, I found that it
has content of my container file resources/views/index.blade.php...
What I did wrong and which is the valid way ?
MODIFIED BLOCK #2 :
I added 'Content-Type' in request
axios({
method: ('post'),
url: window.API_VERSION_LINK + '/customer_register_store',
data: customerRegisterArray,
headers: {
'Content-Type': 'multipart/form-data'
}
but with it I got validation errors in my control, as I define control action with request:
public function store(CustomerRegisterRequest $request)
{
and in app/Http/Requests/CustomerRegisterRequest.php :
<?php
namespace App\Http\Requests;
use App\Http\Traits\funcsTrait;
use Illuminate\Foundation\Http\FormRequest;
use App\Customer;
class CustomerRegisterRequest extends FormRequest
{
use funcsTrait;
public function authorize()
{
return true;
}
public function rules()
{
$request= Request();
$requestData= $request->all();
$this->debToFile(print_r( $requestData,true),' getCustomerValidationRulesArray $requestData::');
/* My debugging method to write data to text file
and with Content-Type defined above I see that $requestData is always empty
and I got validations errors
*/
// Validations rules
$customerValidationRulesArray= Customer::getCustomerValidationRulesArray( $request->get('id'), ['status'] );
return $customerValidationRulesArray;
}
}
In routes/api.php defined :
Route::post('customer_register_store', 'CustomerRegisterController#store');
In the console of my bhrowser I see : https://imgur.com/a/0vsPIsa, https://imgur.com/a/wJEbBnP
I suppose that something is wrong in axios header ? without 'Content-Type' defined my validation rules work ok...
MODIFIED BLOCK #3
I managed to make fetch of blob with metod like :
var self = this;
fetch(this.previewCustomerRegister.avatarFile.blob) .then(function(response) {
console.log("fetch response::")
console.log( response )
if (response.ok) {
return response.blob().then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
// myImage.src = objectURL;
console.log("objectURL::")
console.log( objectURL )
console.log("self::")
console.log( self )
let customerRegisterArray =
{
username: self.previewCustomerRegister.username,
email: self.previewCustomerRegister.email,
first_name: self.previewCustomerRegister.first_name,
last_name: self.previewCustomerRegister.last_name,
account_type: self.previewCustomerRegister.account_type,
phone: self.previewCustomerRegister.phone,
website: self.previewCustomerRegister.website,
notes: self.previewCustomerRegister.notes,
avatar_filename: self.previewCustomerRegister.avatarFile.name,
avatar: objectURL,
};
console.log("customerRegisterArray::")
console.log(customerRegisterArray)
axios({
method: 'POST',
url: window.API_VERSION_LINK + '/customer_register_store',
data: customerRegisterArray,
// headers: {
// 'Content-Type': 'multipart/form-data' // multipart/form-data - as we need to upload with image
// }
}).then((response) => {
self.is_page_updating = false
self.message = ''
self.showPopupMessage("Customer Register", 'Customer added successfully ! Check entered email for activation link !', 'success');
alert( "SAVED!!::")
}).catch((error) => {
self.$setLaravelValidationErrorsFromResponse(error.response.data);
self.is_page_updating = false
self.showRunTimeError(error, this);
self.showPopupMessage("Customer Register", 'Error adding customer ! Check Details fields !', 'warn');
// window.grecaptcha.reset()
self.is_recaptcha_verified = false;
self.$refs.customer_register_wizard.changeTab(3,0)
});
});
} else {
return response.json().then(function(jsonError) {
// ...
});
}
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ', error.message);
});
In objectURL and self I see proper values : https://imgur.com/a/4YvhbFz
1) But checking data on server in laravel's control I see the same values I had at start of my attemps to upload image:
[avatar_filename] => patlongred.jpg
[avatar] => blob:http://local-hostels2.com/d9bf4b66-42b9-4990-9325-a72dc8c3a392
Have To manipulate with fetched bnlob in some other way ?
2) If I set :
headers: {
'Content-Type': 'multipart/form-data'
}
I got validation errors that my data were not correctly requested...
?
You're using request type as application/json hence you won't be able to save the image this way, for a file upload a request type should be multipart/form-data in this case you'll need to send request as
let customerRegisterArray = new FormData();
customerRegisterArray.put('username', this.previewCustomerRegister.username);
customerRegisterArray.put('email', this.previewCustomerRegister.email);
....
customerRegisterArray.put('avatar', this.previewCustomerRegister.avatarFile);
console.log("customerRegisterArray::")
console.log(customerRegisterArray)
axios({
method: ('post'),
url: window.API_VERSION_LINK + '/customer_register_store',
data: customerRegisterArray,
headers: {
'Content-Type': 'multipart/form-data'
}
}).then((response) => {
this.showPopupMessage("Customer Register", 'Customer added successfully !Check entered email for activation link !', 'success');
alert( "SAVED!!::"+var_dump() )
}).catch((error) => {});
Thank you for your help!
Valid decision was :
var self = this;
fetch(this.previewCustomerRegister.avatarFile.blob) .then(function(response) {
if (response.ok) {
return response.blob().then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
let data = new FormData()
data.append('username', self.previewCustomerRegister.username)
data.append('email', self.previewCustomerRegister.email)
data.append('first_name', self.previewCustomerRegister.first_name)
data.append('last_name', self.previewCustomerRegister.last_name)
data.append('account_type', self.previewCustomerRegister.account_type)
data.append('phone', self.previewCustomerRegister.phone)
data.append('website', self.previewCustomerRegister.website)
data.append('notes', self.previewCustomerRegister.notes)
data.append('avatar_filename', self.previewCustomerRegister.avatarFile.name)
data.append('avatar', myBlob)
axios({
method: 'POST',
url: window.API_VERSION_LINK + '/customer_register_store',
data: data,
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data' // multipart/form-data - as we need to upload with image
}
}).then((response) => {
self.is_page_updating = false
self.message = ''
self.showPopupMessage("Customer Register", 'Customer added successfully ! Check entered email for activation link !', 'success');
alert( "SAVED!!::123")
// self.$router.push({path: '/'});
}).catch((error) => {
self.$setLaravelValidationErrorsFromResponse(error.response.data);
self.is_page_updating = false
self.showRunTimeError(error, this);
self.showPopupMessage("Customer Register", 'Error adding customer ! Check Details fields !', 'warn');
window.grecaptcha.reset()
self.is_recaptcha_verified = false;
self.$refs.customer_register_wizard.changeTab(3,0)
});
});
} else {
return response.json().then(function(jsonError) {
// ...
});
}
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ', error.message);
});
and common laravel's file uploading functionality :
$customerAvatarUploadedFile = $request->file('avatar');
...

Dynamically remove cart fees Woocommerce

I have a WordPress store using the Woocommerce plugin. I am currently able to add fees dynamically at checkout using the $woocommerce->cart->add_fee() function, assigned to the woocommerce_cart_calculate_fees hook. However, I would also like to be able to remove fees at checkout as well, but I haven't managed to make it work. I am attempting to trigger a PHP function via AJAX that will then clear the fees using this method.
When I simply echo 'success' from the clearfees() function, the AJAX call completes successfully. However, when I try calling $WC()->cart->remove_all_fees() AJAX fails with a 500 error.
Remove fees AJAX call from Javascript
function clear_fees() {
$.ajax({
type: 'GET',
url: entrada_params.admin_ajax_url,
data: { action : 'clear_fees' }
}).done( function( data ) {
console.log(data);
} )
.fail( function( jqXHR, textStatus, errorThrown ) { // HTTP Error
console.error( errorThrown );
} );
}
The clearfees function in my theme's functions.php
function clearfees() {
$WC()->cart->remove_all_fees();
wp_die();
}
// creating Ajax call for WordPress
add_action('wp_ajax_clear_fees', 'clearfees');
add_action('wp_ajax_nopriv_clear_fees', 'clearfees');
In my searching I've found very little information on the remove_all_fees() function in practice but it seems like the logical solution if I can get it to work.
i am doing this as i am apply fees in function.php
add_action( 'woocommerce_cart_calculate_fees', 'custom_fee_based_on_cart_total', 10, 1 );
function custom_fee_based_on_cart_total( $cart_object ) {
if(isset($_GET['implementation'])){
$charges = (int)$_GET['charges'];
$cart_total = (int)$cart_object->cart_contents_total;
$fees = $cart_total + $charges;
$applyfee = $_SESSION['applyfee'] ? $_SESSION['applyfee'] : 'true';
if($applyfee == 'true'){
$cart_object->add_fee( __( "Implementation Charges", "woocommerce" ), $charges, false );
}else{
$charges = 0;
$cart_object->add_fee( __( "Implementation Charges", "woocommerce" ), $charges, false );
}
}
}
and if i select remove fees option
function clearfees() {
$_SESSION['applyfee'] = 'false';
}
// creating Ajax call for WordPress
add_action('wp_ajax_clear_fees', 'clearfees');
add_action('wp_ajax_nopriv_clear_fees', 'clearfees');
and at last refresh cart page as i get success responce.

Wordpress admin-ajax.php 400 bad request

I have a strange and frustrating behaviour of wordpress admin-ajax.php file, when i make an ajax request it returns 400 error bad request.
(function( $ ) {
var ajaxscript = { ajax_url : 'mydomain.com/wp-admin/admin-ajax.php' }
$.ajax({
url : ajaxscript.ajax_url,
data : {
action : 'cart_clb',
id : 1
},
method : 'POST',
success : function( response ){ console.log(response) },
error : function(error){ console.log(error) }
})
})(jQuery)
And inside my functions.php
add_action( 'wp_ajax_post_cart_clb', 'cart_clb' );
add_action( 'wp_ajax_nopriv_post_cart_clb', 'cart_clb' );
function cart_clb(){
echo json_encode($_POST);
die();
}
As said above when i execute the request :
mydomain.com/wp-admin/admin-ajax.php 400 (Bad Request)
{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
Someone could help me to please? thank you.
First, use full and absolute url, with protocol (or at least protocol-independent form):
var ajaxscript = { ajax_url : '//mydomain.com/wp-admin/admin-ajax.php' }
Second, your ajax action name is not the php callback function name but the dynamic part of the hook wp_ajax_{action_name} / wp_ajax_nopriv_{action_name}, so in your case it should be:
data : {
action : 'post_cart_clb',
id : 1
},
I have modified your code and look at this :
(function( $ ) {
var ajaxscript = { ajax_url : 'mydomain.com/wp-admin/admin-ajax.php' }
$.ajax({
url : ajaxscript.ajax_url,
data : {
action : 'post_cart_clb',
id : 1
},
method : 'POST', //Post method
success : function( response ){ console.log(response) },
error : function(error){ console.log(error) }
})
})(jQuery)
This is the syntax of WordPress ajax :
wp_ajax_{Your_action_name}
wp_ajax_nopriv_{Your_action_name}
wp_ajax_nopriv_(action) executes for users that are not logged in.
So, if you want it to fire on the front-end for both visitors and logged-in users, you can do this:
add_action( 'wp_ajax_my_action', 'my_action' ); // for loggin users
add_action( 'wp_ajax_nopriv_my_action', 'my_action' ); // for non loggin users
admin-ajax.php returns Bad Request headers in 2 situations, when the action function is not registered, and when the action parameter is empty.
I had same error and the issue was that i forgot to add_action('wp_ajax_nopriv'...) i had only wp_ajax_nopriv set, so when i was logged in as admin nesting, it was not working.
In my case, I am using Class based approach. And I found the issue was because I was using wp_ajax_ request in constructor.
If you are using ajax methods inside class, move wp_ajax_ handles outside of class (write in main plugin file) and pass classname and method name. For example:
add_action( 'wp_ajax_your_handle', [ 'Class_Name', 'function_name' ] );
add_action( 'wp_ajax_nopriv_your_handle', [ 'Class_Name', 'function_name' ] );
Just Use
add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
For more detail, check the below link
https://codex.wordpress.org/AJAX_in_Plugins
In Vanilla JavaScript You get a Bad Request if You don't append this header to the POST request:
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
So please be sure that jQuery appends as well that header.
in the url use /wp-admin/admin-ajax.php and try to have a local domain because with localhost or localhost/wordpress this might be weird, on the server this will work fine
try to use fetch or XMLHttpRequest to have more control over the request and don't send data as json send it in a formData object const formData = new FormData();
fetch(loader.ajax_url, {
method: "POST",
body: formData,
}).then((resp) => {
console.log(resp);
}).catch((resp) => {
console.log(resp);
});
it is possible to have it work with other combinations but i find this almost perfect

How does check_ajax_referer() really work?

Smart Wordpress people say that plugin developers should employ a nonce in each AJAX request that is sent from a page back to the wordpress blog (admin-ajax.php).
This is done by (1) generating a nonce on the server side, via
$nonce = wp_create_nonce ('my-nonce');
...(2) making that nonce available to Javascript code that sends AJAX requests. For example you could do it like this:
function myplg_emit_scriptblock() {
$nonce = wp_create_nonce('myplg-nonce');
echo "<script type='text/javascript'>\n" .
" var WpPlgSettings = {\n" .
" ajaxurl : '" . admin_url( 'admin-ajax.php' ) . "',\n" .
" nonce : '" . $nonce . "'\n" .
" };\n" .
"</script>\n";
}
add_action('wp_print_scripts','myplg_emit_scriptblock');
...and then (3) the javascript ajax logic references that global variable.
var url = WpPlgSettings.ajaxurl +
"?action=my-wp-plg-action&" +
"nonce=" + WpPlgSettings .nonce +
"docid=" + id;
$.ajax({type: "GET",
url: url,
headers : { "Accept" : 'application/json' },
dataType: "json",
cache: false,
error: function (xhr, textStatus, errorThrown) {
...
},
success: function (data, textStatus, xhr) {
...
}
});
...and finally (4) checking the received nonce in the server-side logic.
add_action( 'wp_ajax_nopriv_skydrv-hotlink', 'myplg_handle_ajax_request' );
add_action( 'wp_ajax_skydrv-hotlink', 'myplg_handle_ajax_request' );
function myplg_handle_ajax_request() {
check_ajax_referer( 'myplg-nonce', 'nonce' ); // <<=-----
if (isset($_GET['docid'])) {
$docid = $_GET['docid'];
$response = myplg_generate_the_response($docid);
header( "Content-Type: application/json" );
echo json_encode( $response ) ;
}
else {
$response = array("error" => "you must specify a docid parameter.");
echo json_encode( $response ) ;
}
exit;
}
But how does the check really work?
Revising some AJAX procedures, I came to the same question. And it's a simple matter of checking the function code:
function check_ajax_referer( $action = -1, $query_arg = false, $die = true ) {
if ( $query_arg )
$nonce = $_REQUEST[$query_arg];
else
$nonce = isset($_REQUEST['_ajax_nonce']) ? $_REQUEST['_ajax_nonce'] : $_REQUEST['_wpnonce'];
$result = wp_verify_nonce( $nonce, $action );
if ( $die && false == $result ) {
if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
wp_die( -1 );
else
die( '-1' );
}
do_action('check_ajax_referer', $action, $result);
return $result;
}
If wp_verify_nonce is false and you haven't sent false in the $die parameter, then it will execute wp_die( -1 );.
In your sample code, check_ajax_referer() will break the execution and return -1 to the AJAX call. If you want to handle the error yourself, add the parameter $die and do your stuff with $do_check:
$do_check = check_ajax_referer( 'myplg-nonce', 'nonce', false );
Note that the proper way to handle AJAX in WordPress is: register, enqueue and localize the JavaScript files using wp_enqueue_scripts instead of wp_print_scripts.
See Use wp_enqueue_scripts() not wp_print_styles().
Check this update in December 2020 from a core contributor h/t: Rafael Atías:
Apparently we should now use wp_add_inline_script instead of wp_localize_script to expose a global object that needs to be used by your script.
It is just a test that the "nonce" code matches what was given, so a hacker can't cut in and get a shortcut to your database. If the security code doesn't match, the php will die and the page will halt.
"If you code is correctly verified it will continue past, if not it will trigger die('-1'); stopping your code dead."

Resources