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             document.body.style = "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();             document.body.style = "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: ajax_object.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); 

Change AJAX Live Post Search Loop into foreach

I was told that the reason for why the live post search does not work is because the loop needs changing into a foreach.

This is the code:

add_action( 'wp_ajax_data_fetch' , 'data_fetch' ); add_action( 'wp_ajax_nopriv_data_fetch', 'data_fetch' ); function data_fetch() {      global $  wpdb;     $  post_search_query = $  wpdb->get_results("SELECT * FROM wp_posts where post_type = 'post' and post_title like '%'".esc_attr( $  _POST['search_keyword'] )."'%'");          if( $  post_search_query->have_posts() ) :                  while( $  post_search_query->have_posts() ): $  post_search_query->the_post(); ?>                          <h5><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></h5>             <span class="live-search-product-excerpt"><?php the_excerpt(); ?></span>              <?php endwhile;         wp_reset_postdata();     endif;     die(); } 

The search is dead. It shows nothing. Can someone please help me with this as I am at a loss. Here is the rest of the code:

add_shortcode('live_search', 'live_search_shortcode'); function live_search_shortcode(){      $  live_search = '<input type="text" class="live-search" name="postSearch" id="postSearch" placeholder="Type to Live Search"></input>     <div id="datafetch"></div>';          return $  live_search; }  add_action('wp_footer', 'jquery_live_search_data_fetch'); function jquery_live_search_data_fetch() { ?>      <script type="text/javascript">                  (function($  ){              var searchRequest = null;                                  jQuery(function (){                                      var minlength = 3;                                  jQuery("#postSearch").keyup(function (){                                          var that = this,                                      value = jQuery(this).val();                                  if (value.length >= minlength){                                      if (searchRequest != null)                      searchRequest.abort();                                  searchRequest = jQuery.ajax({                                      type: "POST",                     url: "<?php echo admin_url('admin-ajax.php'); ?>",                 data: {                 action: 'data_fetch',                 search_keyword : value                 },                                  dataType: "html",                 success: function(data){                                          if (value==jQuery(that).val()) {                                              jQuery('#datafetch').html(data);                     }                 }             }         );     } else {      jQuery('#datafetch').html( '' );     }   } ); }); } (jQuery));     </script> <?php } 

Ajax contact form widget plugin data not insert in database

I have been working at this for weeks without success. I’ve figured out problem after problem with the code, but none of the corrections seem to fix my core problem. The form doesn’t insert anything into the database and I don’t know why. all my data’s passed in the ajax call but it doesn’t insert in the data in the database.

I’m new to ajax and to WordPress plugins so I might be missing something obvious. Please help me know where I am going wrong. Thanks in advance.

My widget form plugin code

public function widget( $  args, $  instance ) {       if ( ! isset( $  args['widget_id'] ) ) {          $  args['widget_id'] = $  this->id;                  }          $  title = ( ! empty( $  instance['title'] ) ) ? $  instance['title'] : __( 'Contact' );          $  title = apply_filters( 'widget_title', $  title, $  instance, $  this->id_base );                            ?>     <?php         if ( $  title ) {            echo '<h2 class="widget-title">'.$  args['before_title'] . $  title . $  args['after_title'].'</h2>';                    }        ?>      <form  class="form-group" method="POST" id="form" action="">         <label>Name</label><br>         <input class="form-control" type="text" id="name" name="name" ><br>         <label>Mobile</label><br>         <input type="text" class="form-control" id="mobileno" name="mobileno" required><br>         <label>Email</label><br>         <input class="form-control"  type="email" id="email" name="email" ><br>         <label>Message</label><br>         <textarea class="form-control" id="message" name="message"  maxlength="10" onKeyPress="lengthcheck()"></textarea><br><br>         <button  class="btn btn-warning" type="submit" id="submit">Send Message</button>     </form> <?php }    

This is my enqueue methods:

add_action( 'wp_enqueue_scripts', 'vs_con_enqueue_scripts' );  function vs_con_enqueue_scripts(){  wp_register_script(     'ajaxHandle',     plugins_url('valid.js', __FILE__),     array('jquery'),     false,     true   );  wp_enqueue_script( 'ajaxHandle');  wp_localize_script(     'ajaxHandle',     'ajax_object',     array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) )   );  wp_enqueue_style( 'bootstrap-style','https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' );  }   add_action( "wp_ajax_contact", "vs_contact_form" ); add_action( "wp_ajax_nopriv_contact", "vs_contact_form" );   function vs_contact_form(){     global $  wpdb;         $  name = $  _POST["name"];        $  email = $  _POST["email"];        $  mobileno = $  _POST["mobileno"];        $  messsage = $  _POST["messsage"];                $  tablename = $  wpdb->prefix.'contactdetails';        $  insert_row = $  wpdb->insert(           $  tablename,             array(                 'name' => $  name,                 'email' => $  email,                 'mobileno' => $  mobileno,                'messsage' => $  messsage             )          );            // if row inserted in table         if($  insert_row){            echo json_encode(array('res'=>true, 'message'=>__('Message Sent Successfully')));        }else{           echo json_encode(array('res'=>false, 'message'=>__('Something went wrong. Please try again later.')));        }        wp_die(); }  

Here this is my form submit jquery ajax call function

valid.js

jQuery(document).ready(function($  ){     $  ('form#form').on('submit', function(e){        e.preventDefault();        var name =jQuery('#name').val();        var email = jQuery('#email').val();        var mobileno = jQuery('#mobileno').val();        var message = jQuery('#message').val();        debugger;        var text;        if(name.length < 5){          text = "Please Enter valid Name";         alert(text);          return false;        }        if(isNaN(mobileno) || mobileno.length != 10){          text = "Please Enter valid mobileno Number";          alert(text);          return false;        }        if(email.indexOf("@") == -1 || email.length < 6){          text = "Please Enter valid Email";          alert(text);          return false;        }                $  .ajax({           url: ajax_object.ajaxurl,           type:"POST",           dataType:'json',           data: {              action:'contact',              name: name,              email: email,              mobileno: mobileno,              message: message         },   success: function(data){             if (data.res == true){                 alert(data.message);    // success message             }          }, error: function(data){             if (data.res == false){                 alert(data.message);    // success message             }            }        });     $  ('#form')[0].reset();       });     });  

please help me to find out where I am wrong?

Trying to run a add_action within a function to run a woocomerce function on a ajax request

I am able to get a ajax request to work properly on a woocommerce checkout form page, now I want to update the price of the checkout in that ajax request. My add_action is in the function that is fired by the ajax request.

This is all done in a custom plugin as well

Here is my code this far, it doesn’t seem like the function request_gift_card ever fires

 function gift_card_redeem(){      if(!empty($  _SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($  _SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {     error_log("test !empty");          add_action( 'woocommerce_before_calculate_totals', 'request_gift_card', 99 );      function request_gift_card($  cart_object){       if( !WC()->session->__isset( "reload_checkout" )) {           /* Gift wrap price */           $  additionalPrice = 5;           error_log($  cart_object);           foreach ( $  cart_object->cart_contents as $  key => $  value ) {               if( isset( $  value["embossing_fee"] ) ) {                   // Turn $  value['data']->price in to $  value['data']->get_price()                   $  orgPrice = floatval( $  value['data']->get_price() );                   $  discPrice = $  orgPrice + $  additionalPrice;                   $  value['data']->set_price($  discPrice);               }           }       }     }      $  result['type'] = "success";     $  result = json_encode($  result);     echo $  result;   }   else {     error_log("test else");       header("Location: ".$  _SERVER["HTTP_REFERER"]);   }    die(); } 

WordPress update_comment_meta onclick not working with Ajax

I’m attempting to update_comment_meta via Ajax call in WordPress, but no data is returned and the comment_meta field is not being updated.

Fun.php

add_action( 'wp_enqueue_scripts', 'comment_voting_enqueue_scripts' ); function comment_voting_enqueue_scripts() {   wp_enqueue_script( 'comment_meta_voting-js', get_template_directory_uri() . '/js/ajax-vote.js', array( 'jquery' ), '0.5', false );   wp_localize_script( 'comment_meta_voting-js', 'commentMetaVoting', array(     'ajaxurl' => admin_url( 'admin-ajax.php' ),   ) ); } add_action( 'wp_ajax_nopriv_comment_meta_voting', 'comment_meta_voting' ); add_action( 'wp_ajax_comment_meta_voting', 'comment_meta_voting' );  function comment_meta_voting() {     $  comment_id = $  _POST['vote'];     $  vote_total = get_comment_meta($  comment_id , 'vote', true);     ++$  vote_total;     update_comment_meta($  comment_id , 'vote', $  vote_score );     die(); } 

ajax-vote.js

(function($  ) {     'use strict';     $  (document).on('click', '.sl-button', function() {         var button = $  (this);         var cmnt_id = button.attr('data-post-id');         var security = button.attr('data-nonce');              $  .ajax({                 type: 'POST',                 url: commentMetaVoting.ajaxurl,                 data : {                     action : 'comment_meta_voting',                     post_id : cmnt_id,                     nonce : security,                 },                 success: function(response){                     console.log('tst');                 }             });          return false;     }); })(jQuery); 

and in wp_list_comments callback i add core function where i want to show the link to call:

     <a href="<?php echo admin_url( 'admin-ajax.php?action=comment_meta_voting' . '&cmnt_id=' . $  commentid . '&nonce=' . $  nonce ); ?>" class="sl-button" data-nonce="<?php echo $  commentid ; ?>" data-post-id="<?php echo $  commentid ; ?> ">click</a> 

Finally i get console.log(‘tst’); in thee console.. so i think its correct, no data is returned and the comment_meta field is not being updated..

any help?

jQuery Ajax not loading page with ACF fields

I’m using the following jQuery code to load contents from a template part into another on click. Without the ACF PHP tags, it works. However, when I add these tags in <?php the_field('field_name'); ?> it throws a 500 (Internal Server Error) error. Does anyone have a solution for this, please?

    var baseUrl = "http://projectname:8888/wp-content/themes/custom-theme"      $  (".cross__functional").click(function (e) {         e.preventDefault();         console.log('cross functional Clicked')         $  ("#keContent").load(baseUrl + "/template-parts/components/filename.php");     }); 

WordPress ajax serial processing of and sending

I want to install/activate plugins via ajax.But i want to add a loading class on plugins list item which is being installing or activating. In jquery If i want to do it i need to write a lot bunch of code there.For example I have 4 plugins to install.So i have to first, send first ajax request to install first plugin then when a response comes I send second request in success block but its too time consuming. I want to know if there is any easy solution. Or in php file can i send a response back then continue installing 2nd one. Is that possible??

Ensure function has completed before allowing another Ajax call

I am updating an array saved in a users meta field using an ajax function.

The values added to the array are taken from the data-attributes within the tags which also act at the trigger to make the ajax call.

Whilst the function works 95% of the time, it can be a bit hit and miss whether the values save or not. I suspect this is because a user can fire these ajax calls too quickly and not give enough time for the original function call to save and update the meta field.

What would be the best method to ensure the ajax triggered function of updating the meta field value has been completed before allowing the function to run again?

Hope this makes sense – needless to say, please let me know if you need any more info.

Thanks in advance!!

Sample HTML

<div id="rjb_slots" class="slots">   <h5>Mon, 24th Aug 2020</h5>   <div class="slot">     <span class="time">10:30</span>     <a class="book" data-timestamp="1598265000" href="#"></a>   </div>   <div class="slot">     <span class="time">11:00</span>     <a class="booked" data-timestamp="1598266800" href="#"></a>   </div>   <div class="slot">     <span class="time">11:30</span>     <a class="booked" data-timestamp="1598268600" href="#"></a>   </div>   <div class="slot">     <span class="time">12:00</span>     <a class="book" data-timestamp="1598270400" href="#"></a>   </div>   <div class="slot">     <span class="time">12:30</span>     <a class="booked" data-timestamp="1598272200" href="#"></a>   </div>   <div class="slot">     <span class="time">13:00</span>     <a class="book" data-timestamp="1598274000" href="#"></a>   </div>   <div class="slot">     <span class="time">19:30</span>     <a class="book" data-timestamp="1598297400" href="#"></a>   </div> </div> 

Ajax .js

$  ('.slot').on('click', 'a.book', function(e) {   e.preventDefault();    var user   = $  ('#rjb_day').attr( 'data-user' );   var stamp  = $  (this).attr( 'data-timestamp' );       // console.log(bookCap);      $  (this).removeClass('book').addClass('booked');    $  .ajax({     type: 'POST',     url: ajax_object.ajaxurl,     data: {         action: 'rjb_make_diary_slots',         user: user,         stamp: stamp     },     success: function(data) {       // This outputs the result of the ajax request       console.log(data);     },     error: function(errorThrown){         console.log(errorThrown);     }   });      }); 

Function that updates the user metafield

add_action( 'wp_ajax_rjb_make_diary_slots', 'rjb_make_diary_slots' );  function rjb_make_diary_slots() {    $  user   = $  _POST['user'];    $  stamp  = array(               array(                  'rjb_cal_day'           => strtotime('today', $  _POST['stamp']),                 'rjb_cal_when'          => $  _POST['stamp'],                 'rjb_cal_position_id'   => '',                 'rjb_cal_candidate_id'  => ''               )             );    $  calendar   = get_user_meta( $  user, 'rjb_cal', true);   $  stamps     = !empty($  calendar) ? $  calendar : array();   $  new_stamp  = array_merge($  stamps, $  stamp);    usort($  new_stamp, function($  a, $  b) {     return $  a['rjb_cal_when'] <=> $  b['rjb_cal_when'];   });    update_user_meta( $  user, 'rjb_cal', $  new_stamp);    $  log = print_r($  stamp);    wp_die($  log);  } 

Example of a value stored in the rjb_cal user meta field

array (   [0] => array (     [rjb_cal_day] => 1598227200     [rjb_cal_when] => 1598266800     [rjb_cal_position_id] =>      [rjb_cal_candidate_id] =>    )   [1] => array (     [rjb_cal_day] => 1598227200     [rjb_cal_when] => 1598268600     [rjb_cal_position_id] =>      [rjb_cal_candidate_id] =>    )   [2] => array (     [rjb_cal_day] => 1598227200     [rjb_cal_when] => 1598272200     [rjb_cal_position_id] =>      [rjb_cal_candidate_id] =>    ) )