Shortcode not working in Wordpress AJAX - ajax

I am trying to use a shortcode from Ultimate Facebook plugin to display a FB connect button in an AJAX popup and can't seem to get it work properly. I searched and used the solution given by djb in this question - Why might a plugin's 'do_shortcode' not work in an AJAX request?, but it worked only partially. Ideally, I want a user to be able to sign in using FB and then save the list to her account. I want to use the plugin instead of embedding direct code because creates a new user in wordpress too when someone uses FB connect.
Procedure to reproduce issue -
Go to http://www.ajaymreddy.com/stg/country/india/#
Click on Start
Select any of checboxes - take care to not click on the text against
the checkboxes
Click on Save button in the popup If you are not logged in, the fb
connect button should show up. However, only the shortcode text is
currently showing up.
Code in functions.php -
//From http://wordpress.stackexchange.com/questions/53309/why-might-a-plugins-do-shortcode-not-work-in-an-ajax-request
add_action( 'init', function() {
ps_register_shortcode_ajax( 'show_fblogin', 'show_fblogin' );
} );
function ps_register_shortcode_ajax( $callable, $action ) {
if ( empty( $_POST['action'] ) || $_POST['action'] != $action )
return;
call_user_func( $callable );
}
function show_fblogin(){
if (!is_user_logged_in())
echo do_shortcode('[wdfb_connect]');
die ();
}
add_action( 'wp_ajax_show_fblogin', 'show_fblogin' );
add_action( 'wp_ajax_nopriv_show_fblogin', 'show_fblogin' );
Code in ajax file -
$(document).on( 'click', '#saveBtn', function (){
if (myAjax.loggedin==1)
{
jQuery.ajax({
type: 'POST',
url: myAjax.ajaxurl,
data: {
action: 'save_whslist',
selected: selected.toString(),
whsNonce: myAjax.selectNonce,
},
success: function(data, textStatus, XMLHttpRequest){
selected = [];
modal.close();
$("input.whsites").prop('disabled', true);
$("input.whsites").prop('checked', false);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown+' fail');
}
});
}
else
{
jQuery.ajax({
type: 'POST',
url: myAjax.ajaxurl,
data: {
action: 'show_fblogin',
selected: selected.toString(),
whsNonce: myAjax.selectNonce,
},
success: function(data, textStatus, XMLHttpRequest){
modal.open({content: "<p>Please login to save your travel list<br /><span>No auto posts on your wall!</span></p>"+data});
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown+' fail');
}
});
}
});

Adding the solution for posterity -
I solved it by adding FB.XFBML.parse(); once the AJAX call returned succesfully. Hope this helps.

Related

How to get latest records without page refresh using Codeigniter and Websocket

Hello I have one registration form of users as soon as user register in next browser tab i will get that registered user details without page refresh for this i got code from github project and tested that which is working perfectly and I have loaded jquery,socket.js file in both pages (data post,retrieving page)as they mentioned in that still i am not getting latest registered users without page refresh ,so please tell me where the code need to be correct.below is my code
code to post data(register users)
$("#submit").click(function(event){
event.preventDefault();
var dataString = {
name : $("#name").val(),
email : $("#wickets").val()
};
$.ajax({
url: "<?= base_url('User/register') ?>",
type: "POST",
data: dataString,
dataType: "json",
cache : false,
success: function (data) {
if (data.success == true) {
var socket = io.connect( 'http://'+window.location.hostname +':3000' );
socket.emit('registered_users', {
name: data.name,
email: data.email
});
}
}, error: function (xhr, status, error) {
alert(error);
},
});
});
code to get name and email of user who have just register by socket
html div tags to print user name and email
<div id="user_name"></div>
<div id="user_email"></div>
script for socket
var socket = io.connect( 'http://'+window.location.hostname+':3000' );
socket.on( 'registered_users', function( data ) {
$( "#user_name" ).prepend( data.name );
$( "#user_email" ).prepend( data.email );
});

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/

Wordpress wp_ajax public url?

I would like to do an ajax request in my theme.
If I am login to the Back Office, the request does, but if I'm not logged in, the returns is null... What's the solution please ?
In my view :
$.ajax({
type: "POST",
url: 'http://www.mysite.com/wp-admin/admin-ajax.php',
data: $('#EventForm').serialize()+'&action=event_form',
success: function(response){
if(response == 1){
alert('ok');
} else {
alert('no ok');
}
});
In the functions.php (works only if I am log in back Office)
add_action('wp_ajax_event_form', 'ajax_event_form');
function ajax_event_form(){
global $wpdb;
...
echo true;
die;
}
From the Codex: 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_callback');
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');
Create a plugin and add this:
<?php
/*
* Plugin Name:ajax
*/
function my_ajax_callback_function() {
echo "hiii";
print_r($_POST);
exit();
}
add_action( 'wp_ajax_my_action_name', 'my_ajax_callback_function' );
// If called from admin panel
add_action( 'wp_ajax_nopriv_my_action_name', 'my_ajax_callback_function' );
Create a js and add this:
(function($) {
$(document).ready(function(e) {
$.ajax({
url: "<?php echo admin_url('admin-ajax.php'); ?>",
type: 'POST',
data: {
action: "my_action_name","name":"hithin","age":"27"
},
success: function (data, textStatus, jqXHR) {
console.log(data);
}
});
}
})(jQuery);
The ajax request in WordPress works by classifying user in two categories
1) User with login privilege.
2) User without login privileges.
So if you are logged in(even as a subscriber) your ajax function will be triggered i.e.
add_action('wp_ajax_event_form', 'ajax_event_form');
this will call 'ajax_event_form' function.
To make this work for non-logged in users you will have to write this below your ajax action
add_action('wp_ajax_nopriv_event_form', 'ajax_event_form');
So your code will be like:
add_action('wp_ajax_event_form', 'ajax_event_form');
add_action('wp_ajax_nopriv_event_form', 'ajax_event_form');
function ajax_event_form(){
global $wpdb;
...
echo true;
die;
}

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

Getting wordpress to play nice with 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();
}
}

Resources