How to run AJAX request with no conflict? - wordpress

I have a function in functions.php file that makes json request. This is how I am calling this function:
define('IS_AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if (IS_AJAX_REQUEST){
loadmore();
}
Above code works just fine, but the problem is it conflicts with other AJAX request, for example, I see error message saying cannot execute loadmore() when I try to upload an image.
I tried following but none worked.
if (IS_AJAX_REQUEST && is_page()){
loadmore();
}
+
if (is_page()){
if (IS_AJAX_REQUEST){
loadmore();
}
}
+
if (IS_AJAX_REQUEST){
if (is_page()) loadmore(); }
}
And here is the loadmore function
function loadmore(){
header('Content-type: application/json');
echo json_encode (array ('rsp'=>'ok',
'payload'=> DrawPostList($_GET['tribe'], $_GET['offset']),
'lionly'=> true,
'tribe'=> $_GET['tribe'],
'offset'=> $_GET['offset']+20));
exit;
}
I only wanna execute loadmore() function when viewing a page. How can I do that ?

<?php
add_action( 'wp_head', 'my_action_javascript' );
function my_action_javascript() {
is_page() { // load script only on pages
?>
<script type="text/javascript" >
function loadmore() {
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: { action : 'loadmore_trigger', var1 : 'test', var2 : 'one more' }
})
}.done(function( response ) {
alert(response);
}
</script>
<?php
}
}
add_action('wp_ajax_nopriv_loadmore_trigger', 'loadmore_trigger');
add_action('wp_ajax_loadmore_trigger', 'loadmore_trigger');
function loadmore_trigger(){
echo "<pre>";
print_r($_POST);
exit;
}
?>
<input type="submit" onclick="loadmore(); return false;"> // make ajax call on click of submit button

Related

Wordpress ajax call getting 400 error in custom plugin

I am creating a custom plugin in WordPress admin and I want to use ajax call inside plugin. My plugin has different folders. I have written following scripts but its giving me 400 (bad request) error. I use latest wordpress.
I tried to get answer from other post but not able to find what is the issue here. When I am moving the code to function.php everything working but I dont want to use function.php.
The code below has been written in single php file ( say dahboard.php)
<?php
add_action( 'admin_footer', 'ajax_without_file' );
function ajax_without_file() { ?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var dataVariable = {
'action': 'my_action_without_file', // your action name
'variable_name': "Some value" // some additional data to send
};
jQuery.ajax({
url: ajaxurl, // this will point to admin-ajax.php
type: 'POST',
data: dataVariable,
success: function (response) {
console.log(response);
}
});
});
</script>
<?php
}
add_action ('wp_ajax_my_action_without_file' , 'my_action_without_file');
add_action('wp_ajax_nopriv_my_action_without_file','my_action_without_file');
function my_action_without_file(){
echo json_encode($_POST);
wp_die();
}
?>
Try this. I've changed "ajaxurl" to <?php echo admin_url( 'admin-ajax.php' ); ?>
<?php
add_action( 'admin_footer', 'ajax_without_file' );
function ajax_without_file() { ?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var dataVariable = {
'action': 'my_action_without_file', // your action name
'variable_name': "Some value" // some additional data to send
};
jQuery.ajax({
url: <?php echo admin_url( 'admin-ajax.php' ); ?>, // this will point to admin-ajax.php
type: 'POST',
data: dataVariable,
success: function (response) {
console.log(response);
}
});
});
</script>
<?php
}
add_action ('wp_ajax_my_action_without_file' , 'my_action_without_file');
add_action('wp_ajax_nopriv_my_action_without_file','my_action_without_file');
function my_action_without_file(){
echo json_encode($_POST);
wp_die();
}
?>

How to display Country Phone Code in wordpress?

I am not able to edit woocommerce checkout page.
I want to add my country phone number code like ( +88 ) but I am not able to do it.
Update:
I tried this code from this referece and added below code to my main theme ( woodmart) function.php.
wp_enqueue_style( 'int-tel-phone-style', 'https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/6.4.1/css/intlTelInput.css' );
wp_enqueue_script('int-tel-phone-js','https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/6.4.1/js/intlTelInput.min.js');
Finaly added this below code script in footer.php
<script type="text/javascript">
$("#billing_phone").intlTelInput();
</script>
But it still not working.
Any help please?
Just add follows codes snippets in your active theme's functions.php to do the job -
add_action( 'wp_footer', 'callback_wp_footer' );
function callback_wp_footer(){
?>
<script type="text/javascript">
( function( $ ) {
$( document.body ).on( 'updated_checkout', function(data) {
var ajax_url = "<?php echo admin_url('admin-ajax.php'); ?>",
country_code = $('#billing_country').val();
var ajax_data = {
action: 'append_country_prefix_in_billing_phone',
country_code: $('#billing_country').val()
};
$.post( ajax_url, ajax_data, function( response ) {
$('#billing_phone').val(response);
});
} );
} )( jQuery );
</script>
<?php
}
add_action( 'wp_ajax_nopriv_append_country_prefix_in_billing_phone', 'country_prefix_in_billing_phone' );
add_action( 'wp_ajax_append_country_prefix_in_billing_phone', 'country_prefix_in_billing_phone' );
function country_prefix_in_billing_phone() {
$calling_code = '';
$country_code = isset( $_POST['country_code'] ) ? $_POST['country_code'] : '';
if( $country_code ){
$calling_code = WC()->countries->get_country_calling_code( $country_code );
$calling_code = is_array( $calling_code ) ? $calling_code[0] : $calling_code;
}
echo $calling_code;
die();
}

Redirect To URL when a comment is approved in WordPress

I am working on a custom post type, where the post content is updated with the comment content that is approved.
My code is:-
add_action('comment_unapproved_to_approved', 'hgkb_update_post_content_on_comment_approval');
function hgkb_update_post_content_on_comment_approval($comment)
{
$post_id = $comment->comment_post_ID;
$comment = $comment->comment_content;
$post_type=array('hgkb','hg-questions');
if (in_array(get_post_type( $post_id ),$post_type))
{
$update_answer=wp_update_post( array('ID' => $post_id, 'post_content' => $comment) );
if($update_answer)
{
//How to reload the page or redirect to another url?
}
}
}
Once the post content is updated, I want the content to be reflected in the content editor immediately or reload the page, so that the user can see the changes has been made.
Thanks in advance.
I have done it using another hook. So the code becomes:-
add_action('comment_unapproved_to_approved', 'hgkb_update_post_content_on_comment_approval');
function hgkb_update_post_content_on_comment_approval($comment)
{
$post_id = $comment->comment_post_ID;
$comment = $comment->comment_content;
$post_type=array('hgkb','hg-questions');
if (in_array(get_post_type( $post_id ),$post_type))
{
$update_answer=wp_update_post( array('ID' => $post_id, 'post_content' => $comment) );
if($update_answer)
{
//How to reload the page or redirect to another url?
}
}
}
and then:-
add_action('admin_footer-post.php', 'hgkb_reload_after_approval');
function hgkb_reload_after_approval()
{
global $post;
$post_type=array('hgkb','hg-questions');
if (stristr( $_SERVER['REQUEST_URI'], 'post.php' ) !== false && is_object( $post ) && in_array(get_post_type( $post->ID ),$post_type) )
{
?>
<script>
jQuery(document).ready(function(){
// Reload after 1 second when a comment approved
jQuery(document).on('click', '.vim-a', function (e) {
alert("Answer Updated!! The page will be reloaded after you click on OK. ");
setTimeout(function() {
window.location.href = "<?php echo site_url(); ?>/wp-admin/post.php?post=<?php echo $post->ID; ?>&action=edit"
}, 1000);
});
// END Reload after 1 second when a comment approved and Reload the Page when a comment approved
});
</script>
<?php
}
}

Woocommerce: how to use wp_ajax_woocommerce_update_order_review hook in order review page

How i can use Ajax in checkout page in woocommerce. I am trying to add custom pricing just before Payment in Order Review Page.
I have a check box when user will select the checkbox and pricing should be add in order.
Here is my code
function woocommerce_update_order_review() {
global $woocommerce;
$prc = strip_tags($woocommerce->cart->get_cart_total());
$priceValue = str_replace(",","",str_replace("#36;","",substr($prc,1)));
if($priceValue<=300 && $priceValue>200){
$rate_cost = 2.70;
}
else if($priceValue>300){
$extraDvalue = 2.70;
$extraVal = ceil(round(($priceValue-300),0)/100)*.90;
$newPr = $extraDvalue+$extraVal;
$rate_cost = $newPr;
}
if($priceValue>100){
$woocommerce->cart->add_fee( 'Declared value', $rate_cost, false, '' );
}
exit;
}
add_action('wp_ajax_woocommerce_update_order_review','woocommerce_update_order_review');
add_action('wp_ajax_nopriv_woocommerce_update_order_review','woocommerce_update_order_review');
JS CODE
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
// This does the ajax request
jQuery.ajax({
type: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: {
action: 'woocommerce_update_order_review', check: 'check'
}
}).done(function(value) {
alert(value);
});
Please suggest is this possible or not ?
Thanks

Passing variable with Ajax in WordPress

I am trying to pass variable when user click on link to page single.php
Here is my code
<a href='#' id='8' class='clickme' style='font-weight:bold;color:white;font-size:16px;'>";
In function.php, I put this code:
/////////////////////////////////////////////////////////
add_action( 'wp_head', 'myajaxcall' );
function myajaxcall(){ ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
jQuery(".clickme").click( function() {
// We'll pass this variable to the PHP function example_ajax_request
var id = $('.clickme').attr('id');
// This does the ajax request
$.ajax({
url: <?php echo admin_url( 'admin-ajax.php'); ?>,
data: {
'action':'get_sidebar_request',
'page_id' : id
},
// beforeSend: function (jqXHR, settings)
// {
// alert( url = settings.url);
//},
success:function(data){
alert(data);
},
error: function(errorThrown){
//alert(errorThrown);
}
});
});
});
</script>
<?php }
add_action( 'wp_ajax_get_sidebar_request', 'idAjax' );
add_action( 'wp_ajax_nopriv_get_sidebar_request', 'idAjax' );
function idAjax()
{
require( get_template_directory() . '/single.php' );
}
/////////////////////////////////////////////////////////////////////
And in file `single.php, when I want to get the passed variable, I put this code:
$page_id=0;
$page_id = $_REQUEST['page_id'];
echo "page_id=".$page_id;
But the variable isn't passing to single.php. I try to echo it, and nothing happens.
Can you help me?
You can use Network tool in Google Chrome to debug and see sent/received data.
If "id" is not null when you send it, try to use $_POST to output your data in your php file, like this :
var_dump($_POST);
check this :
$.ajax({
url: <?php echo admin_url( 'admin-ajax.php'); ?>,
data: {
'action':'get_sidebar_request',
'page_id' : id
},
and add double quote to url value
$.ajax({
url: "<?php echo admin_url( 'admin-ajax.php'); ?>",
data: {
'action':'get_sidebar_request',
'page_id' : id
},
if you don't see your ajax call, it's a javascript error in your code.
Do you have any error in browser Console ?

Resources