Wordpress wp_ajax public url? - ajax

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

Related

Redirect to another view using AJAX call in Codeigniter

My table contains many rows from database. After clicking edit button in a row, I want to redirect it to another page. I am able get the data, but it cannot redirect to the other page.
I'm using bootstrap template, so there are different file to load on view. I do not know how to load view that consist of more than one files.
Ajax
$('#example2').on('click','#edit',function(){
var id_per = $(this).closest('tr').attr('id');
alert("ini"+id_per);
$.ajax({
url:"<?php echo base_url('c_dokter/ubahdt_perawatan/');?>" + id_per,
type:"POST",
data:{
id_perawatan : id_per,
id_pasien : id_pasien
},
dataType:'JSON',
success:function(data) {
},
error:function() {
alert('error ... ');
}
});
Controller
public function ubahdt_perawatan($id_perawatan){
$data['pasien']=$this->m_pasien->spes_Perawatan($id_perawatan);
if ($this->input->is_ajax_request()) {
echo json_encode($data);
exit;
}
$data['pasien']=$this->m_pasien->DataPerPasien($id_pasien)->result();
$data['sidebar']='member/dokter/sidebar_psn';
$data['content']='member/dokter/edit_perawatan';
$this->load->view('member/dokter/main',$data);
}
Edited answer:
public function ubahdt_perawatan($id_perawatan){
$data['pasien']=$this->m_pasien->spes_Perawatan($id_perawatan);
if ($this->input->is_ajax_request())
{
echo json_encode($data);
}
}
public function test()
{
$id_pasien=$this->uri->segment(2);
$data['pasien']=$this->m_pasien->DataPerPasien($id_pasien)->result();
$this->load->view('member/dokter/sidebar_psn');
$this->load->view('member/dokter/edit_perawatan');
$this->load->view('member/dokter/main',$data);
}
set path to test() in routes.php..
$route['test/(:any)']='controller/test';
then in ajax success function
success:function(data){
window.location.href="<?php echo site_url('test/'.data);";
},
try it.

Shortcode not working in Wordpress 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.

jQuery AJAX form submit error working success not

EDIT
Ok, so I can login fine but when I enter false info I'm redirected to the login page, what I need is to stay on the same page and show the error message e.preventDefault(); doesn't seem to work.
$(function() {
$("#login-form").submit(function(e) {
$('.fail').hide();
$.ajax({
url:"/login",
type: "post",
data: $(this).serialize(),
error:function(){
$('.fail').show();
e.preventDefault();
},
success: function(){
document.location = '/';
}
});
return false;
});
});
Your not actually doing anything with the form, ill try commenting your code to talk you through whats happening.
I'm guessing your using PHP server side for this code.
In PHP you want to check the user credentials and then tell the browser. If the login was successful send back "y", and if it failed "n".
<script type="text/javascript">
$(function() {
$("#login-form").submit(function() {
$('.fail').hide();
$.ajax({
url:"/login",
type: "post",
data: $(this).serialize(),
error:function(){
$('.fail').show();
},
success: function(data) {
if (data == "y") {
//Login was successful. Redirect statement here?
} else {
//Failed login message here
}
}
});
return false;
});
});
</script>
Edit
Try adding this in your success function. Please let me know what you get for a successful login and a failed login.
success: function(data) {
console.log(data);
}
Edit 2
This is because your ajax call is successful, just that the login failed. This is why your success handler is called.
To sort this you'll need to see what is being returned from the server, is it nothing? In which case try:
success: function(data) {
if (data == "") {
e.preventDefault();
} else {
//Login successful, redirect user.
}
}
You should add:
success: function(data){
/* Validation data here, if authentication answer is correct */
if(data == 'ok')
document.location = '/';
else
/* show error here */
}
the success occur when URL is found and accessible.
and error occur when URL is not found.
if you want check the callback MSG you must print it in the URL page & check data in success.
like this:
<script type="text/javascript">
$(function() {
$("#login-form").submit(function() {
$('.fail').hide();
$.ajax({
url:"/login",
type: "post",
data: $(this).serialize(),
success:function(data){
if(data=="true"){
alert("success");
}else{
alert("faild")
}
}
});
return false;
});
});
</script>
in login.php
<?php
//check if for true...
echo "true";
//and if it is not true...
echo "false";
?>
the data parameter in success is a string which get back the html content of "/login"

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