Set cors header for ajax requests

I am trying to use wp-ajax inside another sub-domain, but I am getting a CORS error. To solve this I used add_action with the send_headers hook

function cors_header () {     header('Access-Control-Allow-Origin: *'); } add_action('send_headers', 'cors_header'); 

But this didn’t work either. This is all my code.

    $  email = $  _POST['email'];     if (!$  email) {         status_header(401, 'Unauthorized Request');         exit();     }     $  form_id = 25;     $  search_criteria = array(         'status'     => 'active',         'field_filters' => array(             array(                 'key' => '2', 'value' => $  email,             )         )     );          $  entries = GFAPI::get_entries($  form_id, $  search_criteria);          add_action('send_headers', 'cors_header');          echo json_encode($  entries[0]['created_by']);     exit(); }  function cors_header () {     header('Access-Control-Allow-Origin: *'); } add_action("wp_ajax_nopriv_user_id", "get_user_id"); add_action("wp_ajax_user_id", "get_user_id"); 

Validate nonce with post ID in AJAX

I’m trying to create a nonce in an AJAX form where I can pass in a post ID. Then, validate it of course.

I want to confirm that if the action is intended, but also the post ID so someone cannot just change the POST ID input field value and take control of another post.

Here’s the nonce on the front end:

wp_create_nonce('my_edit_post' . $  post_id); 

And backend action:

add_action('wp_ajax_my_edit_post', 'handle_edit_post_form'); add_action('wp_ajax_nopriv_my_edit_post', 'handle_edit_post_form');  function handle_edit_post_form(){    if( ! isset( $  _POST['edit-post-nonce'] ) || ! wp_verify_nonce( $  _POST['edit-post-nonce'], 'my_edit_post')){      //failed   }   else {      //validated   } 

The whole thing doesn’t work because the $ post_id is not in the backend action.

But how can I pass it in there? $ post_id is undefined in the backend action.

The post ID is going to be dynamic (and not the referer URL’s ID).

Can I use a jQuery Ajax request in Code Snippets Plugin for WordPress?

I am using the Code Snippets Plugin for WordPress to send a jQuery Ajax request but I keep receiving a

POST 400 (Bad Request)

I have tried what seems to be a thousand ways to formulate the Ajax request following examples from stackoverflow, jQuery forums, WordPress forums, and it goes on. Always with the same error.

Here is what I currently have in my Snippet editor: JavaScript code

var jq = jQuery.noConflict(); // a bunch of code to determine what day is selected on a calendar, this all works up until the ajax call jq(".c-day-content").click(function () {     console.log ("handled the day being picked quite nicely...");         day = jq(this).text();         day = day.replace(/[^0-9]/g,'');         console.log("day=" + day);     bookingStart = bookingStart.concat(day);     //query the db looking for time slots with appointments and returning this array      var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ) ?>';     console.log(ajaxurl);      jq.ajax({         url: ajaxurl,         data: {             action: "retrieveAttendees",             dateSelected: bookingStart //bookingStart is variable that has a string value         },         method: 'POST',         success: function(data, XMLHttpRequest) {             //never been able to make it to here             console.log(JSON.stringify(data));         },         error: function (XMLHttpRequest, textStatus, errorThrown) {             console.log("we failed again: " + JSON.stringify(XMLHttpRequest));             console.log("text status: " + textStatus);             console.log("errorThrown: " + errorThrown)         }     });  

Then my php handler inside the same snippet editor:

function retrieveAttendees_request() { console.log("made it to the ajax request"); // I've never made it here either if ( isset($  _REQUEST)) {     $  bookingDay = $  _REQUEST['dateSelected'];     global $  wpdb;     $  sql = $  wpdb->prepare("select apps.bookingStart, COUNT(*) as booked from wp_amelia_customer_bookings as books inner join wp_amelia_appointments as apps on books.appointmentId = where apps.bookingStart like %s'%' and apps.status = 'approved' GROUP BY books.appointmentId;", $  bookingDay);     $  result = $  wpdb->get_row($  sql, ARRAY_A);     echo json_encode($  result); }   die(); } add_action('wp_ajax_retrieveAttendees', 'retrieveAttendees_request'); add_action('wp_ajax_nopriv_retrieveAttendees', 'retrieveAttendees_request'); 

I have tried adding the dataType to the Ajax, no luck. Tried adding both dataType and ContentType, no luck. I have no clue as to why I keep getting the same POST 400 Bad Request error. I would appreciate any help and insight.

Custom events in Google Analytics 4 for Ajax search

I have an search feature on my website. Sending text box value to a controller using Ajax and reading response. I want to track the text box value in Google Analytics 4. I have created a custom event but confused what will be my matching condition (parameter name, operator and value) ? enter image description here

window.gtag('event','search_keyword',{   search_term_input : $  ('#txt-search').val(),   country_code : 'UK' }); 

Request is reaching to GA4 and event is visible in Realtime tracking dashboard. I have created a custom dimension for search_keyword event and when generating report it search term is not available. Report display as "not set". enter image description here

Jquery ajax loses connection after minutes

Is there a way to get jquery ajax to remain connected until the external execution of code is done?


$ .ajax({
        type: "POST",
        data: "pro=2",
        url:"engine/process.php", // huge data to be processed here
        error: function(){
        success: function(finish){
                //php code is complete

the code works but after some few minutes it returns error alert when the connection is lost.
due to that the php code will not finish processing

How to make AJAX Load More Posts on Scroll for custom theme and custom-post-type?

I am currently working on a project where I am coding a custom theme with custom-post-type called products. Now, I am coding archive-product.php and stuck at making an AJAX load more posts on scroll for that.

I saw and tried most of the options available on internet. Most of them are made for Twenty Thirteen or some theme. I expect a custom code specifically for custom post type and that works for my custom theme.

Is this possible way to do so? I just want a code so that I can get more posts on scroll.

Woocommerce custom script ajax post form data fails to be captured in backend

I am using woocommerce and I wanna customize admin page’s coupon section.

So I use the following code snippet such that I can write my own codes in my_script.js.

add_action('admin_enqueue_scripts', 'add_custom_js_file_to_admin'); function add_custom_js_file_to_admin($  hook) {     $  screen = get_current_screen();     if ( 'shop_coupon' === $  screen->id ) {         wp_enqueue_script('my_script', plugin_dir_url(__FILE__) . 'js/my_script.js');     } } 

I am successful to create a new custom field: Taxonomy as shown in the pic below. And ajax post request’s header indicates that the data should be sent correctly (the red box in the pic). I am

However, my backend code snippet below fails to retrieve the data from the post request ( eg: $ tax below is null):

add_action('woocommerce_coupon_options_save', 'save_coupon_text_field', 10, 2); function save_coupon_text_field($  post_id, $  coupon)     {       $  tax = $  _POST['wc_sc_taxonomy_restrictions[0][tax]'];       $  coupon->update_meta_data('taxonomy_tax', $  _POST['wc_sc_taxonomy_restrictions[0][tax]']);       $  coupon->update_meta_data('taxonomy_op', $  _POST['wc_sc_taxonomy_restrictions[0][op]']);       $  coupon->save();     } 

I got 2 questions:

(1) Can someone kindly share any idea on what’s wrong with my codes above?

(2) In the custom script my_script.js, I wanna call an api which serves to retrieve data from my database; the data will then be used as the options available for the taxonomy’s drop-down select box. Can anyone tell me how I can do so in my_script.js? Normally in my BE php file, I wrote sth like below, yet I don’t know how I can perform sth similar in my custom script:

 global $  wpdb;  $  result = $  wpdb->get_results('some sql here'); 

Calling PHP function with AJAX

I am creating a plugin for wordpress for the backend. I when the admin press a button a js function is being called. In this js function, I am calling an API, and then I want to call a PHP with the result and the order id as a parms. so I have done this: action.php

function openpopup($  order_id) {         ?>       <button id="shipping360_create_delivery" data-id= "<?php echo $  order_id?>"              style="background-color: #2e4453; color:#fff; border-radius: 5px;text-align: center;width:100px;height:auto;font-size:10px; line-height: 1.5em;  border: none;-webkit-appearance: none; outline: none; padding:10px;cursor: pointer;">create</button>     <?php             popup($  order_id);      }   add_action('wp_ajax_update_order', 'update_order');   function update_order() {           $  order_id = isset($  _POST['id']) ? $  _POST['id'] : 0;     $  shipping_number = isset($  _POST['shipping_num']) ? $  _POST['shipping_num'] : "";     $  order = wc_get_order($  order_id);      update_post_meta($  order_id, 'shipping_number', $  shipping_number);     $  order->add_order_note($  shipping_number);     die();   }  

the popup function opens a pop-up with the order details. inside the popup function I have a button with the id "create_order" (this function has a lot of HTML and doesn’t really matter – the point is the button). Now for the app.js file

(function ($  ) {  $  (document).ready(function () {         $  ('#close').click(function () { //this is closing the pop-up    = "overflow: scroll";              $  ('#order-model').hide();         });         $  ("#createorder").click(function () { /// this is the call for the main function              createDelivery();         });          $  ("#shipping360_create_delivery").click(function () { // this is opening the pop-up             $  ('#order-model').show();    = "overflow: hidden;margin: 0;";          })     }) }(jQuery));     function createDelivery() {     // creates new delivery      const URL = BASE + "/shipping";      const distributor = document.getElementById("distributor").value;     const token = document.getElementById("ordertoken").innerHTML;     const companyid = document.getElementById("ordercompanyid").innerHTML;     const direction = "1";     const type = document.getElementById("ordertype").innerHTML;     const order_id = document.getElementById("ordernumber").innerHTML;      if (distributor == "") {         alert("Please fill all fields")     }      else {         senderinfo = "";//have data -- does not really matte         receiverinfo = ""; // have data -- does not really matter         const Data = {             senderinfo: senderinfo,             receiverinfo: receiverinfo,             type: type,             distributor: distributor,             companyid: companyid,             token: token,             direction: direction         }         const otherPram = {             headers: { "Content-Type": "application/json; charset=UTF-8" },             body: JSON.stringify(Data),             method: 'POST'         };         console.log(URL)         fetch(URL, otherPram)             .then(data => {                 return data.json()             })             .then(res => {                 body = res["body"]; //////////////////-----------------------/////////////////////////////// up to this point everything is working fine                 (function ($  ) {                     $  .ajax({                         type: "POST",                         url: ajaxurl,                         cache: false,                         data: {                             'action': 'update_order',                             'id': order_id,                             'shipping_num': body,                         },                         success: function (response) {                             location.reload();                             alert(response);  // not popping up                         },                         fail: function () {                             alert("helllo");  // I have put this and the one below just for checking  // not popping up                         },                         complete: function () {                             alert("hiii") // when I call my function this is that only on the pops up                         }                     });                 })(jQuery);               }).catch(function (error) {                 alert("Got an error:", error);               });       }  }      

Thanks for the help

AJAX form post returns 0

I am working on a simple plugin that shows an HTML form where the user can input a keyword which is used to query an external API. I currently have the form and the related jQuery set up, but when passed to the plugin’s PHP file, I get a response of simply 0. At this point I’m only just trying to get any response but 0 (see the echo "Whyyyy" part). I’ve been scouring the internet and feel like I have tried everything that’s been suggested, leading me to think I’m making a mistake somewhere.

Any help would be greatly appreciated. 🙏

This is the plugin’s PHP:

defined('ABSPATH') or die('Ah ah ah. You didn\'t say the magic word.');  class News_search {      // Load scripts upon class initiation     public function __construct() {         add_action('wp_enqueue_scripts', array($  this, 'enqueue_scripts'));         add_action('wp_ajax_get_news_callback', 'get_news_callback');         add_action('wp_ajax_nopriv_get_news_callback', 'get_news_callback');         add_shortcode('wp_news_search', array($  this, 'wp_news_search_form'));     }      function enqueue_scripts() {         // Enqueue CSS         wp_enqueue_style('wp-news-search', plugins_url('/css/wp-news-search.css', __FILE__));         // Enqueue and localize JS         wp_enqueue_script('ajax-script', plugins_url('/js/wp-news-search_query.js', __FILE__), array('jquery'), null, true);         wp_localize_script('ajax-script', 'ajax_object',             array('ajax_url' => admin_url('admin-ajax.php'),                 'security' => wp_create_nonce('my-string-shh'),             ));     }      // Handle AJAX request     function get_news_callback() {         check_ajax_referer('my-special-string', 'security');         $  keyword = isset($  _POST['news-keyword']) ? $  _POST['news-keyword'] : null;         echo "Whyyyy";         die();      }      public function wp_news_search_form() {         $  content .= '<form id="wp-news-search__form">                         <label>                             <input type="text" name="news-keyword" placeholder="' . __('Enter keywords') . '" id="news-keyword" required>                         </label>                         <button id="wp-news-search__submit">' .                          __('Search for news', 'wp-news-search') .                        '</button>                     </form>';         return $  content;     }  }  new News_search(); 

And this is the JS file:

(function ($  ) {      $  (document).ready(function () {         $  ('#wp-news-search__form').submit(function (event) {             event.preventDefault();              // const keyword = $  ('#query-input').val();             const values = $  (this).serialize();               if (values) {                 // send stuff to php                 console.log(values);                 const data = {                     action: 'get_news_callback',                     status: 'enabled',                     security:,                     form_data: values                 }                  $  .post(ajax_object.ajax_url, data, function(response) {                     if (response) {                         console.log(`Response is: $  {response}`);                     }                 })                     .fail(() => { console.error('error'); })                     .always(() => { console.log('form submitted') });             }          });       });  })(jQuery);