Ajax function call to php function - php

I have a simple php function as below defined in one of my php file
add_action('wp_ajax_test','test');
add_action('wp_ajax_nopriv_test','test');
function test(){
echo "Hello";
}
I am calling above "test" function using below ajax function call
jQuery(document).ready(function(){
jQuery('#prev_button_id').click(function(){
jQuery.post(
myAjax.ajaxurl,
{
action:"test",
success: (response)=>{
console.log('Success:'+ response);
},
error:(response)=>{
console.log('Failure:'+ response);
}
});
});
});
I am expecting console output of "Hello" but I getting below undefined response
Success:undefined
Failure:undefined

jQuery(document).ready(function(){
jQuery('#prev_button_id').click(function(){
var params = {action:"test"}
jQuery.post(myAjax.ajaxurl,params,function(data){
if( data ){
console.log ( data );
}
});
});
});
add_action( 'wp_ajax_test','test' );
add_action( 'wp_ajax_nopriv_test','test' );
function test() {
echo "Hello";
die;
}
Try this code and don't forget to die after AJAX call also
make sure you are getting proper AJAX URL in myAjax.ajaxurl

I followed the below video, step by step and it worked.
Probably it had something to do with nonce
AJAX in WordPress using admin-ajax.php

Related

Ajax call to PHP action/function with array as data (in wordpress)

I'm trying to push an array from jquery to a php function and I'm out of options to make it work. I've tried multiple options; $_request, $_post, with JSON.stringify, without JSON.stringify, ...
But I keep getting 'null'; can't figure out the right combination. Someone who's willing to explain me why it's not working and how to fix?
JQuery code:
var userIDs = [];
$( "tr.user-row" ).each(function() {
var userID = $(this).attr("data-userid");
userIDs.push(userID);
});
var jsonIDs = JSON.stringify(userIDs);
$.ajax({
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'built_ranking', // This is our PHP function below
'data' : {data:jsonIDs},
},
dataType:"json",
success:function(data){
// This outputs the result of the ajax request (The Callback)
//$("tr[data-userid='"+userID+"'] td.punten").html(data.punten);
//$("tr[data-userid='"+userID+"'] td.afstand").html(data.afstand);
console.log(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
PHP code:
function built_ranking(){
if ( isset($_REQUEST) ) {
$data = json_decode(stripslashes($_REQUEST['data']));
foreach($data as $d){
echo $d;
}
print json_encode($data);
//$testResult = array("points"=>"test", "afstand"=>"test");
//print json_encode($testResult);
}
// Always die in functions echoing AJAX content
die();
}
add_action( 'wp_ajax_built_ranking', 'built_ranking' );
If I print the $testResult it returns the array and I can use the data back in jquery, so the function is called.
I've based the code on Send array with Ajax to PHP script
I've multiple ajax calls with $_request instead of $_post and they are working fine. But maybe they can't handle arrays? I've no idea... ^^
What I learned from this question and the help I got: don't guess, debug. try to find ways to see what is posted, what is received, ...
You can read how to 'debug' in the comments of the original question. Useful for starters as me ;)
Working code:
JQuery
var jsonIDs = JSON.stringify(userIDs);
$.ajax({
type: 'POST',
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'built_ranking', // This is our PHP function below
'data' : jsonIDs,
},
dataType:"json",
success:function(data){
// This outputs the result of the ajax request (The Callback)
//$("tr[data-userid='"+userID+"'] td.punten").html(data.punten);
//$("tr[data-userid='"+userID+"'] td.afstand").html(data.afstand);
console.log(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
PHP
function built_ranking(){
if ( isset($_POST) ) {
$data = json_decode(stripslashes($_POST['data']));
print json_encode($data);
//$testResult = array("points"=>"test", "afstand"=>"test");
//print json_encode($testResult);
}
// Always die in functions echoing AJAX content
die();
}
add_action( 'wp_ajax_built_ranking', 'built_ranking' );

Wordpress Ajax Request returns 0 in chrome, works fine in FF

I have a front-end Ajax call set up to randomize an image whenever a button is pressed. I set it up as follows:
Functions.php
define("AJAX_URL", admin_url('admin-ajax.php'));
add_action("wp_enqueue_scripts", "enqueue_eyewebz_scripts");
function enqueue_eyewebz_scripts()
{
wp_enqueue_script("jquery");
...
wp_enqueue_script("root-js", JS_URL . "/root.js", array("jquery"));
$script_params = array(
'ajax_url' => AJAX_URL
);
wp_localize_script('root-js', 'theme_vars', $script_params);
}
root.js
function parallax_randomize(e)
{
var data = {
'action': 'randomize_parallax',
'dataType': 'json'
};
console.log(theme_vars.ajax_url);
jQuery.post(theme_vars.ajax_url, data, function(response) {
console.log(response);
var dynb = JSON.parse(response);
jQuery('#front-location span').html(dynb.location);
jQuery('.parallax-slider').fadeOut('fast', function () {
jQuery('.parallax-slider').attr('src', dynb.url);
jQuery('.parallax-slider').fadeIn('fast');
});
});
}
Dynamic background callback
class Dynb
{
function Dynb()
{
...
$this->set_up_ajax();
...
}
public function set_up_ajax()
{
add_action('wp_ajax_randomize_parallax', array($this, 'randomize_parallax'));
}
public function randomize_parallax()
{
$data = set_dynamic_background(true);
echo json_encode($data);
wp_die();
}
}
new Dynb();
In Firefox, this works just fine, but in Chrome, my JS Ajax call returns 0. I can't for the life of me figure out what the problem is. Anyone?
just add exit() in randomize_parallax() function,i think it will fix your issue
When sending an ajax request from the front-end, you need to include an action that has wp_ajax_nopriv_ ... (shown below) if you want this to work. If you don't add that action, users that are not logged in will not be able to call for the ajax function.
add_action('wp_ajax_nopriv_randomize_parallax', array($this, 'randomize_parallax'));

Inserting Option via AJAX using Settings API

I am making a plugin and need to insert a value using the 'add_option()' function - or something that achieves the same result.
This is what I use to call my AJAX:
// localize script
wp_localize_script('button-js', 'the_ajax_script', array('ajaxurl' => admin_url('admin-ajax.php')));
And what launches the PHP function:
add_action('wp_ajax_process_form', array($this, 'process_ajax'));
I need to run add_option() in the function called after my AJAX runs (my AJAX code below):
function post(num) {
var data = {
action : 'process_form',
form_number : num
};
$.post(the_ajax_script.ajaxurl, data).error(
function() {
alert('error');
}).success(function() {
console.log(data);
});
return false;
}
And here is the function that is run by AJAX:
public function process_ajax() {
$num = $_POST['form_number'];
if(isset($num)) {
add_option('form-num', $num);
}
die();
}
My AJAX code runs successfully, and the correct values are logged to the console - however upon using
<?php echo get_option('form_num'); ?>
The value is blank.

How to post data using Angular

i am unable to get posted data on sever using php it returns
Output : Array()
Php Code
public function create()
{
print_r($_POST);
}
Angular Code
angular.module('index',[])
.controller('SignUpController', ['$scope','$http', function($scope,$http) {
$scope.signup=function(user){
var dataObj = {
"name" : "sdadas",
"employees" : "sadsad",
"headoffice" : "sadsa"
};
$http.post("<?=base_url()."index.php/users/create" ?>",dataObj).
success(function(data,status,header,config){
alert(data);
}).
error(function(data,status,header,config){
});
};
}]);
i dont know what base url is but i guess it's a function so i rewrote it from this
$http.post("<?=base_url()."index.php/users/create" ?>",dataObj).
success(function(data,status,header,config){
alert(data);
}).
To this u should put it between single quotes
$http.post('<? echo base_url()."index.php/users/create"; ?>',dataObj).
success(function(data,status,header,config){
alert(data);
}).
public function create()
{
print_r(json_decode(file_get_contents("php://input")));
}

Wordpress: how to call a plugin function with an ajax call?

I'm writing a Wordpress MU plugin, it includes a link with each post and I want to use ajax to call one of the plugin functions when the user clicks on this link, and then dynamically update the link-text with output from that function.
I'm stuck with the ajax query. I've got this complicated, clearly hack-ish, way to do it, but it is not quite working. What is the 'correct' or 'wordpress' way to include ajax functionality in a plugin?
(My current hack code is below. When I click the generate link I don't get the same output I get in the wp page as when I go directly to sample-ajax.php in my browser.)
I've got my code[1] set up as follows:
mu-plugins/sample.php:
<?php
/*
Plugin Name: Sample Plugin
*/
if (!class_exists("SamplePlugin")) {
class SamplePlugin {
function SamplePlugin() {}
function addHeaderCode() {
echo '<link type="text/css" rel="stylesheet" href="'.get_bloginfo('wpurl').
'/wp-content/mu-plugins/sample/sample.css" />\n';
wp_enqueue_script('sample-ajax', get_bloginfo('wpurl') .
'/wp-content/mu-plugins/sample/sample-ajax.js.php',
array('jquery'), '1.0');
}
// adds the link to post content.
function addLink($content = '') {
$content .= "<span class='foobar clicked'><a href='#'>click</a></span>";
return $content;
}
function doAjax() { //
echo "<a href='#'>AJAX!</a>";
}
}
}
if (class_exists("SamplePlugin")) {
$sample_plugin = new SamplePlugin();
}
if (isset($sample_plugin)) {
add_action('wp_head',array(&$sample_plugin,'addHeaderCode'),1);
add_filter('the_content', array(&$sample_plugin, 'addLink'));
}
mu-plugins/sample/sample-ajax.js.php:
<?php
if (!function_exists('add_action')) {
require_once("../../../wp-config.php");
}
?>
jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
var aref = this;
jQuery(this).toggleClass('clicked');
jQuery.ajax({
url: "http://mysite/wp-content/mu-plugins/sample/sample-ajax.php",
success: function(value) {
jQuery(aref).html(value);
}
});
});
});
mu-plugins/sample/sample-ajax.php:
<?php
if (!function_exists('add_action')) {
require_once("../../../wp-config.php");
}
if (isset($sample_plugin)) {
$sample_plugin->doAjax();
} else {
echo "unset";
}
?>
[1] Note: The following tutorial got me this far, but I'm stumped at this point.
http://www.devlounge.net/articles/using-ajax-with-your-wordpress-plugin
TheDeadMedic is not quite right. WordPress has built in AJAX capabilities. Send your ajax request to /wp-admin/admin-ajax.php using POST with the argument 'action':
jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
jQuery(this).toggleClass('clicked');
jQuery.ajax({
type:'POST',
data:{action:'my_unique_action'},
url: "http://mysite/wp-admin/admin-ajax.php",
success: function(value) {
jQuery(this).html(value);
}
});
});
});
Then hook it in the plugin like this if you only want it to work for logged in users:
add_action('wp_ajax_my_unique_action',array($sample_plugin,'doAjax'));
or hook it like this to work only for non-logged in users:
add_action('wp_ajax_nopriv_my_unique_action',array($sample_plugin,'doAjax'));
Use both if you want it to work for everybody.
admin-ajax.php uses some action names already, so make sure you look through the file and don't use the same action names, or else you'll accidentally try to do things like delete comments, etc.
EDIT
Sorry, I didn't quite understand the question. I thought you were asking how to do an ajax request. Anyway, two things I'd try:
First, have your function echo just the word AJAX without the a tag. Next, try changing your ajax call so it has both a success and a complete callback:
jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
var val = '';
jQuery(this).toggleClass('clicked');
jQuery.ajax({
type:'POST',
data:{action:'my_unique_action'},
url: "http://mysite/wp-admin/admin-ajax.php",
success: function(value) {
val = value;
},
complete: function(){
jQuery(this).html(val);
}
});
});
});
WordPress environment
First of all, in order to achieve this task, it's recommended to register then enqueue a jQuery script that will push the request to the server. These operations will be hooked in wp_enqueue_scripts action hook. In the same hook you should put wp_localize_script that it's used to include arbitrary Javascript. By this way there will be a JS object available in front end. This object carries on the correct url to be used by the jQuery handle.
Please take a look to:
wp_register_script(); function
wp_enqueue_scripts hook
wp_enqueue_script(); function
wp_localize_script(); function
File: functions.php 1/2
add_action( 'wp_enqueue_scripts', 'so_enqueue_scripts' );
function so_enqueue_scripts(){
wp_register_script( 'ajaxHandle', get_template_directory() . 'PATH TO YOUR JS FILE', array(), false, true );
wp_enqueue_script( 'ajaxHandle' );
wp_localize_script( 'ajaxHandle', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
File: jquery.ajax.js
This file makes the ajax call.
jQuery(document).ready( function($){
//Some event will trigger the ajax call, you can push whatever data to the server, simply passing it to the "data" object in ajax call
$.ajax({
url: ajax_object.ajaxurl, // this is the object instantiated in wp_localize_script function
type: 'POST',
data:{
action: 'myaction', // this is the function in your functions.php that will be triggered
name: 'John',
age: '38'
},
success: function( data ){
//Do something with the result from server
console.log( data );
}
});
});
File: functions.php 2/2
Finally on your functions.php file there should be the function triggered by your ajax call.
Remember the suffixes:
wp_ajax ( allow the function only for registered users or admin panel operations )
wp_ajax_nopriv ( allow the function for no privilege users )
These suffixes plus the action compose the name of your action:
wp_ajax_myaction or wp_ajax_nopriv_myaction
add_action( 'wp_ajax_myaction', 'so_wp_ajax_function' );
add_action( 'wp_ajax_nopriv_myaction', 'so_wp_ajax_function' );
function so_wp_ajax_function(){
//DO whatever you want with data posted
//To send back a response you have to echo the result!
echo $_POST['name'];
echo $_POST['age'];
wp_die(); // ajax call must die to avoid trailing 0 in your response
}
Hope it helps!
Let me know if something is not clear.
Just to add an information.
If you want to receive an object from a php class method function :
js file
jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
var data = {
'action': 'getAllOptionsByAjax',
'arg1': 'val1',
'arg2': $(this).val()
};
jQuery.post( ajaxurl, data, function(response) {
var jsonObj = JSON.parse( response );
});
});
php file
public static function getAllOptionsByAjax(){
global $wpdb;
// Start query string
$query_string = "SELECT * FROM wp_your_table WHERE col1='" . $_POST['arg1'] . "' AND col2 = '" . $_POST['arg2'] . "' ";
// Return results
$a_options = $wpdb->get_results( $query_string, ARRAY_A );
$f_options = array();
$f_options[null] = __( 'Please select an item', 'my_domain' );
foreach ($a_options as $option){
$f_options [$option['id']] = $option['name'];
}
$json = json_encode( $f_options );
echo $json;
wp_die();
}

Categories