ajax in wordpress not calling php function - php

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

Related

Calling a PHP function from same PHP file throught AJAX

I am trying to call php function through Ajax in same php file.
User enter voucher_id then call ajax that ajax call php function that function is in same file.
How to call that function.
function of PHP code:-
function voucherExist($voucherNo, $sCID, $type){
global $pncon;
$uRow = $pncon->query("SELECT * FROM transactions WHERE voucher_no = '{$voucherNo}' AND company_ID = '{$sCID}' AND type = '{$type}'");
return $uRow;
}
Ajax code:-
<script type="text/javascript">
$(document).ready(function (){
$('#voucher_no').on('change', function () {
var voucher_no = $('#voucher_no').val();
$.ajax({
url: "bankVoucherAddEdit.php",
type: "post",
data: "voucherNo"
});
});
});
</script>
You can get an idea from the below:
<? php
function yourFunction($data){
return $data;
}
if (isset($_POST['voucherNo'])) {
echo yourFunction($_POST['voucherNo']);
}
?>
<script>
$.ajax({
url: 'bankVoucherAddEdit.php',
type: 'post',
data: { "voucherNo": voucher_no },
success: function(response) { console.log(response); }
});
</script>
The thing is that you cannot directly call a PHP function from JS. You can achieve this by RESTful API. They are quite simpler and Standard.
In your case, Send any post value as a flag from JS to PHP, if that POST value exists then call PHP function

Wordpress Plugin Ajax get Javascript Array Data into PHP Variable

function my_action_javascript($val1, $val2) {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
'email': '<?php echo $val1?>',
'password': '<?php echo $val2?>'
};
jQuery.post({
url: 'dummyurl',
method: "POST",
data: data,
success: function (data) {
console.log(data);
}
})
});
</script>
<?php
}
I got this function in my Wordpress Plugin. I parse in some data in the function and then i do a ajax request in Javascript. That all works just fine and i get the data array as response.
The Question is, how do i get the data from the Array in Javascript into my Variable in PHP so i can put the Data into my Wordpress Options?
Try this.
you need to parse the response.
function my_action_javascript($val1, $val2) {
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
'email': '<?php echo $val1?>',
'password': '<?php echo $val2?>'
};
jQuery.post({
url: 'dummyurl',
method: "POST",
data: data,
success: function (data) {
console.log(data);
var obj = jQuery.parseJSON( data);
console.log(obj.somedata);
}
})
});
</script>
<?php
}
You need to have a PHP script that gets called by the AJAX request that will write the data into your options table. There's a specific way of doing this with Wordpress: https://codex.wordpress.org/AJAX_in_Plugins
In a nutshell, you need to add an action parameter to your POST data and then hook your PHP callback function to this parameter. In your callback, you can then use update_option().

Using variables defined in functions.php WORDPRESS

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.

WordPress API - how to load a function using ajax

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

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