I have a multisite wordpress with 2 subdomains, lets say site1.example.com and site2.example.com .
I am sending an AJAX request from site2 to site1 and I'm getting 400 bad request error. Is it possible to send AJAX request to other site ? I've dealt with the CORS issue but not sure why 400 error is occuring.
This is the code I've written in site2 functions.php file:
function custom_profile_content(){
?>
<script>
jQuery(document).ready(function(){
var data = "action=custom_my_action";
jQuery.ajax({
url: 'https://site1.example.com/wp-admin/admin-ajax.php',
type: 'POST',
data : data,
success : function(response){
console.log(response)
},
error: function(){ console.log('error') }
})
})
</script>
<?php
}
add_action('bp_after_member_home_content', 'custom_profile_content');
This is the code I've written in site1 functions.php
function custom_ajax_example(){
echo "success";
wp_die();
}
add_action( 'wp_ajax_custom_my_action', 'custom_ajax_example');
add_action( 'wp_ajax_nopriv_custom_my_action', 'custom_ajax_example');
Related
I have an ajax function in jquery caling a cakephp4 function. The function doesnt work as it is giving a 403 forbidden error. The error is about headers but i cant find what I need to fix this exactly.
This code runs and it does get the var (alert verifies this). Nothing works ?
jquery
///
var freeassessmentid = "<?=$testid?>";
$.ajax({
url: "/freeassessments/freeasssesmenFinaltResult", //path is correct and it can be tested on its own
method: "POST",
dataType: "html",
data: { freeassessmentid:freeassessmentid },
success: function(response) {
//console.log(response);
$('#display-area').append(response); //no output
}
});
public function freeasssesmenFinaltResult($freeassessmentid=0)
{
//debug('test');
$html .= '<li class="listyle" style="height: auto;">hi<br/></li>';
$html .= '</ul>';
//no output
//https://stackoverflow.com/questions/36666256/jquery-ajax-call-results-in-error-status-403
The Ajax url should be:
url: "/freeassessments/freeasssesmen-finalt-result",
Use the kebab case for actions/methods in urls and the camel case for them in the controllers
You have to pass CSRF token in header during ajax call.
You can get CSRF token in many ways.
One of the simplest way is:
You can add bellow code to your head tag of parent layout or inside any of your template file.
<?php echo $this->Html->meta("csrfToken", $this->request->getAttribute("csrfToken")); ?>
At the time of ajax call you will have to get this csrf token and pass it to the ajax header.
Here is the example:
var token = $("meta[name='csrfToken']").attr("content");
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': token
}
});
$.ajax({
url: "path/to/controller/method",
method: "POST",
data: { pram1:val },
success: function(response) {
//console.log(response);
}
});
I hope it may help :)
Trying out AJAX request for the first time and facing problem. I want to load a php file on button click in Wordpress site. So far after researching, I got this code:
index.php file:
<button id="ajaxbtn">Ajax</button>
<div id="ajax">Some Text</div>
ajax.php file (the file i want to be loaded):
<?php echo "Hello!" ?>
functions.php file:
add_action( 'wp_enqueue_scripts', 'myajax_data', 99 );
function myajax_data(){
wp_localize_script('menu_toggle', 'myajax',
array(
'ajax_url' => admin_url('admin-ajax.php')
)
);
}
add_action('wp_ajax_tablo', 'tablo');
add_action('wp_ajax_nopriv_tablo', 'tablo');
function tablo() {
// Grab php file output from server
ob_start();
include(get_template_directory_uri() . '/ajax.php');
$result['content'] = ob_get_contents();
$result = json_encode($result); // use wp_send_json instead to make this shorter
echo $result;
die();
}
menu_toggle.js file (js file with ajax code):
$("#ajaxbtn").click(function () {
$.ajax({
type : 'post',
dataType : 'json',
url : myajax.ajax_url,
data : {action: 'tablo'},
success: function(response) {
//load the fetched php file into the div
alert('Load was performed.');
$('#ajax').append("hello");
$('#ajax').load(response.content);
}
});
});
I can actually get alert('Load was performed.'); and $('#ajax').append("hello"); displaying, so that means that ajax was connected right way and ajax request is working correctly. But $('#ajax').load(response.content); loading whole same index page in #ajax div instead of loading the content of ajax.php file i actually want. I probably got the wrong code either in function tablo() of functions.php file, or in ajax code of menu_toggle.js file. Can someone please help with this one?
You need to convert/parse the json data in JS coming from PHP. Like :
var res = JSON.parse(response);
The full code look like :
$("#ajaxbtn").click(function () {
$.ajax({
type : 'post',
dataType : 'json',
url : myajax.ajax_url,
data : {action: 'tablo'},
success: function(response) {
//load the fetched php file into the div
var res = JSON.parse(response);
alert('Load was performed.');
$('#ajax').append("hello");
$('#ajax').load(res.content);
}
});
});
Chetan Vaghela just helped with this problem on wordpress.stackexchange.com. If someone encounters with same problem as i had, please check Chetan Vaghela's answer below:
Solution provided by Chetan Vaghela on wordpress.stackexchange.com
I have made a ajax call in laravel 5.4 following is the script
<script>
$(document).ready(function()
{
$("#btnLogin").click(function()
{
// var username = $('#username').val();
// var password = $('#password').val();
// var form = new FormData($('.login-form')[0]);
var form = $('.login-form').serializeArray();
$.ajax({
url: '/login',
type: 'POST',
dataType: 'JSON',
data: {form},
})
.done(function(resp){
console.log(resp);
})
.fail(function(resp){
console.log(resp);
})
.always(function(resp){
console.log(resp);
});
});
});
</script>
This is my web.php in routes folder
<?php
Route::match(['get', 'post'], '/login', function () {
return "hello";
});
It is showing the error in console log, i dont know why it is showing this. Firstly it was showing 404 not found then i realized that i had not defined in rotes then i defined in routes then it is showing this error.
POST http://www.example.com/login 500 (Internal Server Error)
If access this url through browser direct it is showing hello but if i am making through ajax it is not loading.
When you hitting through browser, you are requesting page with get request, however, through ajax, it goes through post.
I am using admin ajax but it is not working. Kindly, help me to find out the problem. Here is jquery code
jQuery(document).ready(function($) {
jQuery('#newPostsForm').submit(ajaxSubmit);
function ajaxSubmit(){
var newPostsForm = jQuery(this).serialize();
jQuery.ajax({
type:"POST",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
}
});
return false;
}
}):
If I alert the var "newPostsForm" , it shown the posted values.but it is now proceeding to ajax. Here is the from I am using
<form type="post" action="" id="newPostsForm">
<input type="hidden" name="action" value="addPosts"/>
<!-- input fields -->
</form>
An here is the WordPress function I am using. this function is another file. HTML and javascript are in same file
function addPosts(){
echo "<pre>";
print_r($_POST);
die();
}
add_action('wp_ajax_addPosts', 'addPosts');
add_action('wp_ajax_nopriv_addPosts', 'addPosts'); // not really needed
Check to see if the script is getting processed by PHP before it is sent to the client. Change the code to something similar to this:
jQuery(document).ready(function($) {
jQuery('#newPostsForm').submit(ajaxSubmit);
function ajaxSubmit() {
var newPostsForm = jQuery(this).serialize();
var url = "<?php echo admin_url('admin-ajax.php'); ?>";
alert("Submitting to URL: " + url);
jQuery.ajax({
type:"POST",
url: url,
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
},
error: function (xhr, status, err) {
alert("Got status " + status + " and error: " + err);
}
});
return false;
}
});
If you get an actual URL like https://mysite.example.org then check that the URL goes to a valid location. If you get <?php echo admin_url('admin-ajax.php'); ?> then your code is not getting processed by PHP, and the AJAX call will fail because you are not using a valid URL.
The problem seems that the AJAX URL is not accessible in JS code. If the JS code written into a PHP page then only the code will work. Because the PHP code cant be executed into the JS files.
NOW the solution is to localized the JS file. Please follow the code.
wp_localize_script( 'handle', 'settings', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
Write the above code just under where you have enqueued your js file.
NOW in JS file :
jQuery.ajax({
type:"POST",
**url: settings.ajaxurl,**
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
}
});
Hope it will work at your choice.
I am creating a simple wordpress plugin and trying to use AJAX, but I always get 0 in ajax response.
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
action: 'my_action',
whatever: '1234'
};
jQuery.post("http://localhost/taichi/wp-admin/admin-ajax.php", data, function(response) {
alert(response);
});
});
</script>
<?php
add_action('wp_ajax_my_action', 'my_action_callback');
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback() {
echo "test";
die();
}
what am I doing wrong?
You have to put the add_action at the complete bottom of your file or else it won't find the callback function
Try to change :
jQuery.post("http://localhost/taichi/wp-admin/admin-ajax.php", data, function(response)
To :
jQuery.post(ajaxurl, data, function(response)
And check if it is working on the admin side first. It should work fine.
Error Return Values
If the AJAX request fails when the request url is wp-admin/admin-ajax.php, it will return either -1 or 0 depending on the reason it failed.
Read this
Edit
admin-ajax always return default '0' as output.so while you alerting response you will 0 only.using die() in callback function will terminate that.
Had the same problem, it turned out that my callback was inside a php file which was only included to my "Theme Options" page.
To check if the function is able to trigger trougth admin-ajax.php try to add var_dump(function_exists("your_callback_name")); to the bottom of the wp-admin/admin-ajax.php (before die( '0' );) and then have a look to your ajax output.
Try the following code in your plugin file. or in function.php
jQuery(document).ready(function($){
var ajaxURL = 'http://localhost/taichi/wp-admin/admin-ajax.php';
var dataString = 'action=mnd_news';
$.ajax({
type: "POST",
url: ajaxURL,
data: dataString,
cache: false,
success: function(response){
if(response != 'error') {
alert(response);
}
}
});
});
add_action('wp_ajax_mnd_news', 'get_mnd_ajax');
add_action( 'wp_ajax_nopriv_mnd_news', 'get_mnd_ajax' );
function get_mnd_ajax() {
echo "test";
die();
}