Using variables defined in functions.php WORDPRESS - php

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.

Related

Wordpress make Ajax call to my theme

This is my situation: I have a slide, like the image below, that needs to be responsive. This slide was created from scratch and its working fine, however it's not responsive.
In order to be responsive I need to know the width of the screen of the user so instead of showing 4 slides, I show 3, 2 and 1 (if its a phone).
With that said, I need my slider to be loaded through ajax and I will pass through params the user screen width.
My theme folder is structured this way:
wp-contents/themes/my-theme
...functions.php
...header.php
...footer.php
...index.php
...single.php
I need to make a Ajax call to functions.php to a function that I have created. So I added the following:
add_action('wp_ajax_posts_list', 'my_ajax_posts_list_handler');
function my_ajax_posts_list_handler()
{
echo 'hello, width: ' . $_POST['width'];
wp_die();
}
In the footer.php file I added some testing javascript code:
$(function()
{
var width = $(window).width();
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>'; // Dunno what is this..
$.ajax(
{
url: ajaxurl,
data:
{
action: 'wp_ajax_posts_list',
width: width
},
type: 'GET',
success: function(response)
{
console.log(response);
}
});
});
My problems:
The URL being executed is this http://localhost/wordpress/wp-admin/admin-ajax.php?action=wp_ajax_posts_list
The URL response code is 400
The URL responde value is '0'
The action is actually called post_list. wp_ajax_ is just a prefix. You also should add the same action with prefix wp_ajax_nopriv_ otherwise it wil not work when you are logged out. I also see you do type: 'GET' in your javascript but use $_POST in your PHP. Do one of the two.
add_action('wp_ajax_posts_list', 'my_ajax_posts_list_handler');
add_action('wp_ajax_nopriv_posts_list', 'my_ajax_posts_list_handler');
function my_ajax_posts_list_handler()
{
echo 'hello, width: ' . $_POST['width'];
wp_die();
}
Here the JS:
<script>
$( function () {
var width = $( window ).width();
// var ajaxurl = "http://localhost/wordpress/wp-admin/admin-ajax.php"
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
$.ajax( {
url: ajaxurl,
data: {
action: 'posts_list',
width: width
},
type: 'POST',
success: function ( response ) {
console.log( response );
}
} );
} );
</script>

Get div content value during print post data?

I am new to wordpress and php and I want to get div content data when I print_r($_POST)
I used add_action( 'save_post', 'wpse_save_meta_fields' ); wordpress hook to save data or update data.
When I do print_r($_POST) I get all things except selected_element_all div content.
How could I get data or resolve this ?
jquery code ( for get data from another file)
jQuery(document).ready(function() {
var postid = "<?php echo $post_id;?>";
jQuery("#sel_all_mmy").click(function() {
jQuery.ajax({
data: {
'post_id': postid
},
type: 'POST',
datatype: 'json',
url: "<?php echo get_template_directory_uri();?>/get_all_make_model.php?",
success: function(data) {
jQuery(".selected_element_all").append(data);
}
});
});
});
HTML Div where i append data
<div class="selected_element_all" style="font-size:15px"> </div>
And finally PHP code i used
<?php
function wpse_save_meta_fields( $post_id ) {
global $wpdb;
echo "<pre>";
print_r($_POST);
exit();
}
add_action( 'save_post', 'wpse_save_meta_fields' );
?>
Try like this way
take a input hidden field in your div just like
<input type=hidden name="my_val" class="my_val" value=""> </div>
then use it in your jquery script like
jQuery(document).ready(function(){
var postid ="<?php echo $post_id;?>";
jQuery("#sel_all_mmy").click(function(){
jQuery.ajax({
data:{'post_id':postid},
type:'POST',
datatype: 'json',
url: "<?php echo get_template_directory_uri();?>/get_all_make_model.php?",
success: function(data){
jQuery(".selected_element_all").data(data);
jQuery(".my_val").val(data);
}
});
});
});
And print_r that value in your PHP function like
print_r($_POST['my_val']);
I hope it's working.

jQuery external function needs some PHP values

In my external JavaScript file, I have the following jQuery code:
$(function(){
$('#follow').on('click',function(){
$.ajax({
type: 'POST',
url : 'functions/follow.php',
data: {follower : session_id,
user : p_id,
success: function(result) {
if(result == 'followed'){
$('#follow').attr('id','unfollow').text('-Unfollow');
}
}
});
});
});
On my normal page, I have this:
var session_id = '<?php echo $_SESSION['id']; ?>',
p_id = '<?php echo $p_id; ?>';
but this is not passing the variables into the jQuery function. I have these two variables being set before the JavaScript file is being called, also.
EDIT: I have tested this with the function on the same page as where the button is, and I passed in the PHP values with an echo, and it worked then.
You can create a namespace in the jquery object allowing access to it even inside events. Like so:
$.mynamespace = {
session_id: '<?php echo $_SESSION['id']; ?>',
p_id: '<?php echo $p_id; ?>'
};
Then reference those namespace vars in your code like so:
$(function(){
$('#follow').on('click',function(){
$.ajax({
type: 'POST',
url : 'functions/follow.php',
data: {follower : $.mynamespace.session_id,
user : $.mynamespace.p_id,
success: function(result) {
if(result == 'followed'){
$('#follow').attr('id','unfollow').text('-Unfollow');
}
}
});
});
});
This will also make them available for any other jQuery events/callbacks etc
(NB: Make sure your variables are being set before you try to use them, i.e. higher in the script)

ajax in wordpress not calling php function

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');

How do I get a $_POST value in a PHP file using Javascript and AJAX?

UPDATE 2/28/2012: This question has a solution at the end of it, thanks to #charlietfl.
I have a form and an AJAX call within some JQuery script, and the AJAX appears to be executing successfully, however, the $_POST variable in the PHP file is still empty. Not sure what I'm doing wrong. My code is commented below.
The main question concerns the PHP file. Why is the PHP $_POST variable not set to 'yes? If I do a var_dump, it consistently shows NULL. However, I believe I am manually setting 'removeall' to an arbitrary value, in this case 'yes', using the typical AJAX method. Shouldn't the PHP file be picking up the $_POST variable with a label of 'removeall' as being set to 'yes'?
I hope whatever I'm doing wrong will be completely obvious to someone.
Javascript:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('tr.assoc_row').show();
$('#settings-removed-msg').hide();
$('#new-assoc-msg').hide();
$('#formdeleteassoc').submit(function(e){
e.preventDefault(); //This is working to prevent normal submission of the form.
$.ajax ({
type: 'POST',
url: '<?php echo $cb_t2c_remove_all_url; ?>', //I have checked this to make sure it is the correct url for the PHP file.
data: {removeall: 'yes' //This is the data that is NOT getting passed to the PHP file.
},
success: function() {
$('#settings-removed-msg').fadeIn('fast'); //This gets triggered.
$('tr.assoc_row').fadeOut('fast'); //This gets triggered
}
});
});
});
PHP Code:
<?php
//remove_all.php
global $wpdb;
$prefix = $wpdb->prefix;
$remove_var_dump = $_POST['removeall']; //returning NULL
var_dump($remove_var_dump); //returning NULL
if ( $_POST['removeall'] == 'yes' ) {
echo 'This was set to yes, everything is working.';
}
else {
echo 'This was not set to yes, it is still not working.';
}
?>
Solution:
/*
JQUERY action processed by AJAX
*/
add_action('init', 'cb_t2c_action_javascript');
function cb_t2c_action_javascript() {
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
$('tr.assoc_row').show();
$('#settings-removed-msg').hide();
$('#new-assoc-msg').hide();
$('#formdeleteassoc').submit(function(e){
e.preventDefault(); //Works to prevent normal submission of the form.
var data = {
action: 'cb_t2c_ajax_action',
removeall: 'yes'
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
$.ajax ({
type: 'POST',
url: ajaxurl,
data: data,
success: function() {
$('#settings-removed-msg').fadeIn('fast'); //Working now
$('tr.assoc_row').fadeOut('fast'); //Working now
}
});
$('#formsavesettings').submit(function(){
$('#new-assoc-msg').fadeIn('fast'); //Working now
});
});
});
</script>
<?php
}
//Add the action to process the AJAX.
add_action('wp_ajax_cb_t2c_ajax_action', 'cb_t2c_action_callback');
add_action('wp_ajax_nopriv_cb_t2c_ajax_action', 'cb_t2c_action_callback');
function cb_t2c_action_callback() {
global $wpdb; // this is how you get access to the database
$prefix = $wpdb->prefix;
$remove_var_dump = $_POST['removeall']; //returning NULL
var_dump($remove_var_dump);
$removeall = $_POST['removeall'];
if ( isset($removeall) ){
$wpdb->query("DELETE FROM wp_cb_tags2cats");
}
die(); // this is required to return a proper result
}
try setting this:
var data = 'removeall=yes';
and setting this in your $.ajax({})
data: data,
and see if this does the trick.
I have modify your ajax function please try it.
jQuery.ajax({
type:"GET",
cache:false,
url:'display_alert_msg.php',
data: 'removeall=yes',
success:function(html){
$('#settings-removed-msg').fadeIn('fast'); //This gets triggered.
$('tr.assoc_row').fadeOut('fast'); //This gets triggered
}
});

Categories