Ajax in Wordpress plugin - ajax

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

Related

Admin ajax in wordpress is not working

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.

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/

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...");

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"

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