I have created a function called hello_alert in theme function.php
I want to load this function using ajax when people click on a button.
Instead of creaating a page for ajax request is it possible to load a PHP function directly using ajax API ?
Please give me a commented code to load a php function using Wordpress ajax API
Example, straight from the Codex (more or less):
add_action( 'wp_footer', 'my_action_javascript' );
function my_action_javascript() {
?>
<script type="text/javascript" >
jQuery(document).ready(function(){
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
jQuery('.my_button').click(function(){
var data = {action: 'my_action'};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
});
</script>
<?php
}
add_action( 'wp_ajax_my_action', 'hello_alert' );
function hello_alert()
{
echo 'Hello';
die();
}
Related
On the orders page in woo-commerce I added a button in the actions row, by click this button i want to make curl call to a web service, the code work well when I hook so_payment_complete function, but my goal now would be to make the call by clicking the button i added on orders page. Any suggestion?
You can use JavaScript code for make an ajax request to your PHP function through wordpress hook wp_ajax and wp_ajax_nopriv.
This is and example
JavaScript code:
$( "#button" ).on( "click", function(e) {
e.preventDefault();
$n.ajax({
type: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: YOUR DATA,
async:true,
success: function(msg){
}
});
});
PHP code:
add_action( 'wp_ajax_action', 'FUNCTION_NAME' );
add_action( 'wp_ajax_nopriv_action', 'FUNCTION_NAME' );
function FUNCTION_NAME() {
//YOUR CURL
}
Let me know.
I am using wordpress version 4.9.8 and PHP 7.1.8.
Below you can see, that I have added a button to my post. This button inserts content into the_content field of a post. After submitting the button I would like to refresh the single post page and show the content.
Find below my code for the button:
add_action('media_buttons', 'add_my_media_button', 99);
function add_my_media_button()
{
$post = $GLOBALS['post_ID'];
echo "<a href='#' id='insert-my-media' data-post-id='{$post}' class='button'>Own content</a>";
}
add_action('wp_ajax_updateContent', 'updateContent');
function updateContent()
{
$post_id = intval($_POST['post_id']);
try {
$sp = new SinglePostContent();
$sp->main($post_id);
} catch (Exception $e) {
echo $e;
}
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action('admin_footer', 'my_media_button_script');
function my_media_button_script()
{
?>
<script>
jQuery(document).ready(function ($) {
$('#insert-my-media').click(function () {
var post_id = $(this).attr('data-post-id');
var data = {
'action': 'updateContent',
'post_id': post_id
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function (response) {
console.log("test12")
console.log(response);
});
});
});
</script>
<?php
}
Any suggestions how to refresh the page and show the content.
Looking forward to your replies!
Change your code like this :
[...]
jQuery.post(ajaxurl, data, function (response) {
console.log("test12")
console.log(response);
window.location.reload();
});
[...]
in callback function, reload the page:
jQuery.post(ajaxurl, data, function (response) {
console.log("test12")
console.log(response);
location.reload();
});
jQuery.post(ajaxurl, data, function (response) {
console.log("test12")
console.log(response);
location.reload(true);
});
use ture in reload to make a hard refresh reload from the server.
or you can return the updated post content and use html() to replace it without a refresh.
I have a variable that is being pulled from a jQuery into php in my functions.php file.
But I'm unable to use it in a page.
When I echo it from functions.php, it appears in the console in chrome, but has a 0 appended..
If I try to echo it in my template page, I get nothing.
Code below.
jQuery
var pie = 131;
$.ajax({
url: ajaxurl, //super global supplied by Wordpress; do not change
type: 'POST',
data: {
action: 'get_post_id', //this is correct
pie : pie
},
success: function (data){
console.log(data);
}
});
functions.php
add_action('wp_head','pluginname_ajaxurl');
function pluginname_ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
add_action( 'wp_ajax_nopriv_get_post_id', 'my_ajax_function' );
add_action( 'wp_ajax_get_post_id', 'my_ajax_function' );
function my_ajax_function() {
$new_pie = isset($_POST['pie']) ? $_POST['pie'] : false;
echo($new_pie);
}
template-page.php
<?php echo($new_pie); ?>
Thanks in advance.
I addressed this in a previous question of yours.
The 0 is being appended to the Ajax call because you need to die() after the echo.
echo $new_pie;
die();
This will stop the 0 from being appended.
As for the return of the data from the AJAX call, you need to do something with it, like append it to an element.
$('#elementID').append(data);
Which in this case, elementID is the ID of an element such as a DIV or P.
sidenote
There's no reason to use the following:
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
Wordpress has created the javascript ajaxurl variable for you and has been doing so since WP 2.8.
Is it possible to send jQuery variable to function.php, and use it in some php function? Via AJAX or probably.
Theme related, not using a plugin.
Eg.
I have some post CSS classes added on 'client side' via jQuery on click.
Can I use this classes on 'server side' so I can pass them in any page of my theme?
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', 'so18550905_enqueue_scripts' );
function so18550905_enqueue_scripts(){
wp_register_script( 'ajaxHandle', get_template_directory() . 'PATH TO YOUR SCRIPT 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', 'so18550905_wp_ajax_function' );
add_action( 'wp_ajax_nopriv_myaction', 'so18550905_wp_ajax_function' );
function so18550905_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.
Yes you can use AJAX to send your jQuery variable. (or any Javascript Variable)
Simply do a JSON.stringify(any-Variable-Here) then you get a corresponding string.
Send the value via AJAX to any php file like:
var toBeSent = JSON.stringify($($('#selector')[0]).attr('class'));
$.ajax({
type: "POST",
url: 'function.php',
data: toBeSent,
success: function(data){ // any action to be performed after function.php returns a value.
},
dataType: 'text'
});
NOTE: I've stringified the items here so that you can access the variables on the server side by doing simple splits.
Sure you can
$('element').click(function(e){
e.preventDefault();
var el = $(this);
//do stuff on click
//send this elements class to the server
$.ajax({
url: "some.php",
data: {
class: el.attr('class')
},
success: function(r){
alert("class name sent successfully to some.php");
}
});
});
another option for you could be $.post()
$(document).ready( function() {
$('#myDiv').click(function(){
var myClass = $(this).attr('class');
var url = 'page.php';
$.post(url, { class: myClass })
.done( function() {
alert('class sent to ' + url);
});
});
});
wonder if anyone can help; I'm trying to implement some ajax through jquery onto a form in a wordpress template.
The jquery is working, and the I can log a console message in the sucess: section, but the data is 0, when it should be calling the php function (at the moment on the same page, and I can call this directly)
so I guess the jquery is working, the admin-ajax is being called, its just the php function is not being called. Any ideas what I could be doing wrong ? I don't fully understand hooks, so perhaps that is an issue - that I need to hook something in somewhere?
jquery (domain would replace comments)
<script type="text/javascript">
jQuery(function ($) {
$( "#movies" ).autocomplete({
minLength:2,
delay:500,
source: function( request, response ) {
$.ajax({
type: 'POST',
url: "http://<!--domain here -->/wp-admin/admin-ajax.php",
dataType: 'json',
data: {
action: 'getMoviesForCode',
searchString: $("#movies").val()
},
success: function( data ) {
response(data);
console.log('jjj'+data);
}
});
}
});
});
</script>
php function (on same page)
<?php
function getMoviesForCode(){
echo "
<script type=\"text/javascript\">
alert(\"hh\");
</script>
";
$searchString = $_POST['searchString'];
$results = va_getMoviesForCode($searchString);
$results = json_encode($results);
die($results);
}
?>
Thanks,
You're doing it wrong. You php function should be in your theme's functions.php file.
You should then hook the function to wp_ajax_[your_action] and wp_ajax_nopriv_[your_action].
Example of what should be in your functions.php :
function getMoviesForCode(){
echo "
<script type=\"text/javascript\">
alert(\"hh\");
</script>
";
$searchString = $_POST['searchString'];
$results = va_getMoviesForCode($searchString);
$results = json_encode($results);
die($results);
}
add_action('wp_ajax_getMoviesForCode', 'getMoviesForCode');
add_action('wp_ajax_nopriv_getMoviesForCode', 'getMoviesForCode');