WP ajax response is empty for $_POST value - php

I am trying to echo the posted value of an input field via WP ajax, but it keeps returning empty (i.e. no $_POST content), why? If I try to echo 'test', it works.
functions.php:
add_action('wp_footer', 'ajx_action_subscriber');
function ajx_action_subscriber() {
?>
<script type="text/javascript">
jQuery( document ).on( 'click', '#subscribe-submit', function() {
var subscribe_email = $('#footer-email').val();
$('#subscribe-confirmation').html('Registering');
jQuery.ajax({
url : '<?php echo esc_url( home_url() ); ?>/wp-admin/admin-ajax.php',
type : 'post',
data : {action:'subscribe_user', subscribe_email:subscribe_email},
success : function( response ) {
$('#subscribe-confirmation').html(response);
}
});
});
</script>
<?php
}
add_action('wp_ajax_subscribe_user', 'subscribe_user');
function subscribe_user() {
echo $_POST['subscribe_email'];
// echo 'test'; // works successfully ?!!?
die();
}

Related

Use Woocommerce session variable whitout reload

I'm having a problem, a need to apply a filter when user changes the selection of an input radio, I did this code, but it only works if I reload the page, what can I do to avoid reload and the page charge the filter whithout reloading?
`
add_action( 'wp_footer', 'wpmc_set_session_on_button_click' );
function wpmc_set_session_on_button_click() {
session_start();
$array_selectores = $_SESSION['array_selectores'];
$json = json_encode($array_selectores);
?>
<script>
document.querySelectorAll('input[name="horario-liga"]').forEach(function(input) {
input.addEventListener("change", function(e) {
var jsArray = <?php echo $json; ?>;
var horarioLigaValue = document.querySelector('input[name="horario-liga"]:checked').value;
var data = {
action: 'wpmc_set_session',
dto_manana: 'dto'
};
var data2 = {
action: 'wpmc_set_session',
dto_manana: 'no'
};
if (jsArray.includes(horarioLigaValue)) {
jQuery.post(
'<?php echo admin_url('admin-ajax.php'); ?>',
data,
function(response) {
console.log(response);
//console.log('dto');
}
);
}
else {
jQuery.post(
'<?php echo admin_url('admin-ajax.php'); ?>',
data2,
function(response) {
console.log(response);
//console.log('no');
}
);
}
});
});
</script>
<?php
}
// Manejador de petición AJAX para establecer la variable de sesión
add_action( 'wp_ajax_wpmc_set_session', 'wpmc_ajax_set_session' );
add_action( 'wp_ajax_nopriv_wpmc_set_session', 'wpmc_ajax_set_session' );
function wpmc_ajax_set_session() {
error_log(print_r($_POST, true));
echo $_POST['dto_manana'];
WC()->session->set( 'dto_manana', $_POST['dto_manana'] );
wp_die();
}
add_action( 'woocommerce_review_order_before_payment', 'detectar_radio_button_seleccionado' );
function detectar_radio_button_seleccionado() {
$dto_manana = WC()->session->get('dto_manana');
if (isset($dto_manana)) {
echo $dto_manana;
}
}
add_filter('woocommerce_cart_calculate_fees', 'add_recurring_postage_fees',10,1);
function add_recurring_postage_fees( $cart ) {
$dto_manana = WC()->session->get('dto_manana');
if ( (! empty( $cart->recurring_cart_key )) && ($dto_manana == 'dto') ) {
$cart->add_fee( 'Postage', 5 );
}
}`
If I go to checkout page I get the value 'dto' or 'no' but in order review only show the value of the last session, not the actual. I need to apply add_filter('woocommerce_cart_calculate_fees', 'add_recurring_postage_fees',10,1); when I select in horario-liga any value include in the array

Access WC() to get cart content in ajax callback

I'm trying to get woocommerce cart content in ajax callback function but it returns empty.
I've also tried using global $woocommerce variable that also returns the same result. I'm trying to get the cart content and convert all product to autoship feature. I'm using wooautoship plugin for that. however, main query is, how to get the cart details in ajax callback.
My Code is as follow:
add_action('wp_footer', 'woo_cart_autoship_js', 99);
function woo_cart_autoship_js(){
?>
<script type="text/javascript">
(function($){
$(document).on('click', '#convert-to-autoship', function(e){
e.preventDefault();
$.post( "<?php echo admin_url('admin-ajax.php'); ?>", { action: "convert-to-autoship" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
});
})(jQuery);
</script>
<?php
}
add_action( 'wp_ajax_convert-to-autoship', 'convert_to_autoship', 99 );
add_action( 'wp_ajax_nopriv_convert-to-autoship', 'convert_to_autoship', 99 );
function convert_to_autoship(){
print_r(WC()->cart->get_cart());
wp_die();
}

Trying to get PHP responce on ajax

Here I am trying to update the MSQL table using jQuery, both PHP code and jQuery script is written on the same page, the code working fine to update my tables but the response msg is not getting by the AJAX so it always shows me the default message "Some problem occurred, please try again.".
HTML
<!-- HTML code to display msg -->
<p class="statusMsg_post"></p>
jQuery
<script>
$(document).ready(function(){
$('#btn_publish').click( function() {
var obj_post_postID="<?php echo $post_id; ?>";
var publish_post="publish";
$.ajax({
type:'POST',
// url:'post_view.php',
data:{
"post_status_update": publish_post,
"obj_post_status": obj_post_postID,
},
success:function(res) {
if (res=='ok') {
$('.statusMsg_post').html('<span style="color:green;">Post has been '+publish_post+' sucessfully</span>');
}
else {
$('.statusMsg_post').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
}
});
});
});
</script>
PHP
// my PHP code to update my table
<?php
// require_once('../../inc/db-connect.php');
if (isset($_POST['post_status_update'])) {
$temp_publish_post = $_POST['post_status_update'];
echo $bj_post_postID = $_POST['obj_post_status'];
$obj_post_status_query = "UPDATE `objection_report` SET `obj_status` = '$temp_publish_post' WHERE `objection_report`.`obj_post_id` = $bj_post_postID;";
$obj_post_status_query .= "UPDATE `post` SET `status` = '$temp_publish_post' WHERE `post`.`post_id` = $bj_post_postID ;";
if (mysqli_multi_query($con, $obj_post_status_query)) {
echo "ok";
die;
}
}
?>
all the above codes are on the same page
The script is returning the HTML and JS on the ajax call. If you put checks around the HTML it will not:
<?php if ( ! isset( $_POST['post_status_update'] ) ): ?>
<p class="statusMsg_post"></p>
<script>
$( document ).ready( function () {
$( '#btn_publish' ).click( function () {
var obj_post_postID = "<?php echo $post_id; ?>";
var publish_post = "publish";
$.ajax( {
type: 'POST',
// url:'post_view.php',
data: {
"post_status_update": publish_post,
"obj_post_status": obj_post_postID,
},
success: function ( res ) {
if ( res === 'ok' ) {
$( '.statusMsg_post' ).html( '<span style="color:green;">Post has been ' + publish_post + ' sucessfully</span>' );
} else {
$( '.statusMsg_post' ).html( '<span style="color:red;">Some problem occurred, please try again.</span>' );
}
}
} );
} );
} );
</script>
<?php endif; ?>

Why my ajax login form doesn't work correctly?

I create a login form using AJAX .
And this is my JQUERY code:
$("#logbtn").on("click" , function() {
if (!$("div").hasClass("error"))
{
$.ajax
({
type:'post',
url:'http://localhost/mysite/wp-content/themes/facecar/admin/inc/proccesslogin.php',
data:{
username: $("#loguser").val(),
password: $("#logpass").val()
},
success:function(response) {
console.log(response);
if (response == "yes")
{
alert("answer is yes ");
} else {
alert("answer is no !");
}
}
});
}
});
This is my PHP code:
<?php
if (strpos($_POST["username"] , "moria") >= 0)
{
echo "yes";
} else {
echo "false";
}
?>
I put the response in the console and it show my php codes and alert "answer is no !" . what is problem ?
I believe, you are using wordpress and the way you are trying ajax in wordpress is not the right way. In wordpress ajax url is admin_url( 'admin-ajax.php' ).
You'll get an idea from this link: Ajax call from front in wordpress. I hope you can do the rest following that link.
Let's make it easy for you to understand...
write in your functions.php
/* include your js script */
add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts' );
function my_enqueue_scripts() {
//Change the key and url with yours
wp_register_script('my-js', get_stylesheet_directory_uri(). '/js/my-js.js', array( 'jquery' ) );
wp_enqueue_script('my-js');
//Localize script data to be used in my-js.js
$scriptData = array();
$scriptData['ajaxurl'] = admin_url( 'admin-ajax.php' );
$scriptData['action'] = 'answerAction';
wp_localize_script( 'my-js', 'my_js_data', $scriptData );
}
/* Add your server code */
add_action("wp_ajax_answerAction", "answerAction");
add_action("wp_ajax_nopriv_answerAction", "answerAction");
function answerAction(){
if (strpos($_POST["username"] , "moria") >= 0)
{
echo "yes";
} else {
echo "false";
}
die();
}
Now, add you js script in my-js.js
(function($){
$(document).ready(function(){
$('#logbtn').on('click',function(e){
e.preventDefault();
var data = {
'action': my_js_data.action,
'username': jQuery("#loguser").val(),
'password': jQuery("#logpass").val()
};
if (!$("div").hasClass("error"))
{
jQuery.post( my_js_data.ajaxurl, data, function(response) {
console.log(response);
if (response == "yes")
{
alert("answer is yes ");
} else {
alert("answer is no !");
}
});
}
});
});
})(jQuery);
Best of luck.

Ajax display msg on submit without refresh

I am submitting form data via Ajax and would like to display a message above the form on successful submit.
Currently the form does send the data successfully. It should render the feedback message on form submit <?php $this->renderFeedbackMessages(); ?> as defined in my config.php
Where am I going wrong? Possibly doing things in the wrong order due to first time working with mvc?
my config.php file I have the following defined;
define("FEEDBACK_BOOK_ADD_SUCCESSFUL", "Book add successful.");
my model;
public function addIsbn($isbn)
{
// insert query here
$count = $query->rowCount();
if ($count == 1) {
$_SESSION["feedback_positive"][] = FEEDBACK_BOOK_ADD_SUCCESSFUL;
return true;
} else {
$_SESSION["feedback_negative"][] = FEEDBACK_NOTE_CREATION_FAILED;
}
// default return
return false;
}
my controller;
function addIsbn()
{
// $_POST info here
header('location: ' . URL . 'admin/searchIsbn');
}
my searchIsbn.php;
<?php $this->renderFeedbackMessages(); ?>
<div>
//my html form here
</div>
<div id="result"></div>
<script>
$('#form').submit(function() {
event.preventDefault();
var isbn = $('#isbn_search').val();
var url='https://www.googleapis.com/books/v1/volumes?q=isbn:'+isbn;
$.getJSON(url,function(data){
$.each(data.items, function(entryIndex, entry){
$('#result').html('');
var html = '<div class="result">';
html += '<h3>' + entry.volumeInfo.isbn + '</h3>';
html += '<hr><button type="button" id="add" name="add">add to library</button></div>';
$(html).hide().appendTo('#result').fadeIn(1000);
$('#add').click(function(ev) {
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>admin/addIsbn',
data: {
'isbn' : isbn
}
});
});
});
});
});
</script>
No console error messages.
You are redirecting here:
header('location: ' . URL . 'admin/addIsbn');
remove it.
echo the success message here and add it to an HTML element's .html() API.
Your page will not be refreshed.
Your page is making the call to admin/addIsbn which is redirected to admin/searchIsbn. So you already have the output of renderFeedbackMessages() being sent to your function.
Use the success callback to output the results to the page:
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>admin/addIsbn',
data: {
'isbn' : isbn
},
success: function(data) {
$('#result').html(data);
}
});
The only way I could get this to work was to add an auto-refresh to my Ajax success function as follows;
window.location.reload(true);
Working however open to suggestions.

Categories