How to call ajax url properly on Wordpress? - php

I have this script:
<script>
(function($){
load_data();
function load_data(query)
{
jQuery.ajax({
url:"fetch.php",
method:"post",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
})(jQuery);
</script>
on a php file, but I get constantly an error cause Wordpress doesn't recognize the ajax url (fetch.php) and it tries to generate a new URL in my domain.
How can I do it properly?

You need use wp_ajax or wp_ajax_nopriv action hooks to use WordPress ajax. check the below code.
For call the wp_ajax or wp_ajax_nopriv action hooks you need use
WP admin_url('admin-ajax.php') this will return wordperss ajax url.
And, also pass action in jQuery.ajax data params.
Check the below code. code goes in your active theme functions.php file.
function call_ajax(){ ?>
<script>
(function($){
load_data();
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != ''){
load_data(search);
}else{
load_data();
}
});
function load_data( query ){
jQuery.ajax({
url:"<?php echo admin_url('admin-ajax.php'); ?>",
method:"post",
data:{acion:'your_action_name',query:query},
success:function( data ) {
$('#result').html( data );
}
});
}
})(jQuery);
</script>
<?php }
add_action( 'wp_footer', 'call_ajax', 10, 1 );
add_action( 'wp_ajax_your_action_name', 'your_action_name' );
add_action( 'wp_ajax_nopriv_your_action_name', 'your_action_name' );
function your_action_name(){
echo "ajax call";
echo $_POST['query'];
die;
}

Related

call function url page with ajax

I have tried several times but it didn't work. I want to call the function nama() on the dom_area.php page.
This is dom_area as target
<?php
function nama()
{
echo $_POST['data_area'];
}
?>
and this is the page where I call the function
<button id='acc'>asas</button>
<script>
$(document).ready(function() {
$('#acc').click(function() {
let data_area = 2;
let url_address = "<?= 'dom_area.php/nama()'; ?>";
$.ajax({
url:url_address,
type:'post',
data:{data_area:data_area} ,
}).done(function(output){
console.log(output);
// alert(data);
});
// console.log(url);
});
});
</script>
You can only cause a php file to be launched, NOT a specific function within that script
However if you pass a parameter to control what to do in the script you can achieve what you are trying to do
<button id='acc'>asas</button>
<script>
$(document).ready(function(){
$('#acc').click(function(){
let data_area = 2;
$.ajax({
url:'dom_area.php', // the script file name
type:'post',
// add a control parameter
data:{control:"Nama", data_area:data_area},
}).done(function(output){
console.log(output);
// alert(data);
});
// console.log(url);
});
});
</script>
Now in the PHP
<?php
function nama()
{
echo $_POST['data_area'];
}
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
// form was submitted
switch($_POST['control'])
case 'Nama':
nama();
break;
default:
echo json_encode(['status'=>'failed']);
}
}
?>
try this:
<?php include_once('dom_area.php') ?>
<button id='acc'>asas</button>
<script>
$(document).ready(function(){
$('#acc').click(function(){
let data_area = 2;
let url_address = "<?= json_encode(nama()); ?>";
$.ajax({
url:url_address,
type:'post',
data:{data_area:data_area} ,
}).done(function(output){
console.log(output);
// alert(data);
});
// console.log(url);
});
});
</script>
Please try this in call part.
<button id='acc'>asas</button>
<script>
$(document).ready(function(){
$('#acc').click(function(){
let data_area = 2;
$.ajax({
url:'dom_area.php/nama',
type:'post',
data:{data_area:data_area} ,
}).done(function(output){
console.log(output);
// alert(data);
});
// console.log(url);
});
});
</script>

Create WooCommerce custom Order meta via AJAX on thank you page

I am trying to use update_meta_data via AJAX on the WooCommerce thank you page but I am stuck.
Here is what I have so far:
//Following function gets called from the page already
function renderForm() {
echo "<script>
jQuery(document).ready(function() {
$('body').on('click', '#button', function(){
$.ajax({
type: 'POST',
url: 'https://thepropdrop.com/wp-admin/admin-ajax.php',
data: {
action: 'create_user_meta'
},
success: function(textStatus){
console.log('Success');
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert('errorThrown');
}
});
});
});
</script>";
}
add_action("wp_ajax_create_user_meta", "create_user_meta");
add_action("wp_ajax_nopriv_create_user_meta", "create_user_meta");
function create_user_meta() {
$order = wc_get_order($order_id);
$order->update_meta_data('hasAnswered', 'Yes');
$order->save();
die();
}
Any help you could provide would be greatly appreciated.
EDIT - My related code, that will provide some context:
Here is the button on the thankyou.php:
<span class="button gameStart">
Let's do this
</span>
<script>
jQuery(document).ready(function() {
$('.gameStart').click(function(event){
$(this).remove();
$('.gameHeader').remove();
$('.gamePage .gameContainer').css('display', 'block');
$.ajax({
type: 'GET',
url: '<?php echo admin_url("admin-ajax.php");?>',
data: {
action: 'CCAjax'
},
success: function(textStatus){
$( '.gameForm' ).prepend( textStatus );
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
</script>
<div class="gameContainer">
<div class="timerWrapper">
<div id="timer">
</div>
</div>
<div class="gameForm">
<h3>Which of the following countries has the largest land mass?</h3>
<div id='answerSubmitButton'>Submit answer</div>
</div>
</div>
Then functions.php:
function CCAjax() {
get_template_part('template-parts/game');
die();
}
add_action('wp_ajax_CCAjax', 'CCAjax');
Then the game.php:
<?php
renderForm();
?>
Now here is the full render form function (It pulls 3 potential answers from DB and also has a countdown timer, hence why i didnt post it all i didnt want to confuse)
function renderForm() {
// Fetch contries object
global $wpdb;
$results = $wpdb->get_results("select * from ( select *,#curRow :=#curRow + 1 as row_number from ( select * from ( select * from wpCountriesDB order by rand() limit 3 )b order by Mass desc )a JOIN (select #curRow :=0)r)x order by RAND()");
// Create array for answers
if(!empty($results)) {
$i = 1;
foreach ($results as $r) {
echo "<div class='answerWrapper'>
<span class='questionNumber'><span>$i</span></span>
<label class='label' for='radio$i'>".$r->Country."</label>
<input type='radio' id='radio$i' name='like' value='$r->row_number' />
</div>";
$i++;
}
}
// Display timer and check answer correct
echo "<script>
var timeLeft = 3000;
var elem = document.getElementById('timer');
var timerId = setInterval(countdown, 1000);
function countdown() {
if (timeLeft < 0) {
clearTimeout(timerId);
$('#answerSubmitButton').click();
} else {
elem.innerHTML = timeLeft + 's';
timeLeft--;
}
}
jQuery(document).ready(function() {
$('body').on('click', '#answerSubmitButton', function(){
var fetchInput = document.querySelector('.answerWrapper input[name=\'like\']:checked');
var fetchSelected = fetchInput.value;
if (fetchSelected == 1) {
$.ajax({
type: 'POST',
url: 'ajaxURL',
data: {
action: adding_custom_meta
},
success: function(textStatus){
console.log('Success');
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert('errorThrown');
}
});
} else {
console.log('incorrect')
}
});
});
</script>";
}
add_action("wp_ajax_create_user_meta", "create_user_meta");
add_action("wp_ajax_nopriv_create_user_meta", "create_user_meta");
function create_user_meta() {
$order = wc_get_order($order_id);
$order->update_meta_data('hasAnswered', 'Yes');
$order->save();
die();
}
Do i have to pass the Order ID at the very start?
Update (since your gave some context with the missing code):
Yes you have to pass the Order ID at the very start from your thankyou page (template).
You need to rethink differently your code, as you can't pass the order ID to your renderForm() function. The order ID is required to be passed through jQuery Ajax to your PHP Wordpress Ajax function that need it (to add to the order the custom meta data).
Also another mistake is (2 times):
jQuery(document).ready(function() {
that need to be instead (as you are using the jQuery shortand $):
jQuery(document).ready(function($) {
or (the same) in a shorter way:
jQuery(function($) {
Original answer:
There is some errors and missing things in your script, like the order Id that need to be passed through jQuery ajax to your PHP Wordpress/Ajax function that will add the custom meta data…
Also you don't provide in your code, the displayed button output…
So Here it is a complete example, based on your revisited code, that will display the button on Order received (thankyou) page and will add custom meta data to your order:
// PHP Wordpress AJAX: Add custom meta data to the Order
add_action("wp_ajax_adding_custom_meta", "adding_custom_order_metadata");
add_action("wp_ajax_nopriv_adding_custom_meta", "adding_custom_order_metadata");
function adding_custom_order_metadata() {
if( isset($_POST['order_id']) && $_POST['order_id'] > 0 ){
update_post_meta(esc_attr($_POST['order_id']), '_has_answered', 'Yes');
echo json_encode($_POST['order_id']);
}
die();
}
// Display a button on thankyou page (+ jQuery Ajax script)
add_action( 'woocommerce_thankyou', 'jquery_thank_you_page', 90, 1 );
function jquery_thank_you_page( $order_id ) {
// Display the button on thankyou page
echo ''.__("Update").'';
// The jQuery script (Ajax)
?>
<script type="text/javascript">
jQuery(function($) {
$('body').on('click', '#button', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '<?php echo admin_url("admin-ajax.php");?>',
data: {
'action': 'adding_custom_meta',
'order_id': '<?php echo $order_id; ?>'
},
success: function(response){
console.log(response); // Just for testing
},
error: function(error){
console.log(error); // Just for testing
}
});
});
});
</script>
<?php
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Using update_post_meta() function is much better and lighter alternative than calling an instance of the WC_Order Object and use after the save() method.
I have changed the order custom meta key from hasAnswered to _has_answered
On "Order received" page, the displayed button (the order Id come back, see in the console):
In the database, the custom post meta data is created:
Something like this
function renderForm($order_id) { //add an argument
echo "<script>
jQuery(document).ready(function() {
$('body').on('click', '#button', function(){
$.ajax({
type: 'POST',
url: 'https://thepropdrop.com/wp-admin/admin-ajax.php',
data: {
action: 'create_user_meta',
order_id: {$order_id} //add to your request data
},
success: function(textStatus){
console.log('Success');
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert('errorThrown');
}
});
});
});
</script>";
}
Then in your AJAX callback
function create_user_meta() {
if(empty($_POST['order_id'])) {
//return some error message
die();
}
$order = wc_get_order($_POST['order_id']); //get the id from the request
$order->update_meta_data('hasAnswered', 'Yes');
$order->save();
die();
}
As there is no way for me to know how you call renderForm there is no way for me to know how to put the order id in it. But at some point it will have to be either an argument or part of an argument (in the case of shortcode $attr such as [renderForm order_id=45]).
You may be also able to use something like
$order_id = get_the_ID();
Or
$order = get_post();
$order_id = $order->ID;
Depending on the context of how you use renderForm, you probably cant use them in the AJAX callback because it's a new request so you lose any of that context you had when building the page.
Hope that makes sense.
Not tested, but ... maybe it will work ... it should in theory.

On country change ajax update checkout for shipping in Woocommerce

I'm looking for a way to update order review (shipping price) when client change country on checkout page.
I want to use jQuery. but wc_checkout_params wc_checkout_params is deprecated.
function custom_checkbox_checker() {
if (is_checkout()) {
wp_enqueue_script('jquery');
?>
<script type="text/javascript">
jQuery(document).ready(function (e) {
var $ = jQuery;
// wc_checkout_params is required to continue, ensure the object exists
if (typeof wc_checkout_params === 'undefined')
return false;
var updateTimer,
dirtyInput = false,
xhr;
function update_shipping(billingstate, billingcountry) {
if (xhr)
xhr.abort();
$('#order_methods, #order_review').block({message: null, overlayCSS: {background: '#fff url(' + wc_checkout_params.ajax_loader_url + ') no-repeat center', backgroundSize: '16px 16px', opacity: 0.6}});
var data = {
action: 'woocommerce_update_order_review',
security: wc_checkout_params.update_order_review_nonce,
billing_state: billingstate,
billing_country: billingcountry,
post_data: $('form.checkout').serialize()
};
xhr = $.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: data,
success: function (response) {
var order_output = $(response);
$('#order_review').html(response['fragments']['.woocommerce-checkout-review-order-table'] + response['fragments']['.woocommerce-checkout-payment']);
$('body').trigger('updated_checkout');
},
error: function (code) {
console.log('ERROR');
}
});
}
jQuery('.state_select').change(function (e, params) {
update_shipping(jQuery(this).val(), jQuery('#billing_country').val());
});
});
</script>
<?php
}
}
add_action('wp_footer', 'custom_checkbox_checker', 50);
any clue?
All solutions related to AJAX for WC like this are useless since wc_checkout_params removed on 3.x version.
Nothing useful found in woocommerce documentations.
nothing in stack overflow!
wondering why no one answered questions like this for 2 years+
Normally woocommerce do it itself, and nothing is needed…
But you can try the following instead, that should work in Woocommerce 3+ versions:
add_action('wp_footer', 'billing_country_update_checkout', 50);
function billing_country_update_checkout() {
if ( ! is_checkout() ) return;
?>
<script type="text/javascript">
jQuery(function($){
$('select#billing_country, select#shipping_country').on( 'change', function (){
var t = { updateTimer: !1, dirtyInput: !1,
reset_update_checkout_timer: function() {
clearTimeout(t.updateTimer)
},
trigger_update_checkout: function() {
t.reset_update_checkout_timer(), t.dirtyInput = !1,
$(document.body).trigger("update_checkout")
}
};
$(document.body).trigger('update_checkout');
console.log('Event: update_checkout');
});
});
</script>
<?php
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.

Ajax PHP - keyup function Bug (Slow Query)

I building a application to fetch records database with ajax. And I'm using the keyup function to catch what I'm querying/writing. But some times when I write something like "si" and there are many records in the database and query takes more time than me writing the next letter this bug happens. (querying 'sitre' but PHP only catches 'si'):
My question is, is there a way to get around this?
My JS code:
<script>
$(document).ready(function(){
load_data();
function load_data(query) {
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '') {
load_data(search);
} else {
load_data();
}
});
});
</script>
Thank you.
Fixed with delay thanks to Taron Saribekyan
<script>
var timeout = null;
$(document).ready(function(){
load_data();
function load_data(query) {
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
clearTimeout(timeout);
if(search != '') {
timeout = setTimeout(function () {
load_data(search);}
, 500);
} else {
load_data();
}
});
});
</script>
Set delay before ajax query.
See how to do it

Ajax function issue on return true and false in wordpress

I am validating a form with ajax and jquery in WordPress post comments textarea for regex. But there is an issue when i want to alert a error message with return false. Its working fine with invalid data and showing alert and is not submitting. But when i put valid data then form is not submit. May be issue with return false.
I tried making variable and store true & false and apply condition out the ajax success block but did not work for me.
Its working fine when i do it with core php, ajax, jquery but not working in WordPress .
Here is my ajax, jquery code.
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And i'm using wordpress wp_ajax hook.
And here is my php code.
<?php
function nmp_process_func (){
$comment = $_REQUEST['comment'];
preg_match_all("/(->|;|=|<|>|{|})/", $comment, $matches, PREG_SET_ORDER);
$count = 0;
foreach ($matches as $val) {
$count++;
}
echo $count;
wp_die();
}
?>
Thanks in advance.
Finally, I just figured it out by myself.
Just put async: false in ajax call. And now it is working fine. Plus create an empty variable and store Boolean values in it and then after ajax call return that variable.
Here is my previous code:
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And the issue that i resolved is,
New code
var returnval = false;
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
async: false, // Add this
data: 'action=nmp_process_ajax&comment=' + comment,
Why i use it
Async:False will hold the execution of rest code. Once you get response of ajax, only then, rest of the code will execute.
And Then simply store Boolean in variable like this ,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
returnval = false;
} else {
returnval = true;
}
}
});
// Prevent Default Submission Form
return returnval; });
That's it.
Thanks for the answers by the way.
Try doing a ajax call with a click event and if the fields are valid you submit the form:
jQuery(document).ready(function () {
jQuery("input[type=submit]").click(function (e) {
var form = $(this).closest('form');
e.preventDefault();
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: {'action':'nmp_process_ajax','comment':comment},
success: function (res) {
var count = parseInt(res);
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
} else {
form.submit();
}
}
});
});
});
note : you call need to call that function in php and return only the count!
Instead of submitting the form bind the submit button to a click event.
jQuery("input[type=submit]").on("click",function(){
//ajax call here
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}else{
jQuery("form").submit();
}
}
});
return false;
})
Plus also its a good idea to put return type to you ajax request.
Let me know if this works.

Categories