Getting wordpress to play nice with AJAX - ajax

How do I use WP functions from AJAX calls. I've looked at the documentation for creating plugins that use ajax, but I couldn't figure out how to apply that to regular pages and posts.
Is there an easy way to just load everything without using their API? I have my way I like to do ajax and would rather not use their stuff.
This is a fluff version of my code:
Javascript (jQuery):
$('.action.next_posts').click(function() {
var last_date = $(this).attr('title');
//alert();
$.ajax({
url: WP_DIR+'functions.php?action=get_next_posts',
type: 'POST',
data: {date : last_date},
success: function(response) {
alert(response);
},
error: function(error) {
alert("error");
}
});
});
Functions.php (PHP):
// AJAX controller
if(isset($_GET['action'])) {
require_once('../../../wp-config.php');
require_once('../../../wp-includes/classes.php');
require_once('../../../wp-includes/functions.php');
wp();
echo 'ok';
echo bloginfo('name'); // NOT WORKING. TRIED adding actions..
return;
}

The following solution should work. You are going to go ahead and post directly to the WordPress installation and intercept the request before WordPress does all the querying that it would normally do. There are some caveats to this method, one of which being that some caching methods will interfere with it, but it should work fairly well for your purposes.
Besides, you said you didn't want to use the specified WordPress API, so this should be right up your alley.
JavaScript:
jQuery(document).ready(function($) {
$('.action.next_posts').click(function(event) {
event.preventDefault();
var last_date = $(this).attr('title');
$.ajax({
url: '/',
type: 'post',
data: {date : last_date, action: 'get_next_posts'},
success: function(response) {
alert(response);
},
error: function(error) {
alert("error");
}
});
});
});
functions.php
add_action('parse_request','my_request_parser');
function my_request_parser($wp) {
if( 'get_next_posts' == $_POST['action'] ) {
echo 'ok';
bloginfo('name');
exit();
}
}

Related

Simple wordpress ajax query is not working

Do you have any idea why this simple wp ajax query is not working? It always returns fail. Console -> https://pastebin.com/TABQCjXe
jQuery(document).ready(function($) {
// This does the ajax request
$.ajax({
type: 'post',
url: ajaxurl,
data: {
'action':'prefix_load_cat_posts'
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
$( ".prefix_load_cat_posts" ).append("success");
},
error: function(errorThrown){
console.log(errorThrown);
$( ".prefix_load_cat_posts" ).append("fail");
}
});
});
PHP -> https://pastebin.com/g4QiWDky
The action should be load-filter instead of prefix_load_cat_posts. Seeing your PHP code, the prefix_load_cat_posts is actually the callback function name.
data: {
'action':'load-filter'
},
There is another alternate option. I am agree with samuel but i am sharing one more option
add_action( 'wp_ajax_nopriv_prefix_load_cat_posts', 'prefix_load_cat_posts' );
add_action( 'wp_ajax_prefix_load_cat_posts', 'prefix_load_cat_posts' );
Your action it's 'load_filter', Also you are must be localize ajaxurl use this function wp_localize_script
$.ajax({
type: 'post',
url: ajaxurl,
data: {
'action':'load-filter'
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
$( ".prefix_load_cat_posts" ).append("success");
},
error: function(errorThrown){
console.log(errorThrown);
$( ".prefix_load_cat_posts" ).append("fail");
}
});

WordPress API functions not working at AJAX functions.php call

I am trying to show subcategories of a category in WordPress using AJAX: when I select a main category, there is a call to WP Ajax and the result is used in showing the subcategories.
So far, I have the client-side code that works when not calling a WP function (this code is in a theme page):
jQuery('#cat-location-main').change(function () {
var optionSelected = jQuery(this).find('option:selected');
var valueSelected = optionSelected.val();
var textSelected = optionSelected.text();
console.log(valueSelected);
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {
action: 'myajax-get-subcat',
category: valueSelected,
// send the nonce along with the request
categoryNonce: '<?php echo wp_create_nonce( 'myajax-get-subcat-nonce' );?>'
},
success: function(data, textStatus, jjqXHR) {
console.log(data);
},
dataType: 'json'
});
});
And I have this in the functions.php:
add_action('wp_ajax_myajax-get-subcat', 'myajax_get_subcat');
function myajax_get_subcat() {
$nonce = $_POST['categoryNonce'];
$main_category = $_POST['category'];
if (!wp_verify_nonce($nonce, 'myajax-get-subcat-nonce'))
die ( 'Busted!');
if(function_exists('wp_dropdown_categories')==true) {
echo 'true';
} else {
echo 'false';
}
wp_dropdown_categories('taxonomy=category&selected=1&echo=1&orderby=NAME&order=ASC&hide_empty=0&hide_empty=0&hierarchical=1&depth=1&id=cat-location-secondary&child_of='.$main_category);
exit;
}
Now I get a "true" on the client side when commenting wp_dropdown_categories line, and I get absolutely nothing when I uncomment that line (PHP crash). Nothing in php error log (WAMP setup).
Also, not working even if I add require_once(__DIR__.'/../../../wp-load.php'); but it works if I use GET in browser (for the functions.php).
Any help would be greatly appreciated!
My problem was because I do not return a json object but an html (actually mixed text and html), and you set jQuery to validate that the response is json, which it isn't.

load mypage.php via ajax into a div in wordpress

i have an ajax load request working in wordpress, but i would like to load the content from another page into the container div. at the moment it just passes the url in $dataToSend as a string?
jQuery(document).ready(function(){
var $dataToSend = "my-page.php";
var $testBtn = jQuery('#text-ajax-btn');
var $holdingCtn = jQuery('#my-holding-ctn');
$testBtn.click(function(){
jQuery.ajax({
type:'POST',
url: myAjax.ajaxurl,
data:{
action:'myAjax',
dataToSend:$dataToSend,
},
success: function(data,textStatus,XMLHttpRequest){
$holdingCtn.html("");
$holdingCtn.append(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
how can i pass an entire .php page through as the $dataTosend?
I do this all the time for wordpress, give me a sec to access my repository and I will show you example code.
I think problem is your my-page.php! I imagine you custom coded it. So it doesn't have necessary functions loaded.
put following code at the top of your my-page.php (this will help with 500 error you are getting)
require('../../../wp-load.php');
ajax part should look something like this:
//start ajax
$.ajax({
url: "http://localhost/wp-content/themes/theme/my-page.php",
type: "POST",
data: data,
cache: false,
success: function (data) {
console.dir(data);
}
})
If you want to load content from my-page.php file then you can load from the server side using
$data = file_get_contents('path/to/file/my-page.php'); // pass right path/url
Then, just echo the content from your function (registered ajax handler in WordPress using add_action) and in this case it should be
echo $data;
die(); // terminate the further execution
So, it should look something like
add_action( 'wp_ajax_myAjax', 'yourAjaxHandler' );
add_action( 'wp_ajax_nopriv_myAjax', 'yourAjaxHandler' );
function yourAjaxHandler(){
$data = file_get_contents('path/to/file/my-page.php');
die($data); // echo out the string and terminates execution
}
In your success callback, you can use
success: function(data){
jQuery('#my-holding-ctn').html(data);
}
Not sure if this is fully applicable, but the super easy way is just
$("#myDiv").load("myFile.php?foo=1&bar=2...");

Write to Session with Post - CakePHP

I am trying to post an array of check box ids to an action in my controller. Here is the script from my index.ctp:
<script type="text/javascript">
$('.editSel_dialog').click(function()
{
var selected = [];
alert('Edit Selected Has Been Clicked');
$("#[id*=LocalClocks]").each(function()
{
if(false != $(this).is(':checked'))
{
selected.push($(this).attr('id').replace('LocalClocks', ''));
}
});
alert(selected);
/*$.ajax(
{
type: 'POST',
url: "/LocalClocks/editSelected/",
data: selected,
traditional: true,
//contentType: "application/json",
dataType: "text",
success: function(data){ alert(data); alert('Edit Success');}
});*/
$.post('/LocalClocks/editSelected', { "Session" : selected }, function(data){
alert(data);
});
});
</script>
I have both an ajax request and a post request. I was using the ajax until I saw that the post can actually modify a php variable. The code in the braces { "Session" : selected } should modify the Session variable with the array selected.
I tried using debug on $this->data, and $this->request->data, and $_POST, but they all are empty.
I need help getting the selected array written to a variable or something. I was thinking of trying to write to $this->Session but I am not sure how I would go about doing that.
Thanks in advance
With Cake, to get posted values in $this->request->data, their names have to be prefixed with data:
Javascript:
$.post('/LocalClocks/editSelected', { "data[Session][selected]" : selected }, function(data){
alert(data);
});
Controller:
function editSelected()
{
if($this->request->is('post'))
{
if(isset($this->request->data['Session']['selected']))
{
$this->Session->write('selected', $this->request->data['Session']['selected']);
}
}
}
Maybe I'm wrong, but I think you cannot do that directly from the client side using ajax. Can you share the source your statement regarding you can modify the php variable? I googled for that with no luck, and it will be weird to me being able to modify the PHP session.. it would be really insecure, saying you could use Session Fixation/Injection or other malicious techniques
Edited
For assigning the value on a existing variable you need
Make the ajax call
$.post('/LocalClocks/editSelected', { "selected" : selected }, function(data){
alert(data);
});
and on your controller you'll have a function like this
function editSelected($selected){
$_SESSION["selected"] = $selected;
}
and voila

Ajax in Wordpress plugin

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();
}

Resources