Forbidden Error in ajax call with wordpress - ajax

I'm getting 403 error in my plugin develop when I try to use ajax calls. I had disabled all plugins and activated default theme, no works. I have no cache plugin, and I have no server cache.
I get:
403
Forbidden
Access to this resource on the server is denied!
PHP
add_action('wp_ajax_actualizar_jornada', 'actualizar_jornada' );
add_action('wp_ajax_nopriv_actualizar_jornada', 'actualizar_jornada');
function actualizar_jornada() {
$postdata = $_POST;
echo $postdata;
wp_die();
}
LOCALIZATION SCRIPT
wp_register_script('lmfront-js', plugin_dir_url( __FILE__ ) . '../includes/js/lmfront.js');
wp_localize_script('lmfront-js', 'strings', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'lstJugadoresParticipantesPlaceholder' => __('Find Players', 'leaguemanagement'),
'lstEquiposTeamsPlaceholder' => __('Find Teams', 'leaguemanagement'),
));
wp_enqueue_script('lmfront-js');
JS
$('.btn-update-jornada').on('click', function(){
var idjornada = parseInt($(this).data('idjornada'));
var data = {
'action': 'actualizar_jornada',
'idjornada': idjornada,
'marcador_local': parseInt($('#resultado-local-' + idjornada).val()),
'marcador_visitante': parseInt($('#resultado-visitante-' + idjornada).val()),
};
$.ajax({
type : "post",
url : strings.ajaxurl,
data : data,
error: function(response){
console.error(response);
},
failure: function(response){
console.error(response);
},
success: function(response) {
console.log(response);
}
});
});

Related

Ajax in Wp work only in index.php but not in footer,php and other pages

$.ajax({
url: '<?php echo admin_url("admin-ajax.php") ?>',
type: 'POST',
data: 'action=my', // можно также передать в виде массива или объекта
success: function( data ) {
alert( data );
}
});
This code work only in index.php
Inline usage of Ajax requests is not acceptable in WordPress.
Instead of it you need to use the code like this:
Javascript
var data = {
'action' : 'my_action'
};
jQuery.post( ajaxurl, data, function(response) {
});
PHP
add_action( 'wp_ajax_my_action', 'my_action_func' );
add_action( 'wp_ajax_my_action', 'my_action_func');
function my_action_func(){
echo 'this is result';
wp_die();
return;
}
Notes: put JavaScript is code in .js file, ajaxurl should be defined before the ajax request.

Returning a view with previous inputs using Laravel

I have a form, when submitted, invokes an AJAX request. This ajax request performs back-end validation on the inputs. If an error is detected, it displays the error messages. So if the user fills out 30 fields, and one is not valid, I would like to return all those inputs with an error message.
My Laravel Code:
Route::post('/roa', function() {
$m = Request::except('_token');
$name = "form1_sections/" . $m['nextTab'] . "_form";//next view name
$name2 = "form1_sections/" . $m['currentTab'] . "_form";//current view name
$var= parse_str($m['inputs'], $output);//data from ajax is a string
if ($m['currentTab']=='section2'){//i'm only doing validation on one section right now
//to simplify the code.
$rules = [
'TB1_course.*' => 'required'
];
$validator=Validator::make($output, $rules);
if ($validator->passes()){//if no error, return the next view
return ["view" => view("$name")-> render(), "value"=>1, "inputs"=>$output];
}
return ["view" => view("$name2")->withInput($output)->withErrors($validator) -> render(), "value"=>1, "inputs"=>$output];
}
return ["view" => view("$name") -> render()];
});
My Ajax request:
$('#form').on('submit', function (e) {
var formData = $('#form').serialize();
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: '/roa',
dataType: 'json',
data: {inputs: formData, nextTab: relatedTabID, currentTab: tabID},
success: function(data){
$('#tabShow').html((data.view));
},
error: function () {
alert('error');
}
});
});
I am successfully able to receive all the error messages, but the withInput($output) for some reason is not working. Thank you for all your help.
'view' => view('template')->withInput()?

Using Ajax in meta-box button on post.php

I have created a plugin that creates a custom Post Type called smm_newsletter, and used that Post Type to create newsletter template and send a newsletter email. Then, I made a meta-box for sending button include in that Post Type's post-new.php/post.php.
The script for wp_localize_script is this
function smm_admin_scripts() {
wp_register_script( 'smm-js-priv-script', plugins_url( '/js/private/smm-builder.js', __FILE__ ), array( 'jquery' ), '', true );
// localize admin URL
$php_localized_priv_script = array( 'admin_url' => admin_url() );
wp_localize_script( 'smm-js-priv-script', 'smm_priv_script', $php_localized_priv_script );
wp_enqueue_script( 'smm-js-priv-script' );
}
add_action( 'admin_enqueue_scripts', 'smm_admin_scripts' );
*I added exactly same localized admin URL to my public scripts function and it work fine in input submit button. This code too, it work fine in input submit button.
This is code for that button
// I do not use type="submit" because publish/update button use it.
<input id="smm_newsletter_send" name="smm_newsletter_send" type="button" value="Send Newsletter">
and ajax
jQuery( document ).ready( function($) {
/* Newsletter Section */
// I did localized script for path to wp-admin here
var wpajax_url = smm_priv_script.admin_url + 'admin-ajax.php';
var sendingNewsletter_url = wpajax_url + '?action=smm_newsletter_sender';
// out put form console: http://localhost/wordpressProject/wordpress/wp-admin/admin-ajax.php?action=smm_newsletter_sender
console.log(sendingNewsletter_url);
$( '#smm_newsletter_send' ).on( 'click', function( e ){
e.preventDefault();
$form = $( 'form#post' );
// setup our form data for ajax post
var form_data = $form.serialize();
console.log( form_data ); // here it work find
// submit form data with ajax post
$.ajax({
'method' : 'post',
'url' : sendingNewsletter_url,
'data' : form_data,
'dataType' : 'json',
'catch' : false,
'success' : function( data, textStatus ){
if( data.status == 1 ) {
// success
// notify the user of success
window.location.reload( true );
console.log( data.status + '\n' );
console.log( data.message + '\n' + '——————————' );
} else {
// error
// begin building our error message text
console.log( data.status + ' ' + 'error' + '\n' );
console.log( data.message + '\n' + '——————————' );
}
},
'error' : function( jqXHR, textStatus, errorThrown ) {
// ajax didn't work
console.log('A jQuery Ajax error has occurred! See details below...');
console.log(textStatus);
console.log(errorThrown);
}
});
// stop the form from submitting nornally
return false;
});
});
But, after I clicked that button ajax() only console.log undefined for me
undefined error
undefined
——————————
So, I tried another method to test my sending newsletter function [smm_newsletter_sender()] to make sure that function works, by changing $_POST to $_GET. And simply placed URL that look like this http://localhost/wordpressProject/wordpress/wp-admin/admin-ajax.php?action=smm_newsletter_sender?post_ID=123. It worked perfectly, by sending all of newsletter emails and returning the proper JSON. My email sending function is working fine, but the button for send not, why?.
At first, I had suspected about ajax(), may I did something wrong about it? But I did not found anything wrong. So, may be It about WordPress itself that prevent something that I don't know.
The first thing is to print our scripts only on the pages we need. This is important because we don't want our styles/scripts printing all over wp-admin.
add_action( 'admin_print_scripts-post.php', 'smm_admin_script');
add_action( 'admin_print_scripts-post-new.php', 'smm_admin_script');
Also:
check if it's the correct Post Type before printing the scripts:
localize the full admin-ajax URL
localize the security nonce
function smm_admin_script() {
global $typenow;
if( 'smm_newsletter' !== $typenow )
return;
wp_enqueue_script('my-ajax', plugins_url( '/my-ajax.js', __FILE__ ), array('jquery') );
wp_localize_script(
'my-ajax',
'my_plugin',
array(
'ajaxnonce' => wp_create_nonce( 'nonce_smm' ),
'ajaxurl' => admin_url( 'admin-ajax.php' )
)
);
}
The file my-ajax.js will use the localized values my_plugin.ajaxnonce and my_plugin.ajaxurl. The action is defined on the Ajax PHP function.
For testing I used button#send-ajax and div#aresponse.
jQuery(document).ready(function($) {
$( '#send-ajax' ).click( function(e) {
e.preventDefault();
var data = {
action: 'sendform_smm',
security: my_plugin.ajaxnonce,
form_smm: { 'input1': 'value1', 'input2': 'value2' }
};
/*
You can send the full form as an object using:
form_smm: $form.serializeArray()
*/
$.post(
my_plugin.ajaxurl,
data,
function( response ){
// ERROR HANDLING
if( !response.success ) {
// No data came back, maybe a server error
if( !response.data )
$( '#aresponse' ).html( 'AJAX ERROR: no response' );
else
$( '#aresponse' ).html( response.data.error );
}
else
$( '#aresponse' ).html( response.data );
}
);
});
});
The Ajax function checks the nonce, you make your thing and return Error or Success:
add_action( 'wp_ajax_sendform_smm', 'sendform_smm_callback' );
function sendform_smm_callback() {
check_ajax_referer( 'nonce_smm', 'security' );
# Form values sent by JS
$received_data = $_POST['form_smm'];
# Read the data sent and send it back just for testing purposes.
$text = 'Input Field: ' . $received_data['input1'];
# Your form actions
$do_your_thing = true;
if( !$do_your_thing )
wp_send_json_error( array( 'error' => __( 'Error message.' ) ) );
else
wp_send_json_success( $text );
}
Looks like your ajax url displaying undefined.
You need to localize your script first like:
wp_register_script('myscript', get_stylesheet_directory_uri() . '/js/myscript.js', array('jquery'), '1.0.1', TRUE);
$protocol = !empty($_SERVER['HTTPS']) ? 'https://' : 'http://';
wp_localize_script('myscript', 'ajax_obj', array('admin_ajax' =>admin_url('admin-ajax.php',$protocol)));
// Enqueued script with localized data.
wp_enqueue_script('myscript');
Then in your .js file read admin URL like :ajax_obj.admin_ajax.
I had tried in many ways to solve this problem. OK, I don't know why, but this make it work. At first, I changed method form POST to GET and input button to a.
This is happen in custom meta-box.
// I created nonce url for security thing
$nonce_url = wp_nonce_url( admin_url( 'admin-ajax.php?action=smm_newsletter_sender&post_ID=' . $post->ID ), basename( __FILE__ ), 'smm_send_newsletter_nonce' );
// and changed inupt to a tag
echo( '<div>Send Newsletter' );
and in jQuery ajax()
jQuery( document ).ready( function($) {
$( '#smm_newsletter_send' ).on( 'click', function( e ){
$.ajax({
'method' : 'GET',
'url' : $( this ).attr( 'href' ),
'dataType' : 'json',
'catch' : false,
'success' : function( data, textStatus ){
if( data.status == 1 ) {
// success
// notify the user of success
window.location.reload( true );
console.log( data.status + '\n' );
console.log( data.message + '\n' + '——————————' );
} else {
// error
// begin building our error message text
console.log( data.status + 'error' + '\n' );
console.log( data.message + '\n' + '——————————' );
}
},
'error' : function( jqXHR, textStatus, errorThrown ) {
// ajax didn't work
console.log('A jQuery Ajax error has occurred! See details below...');
console.log(textStatus);
console.log(errorThrown);
}
});
e.preventDefault();
// stop the form from submitting nornally
return false;
});
});
As I said above, I don't know why this work and, in case of input button, why ajax() can not sent the request URL to sending action. So, this is only a practical way.
If someone can explain, please do it.
Thank.

Wordpress Ajax returns 0 from PHP data but the ajax is working

Everytime I click Submit the popup alert only ever gives me a value of 0, also the console never logs what I echo from the php function. The String "Monkey" below does appear in the html, but the data variable doesnt work. (note: I've omitted the full ajax URL from public display)
In my WP plugin I've put this code:
function register_bio_script(){
wp_register_script('bio-script',plugins_url('js/bio-script.js',__FILE__), false, '1.0.0', 'all');
}
add_action('init','register_bio_script');
function enqueue_bio_script(){
wp_enqueue_script( 'bio-script', plugin_dir_url(__FILE__) . 'js/bio-script.js' );
}
add_action('wp_enqueue_scripts', 'enqueue_bio_script');
add_action( 'wp_ajax_nopriv_ MyAjaxFunction', 'MyAjaxFunction' );
add_action( 'wp_ajax_ MyAjaxFunction', 'MyAjaxFunction' );
function MyAjaxFunction(){
$GreetingAll = $_POST['GreetingAll'];
echo "peanut";
$results = "<h2>".$GreetingAll."</h2>";
die($results);}
and then i have the JS:
jQuery(document).ready(function() {
var GreetingAll = jQuery("#GreetingAll").val();
jQuery("#PleasePushMe").click(function(){
jQuery.ajax({
type: 'POST',
url: '.../wp-admin/admin-ajax.php',//the full url goes here
data: {
action: 'MyAjaxFunction',
GreetingAll: GreetingAll
},
success: function(data, textStatus, XMLHttpRequest){
jQuery("#test-div1").html('');
jQuery("#test-div1").append("Monkey");
alert(data);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
solved! i had to use wp_localize_script() for frontend ajax. wp ajax only works for backend users unless the script is localized.
the actual coding is complex but all the answers are
in this tutorial http://www.benmarshall.me/wordpress-ajax-frontend-backend/

how i call javascript function in ajax callback function

how i call javascript function in ajax callback function and how i can pass arguments to this javascript function like field name or something
'#ajax' => array(
'callback' => 'ajax_javascript_function',
'wrapper' => 'd-div-autocomplete-textfield-div',
'method' => 'replace',
'event' => 'blur',
'effect' => 'fade',
'progress' => array('type' => 'throbber', 'message' => ''),
),
You need to pass those variables to a server with javascript ajax JSONP. There are many ways, but here are 2 examples:
With plain querystring:
$.ajax({
type: "GET",
dataType: "jsonp",
url: "some.php?callback=mycallback",
data: "name=John&location=Boston",
success: function(response){
alert( "Data received: " + received);
},
error: function(e){
alert(e);
}
});
with object for querystring parameters
$.ajax({
type: "GET",
dataType: "jsonp",
url: "some.php?callback=mycallback",
data: {
"name" : "John",
"location" : "Boston"
}
success: function(response){
alert( "Data received: " + response );
},
error: function(e){
alert(e);
}
});
Your PHP code must output its response with the callback you asked for in this javascript (I used 'mycallback'). If you are not writing the PHP(or some kind of server side code) then that server must be agreeing to return responses wrapped with the callback function you asked for it to use. This way, the response gets into your javascript because you told it what function would be callable. This is called JSONP architecture. It works because the one thing that you can request Cross-Domain is a script.
PHP
echo "mycallback('" + $data + "');";
Good luck, read more here: http://api.jquery.com/jQuery.ajax/

Resources