$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>plugins - Ajax call to php function doesn't work PHP code|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

plugins - Ajax call to php function doesn't work PHP code

matteradmin10PV0评论

I have a form like this:

<form method="post" action="" id="BookingForm">
    <label for="email">Email</label>
    <input type="text" name="email" id="emailId" value="" />
    <input type="hidden" name="action" value="1" />
    <input type="submit" name="submitname" value="Send" />
</form>
<div id="container"></div>

My custom js file is in the following path: assets/js/makebooking.js My JS file makebooking.js :

jQuery(document).ready(function(event) {
 jQuery('#BookingForm').submit(validateForms);
 function validateForms(event) {
 event.preventDefault();

     var x =  MBAjax.ajaxurl;
     alert(x);

    jQuery.ajax({
      action:  'makeBooking',
      type:    "POST",
      url:     MBAjax.admin_url,
      success: function(data) {
         alert(data);
         //jQuery("#container" ).append(data);
      },
    fail: function(error){
        alert("error" + error);
    }
    });
     return false;
  }
});

Functions.php file:

// embed the javascript file that makes the AJAX request
wp_enqueue_script( 'make-booking-ajax','/wp-content/themes/twentyseventeen/assets/js/makebooking.js', array( 'jquery' ) );
// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script( 'make-booking-ajax', 'MBAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

function makeBooking(){
    echo "Home again";
    return "Home";
}


add_action('wp_ajax_make_booking', 'makeBooking');

The problem is that the ajax call returns all the dom and not what the php function returns. The code in the php function does not work; the echo message is not printed

The image below shows the issue:

Thanks,

Federico


This is my status code and my response of ajax

I have a form like this:

<form method="post" action="" id="BookingForm">
    <label for="email">Email</label>
    <input type="text" name="email" id="emailId" value="" />
    <input type="hidden" name="action" value="1" />
    <input type="submit" name="submitname" value="Send" />
</form>
<div id="container"></div>

My custom js file is in the following path: assets/js/makebooking.js My JS file makebooking.js :

jQuery(document).ready(function(event) {
 jQuery('#BookingForm').submit(validateForms);
 function validateForms(event) {
 event.preventDefault();

     var x =  MBAjax.ajaxurl;
     alert(x);

    jQuery.ajax({
      action:  'makeBooking',
      type:    "POST",
      url:     MBAjax.admin_url,
      success: function(data) {
         alert(data);
         //jQuery("#container" ).append(data);
      },
    fail: function(error){
        alert("error" + error);
    }
    });
     return false;
  }
});

Functions.php file:

// embed the javascript file that makes the AJAX request
wp_enqueue_script( 'make-booking-ajax','/wp-content/themes/twentyseventeen/assets/js/makebooking.js', array( 'jquery' ) );
// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script( 'make-booking-ajax', 'MBAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

function makeBooking(){
    echo "Home again";
    return "Home";
}


add_action('wp_ajax_make_booking', 'makeBooking');

The problem is that the ajax call returns all the dom and not what the php function returns. The code in the php function does not work; the echo message is not printed

The image below shows the issue:

Thanks,

Federico


This is my status code and my response of ajax

Share Improve this question edited Oct 22, 2018 at 16:22 Johansson 15.4k11 gold badges44 silver badges80 bronze badges asked Oct 22, 2018 at 9:32 FedericoFederico 1031 silver badge3 bronze badges 0
Add a comment  | 

3 Answers 3

Reset to default 1

It looks like the MBAjax.ajaxurl and MBAjax.admin_url are probably not set. If it can't post to the correct Wordpress handler, then you will probably get a 404 page HTML returned instead of the PHP function return value.

You can test by hard-coding the ajax url to url: "/wp-admin/admin-ajax.php", and see if that fixes things.

Secondly, I have always added a hidden field on my forms with the action <input type="hidden" name="action" value="make_booking">

Try that and see how you get on. Also check your browser console network tab to see the AJAX request being sent. You can check the data you are POSTing and also the response you get back. Easier than trying to use alerts.

You can also use console.log(x) instead.

Update: I think you're missing sending anything in your AJAX request:

jQuery.ajax({
   action : 'make_booking',
   type   : "POST",
   data   : {
      action: 'make_booking'
   }
   url    : MBAjax.admin_url,
   success: function(data) {
      alert(data);
      //jQuery("#container" ).append(data);
   },
   fail: function(error){
      alert("error" + error);
   }
});

Try that.

The action seems to be incorrect on your Ajax call. As per the wp_ajax_{action} codex entry,

The wp_ajax_ hooks follows the format "wp_ajax_$youraction", where $youraction is the 'action' field submitted to admin-ajax.php.

So try changing action: 'makeBooking', to action: 'make_booking', and see if it works then.

And if you want the ajax call to work for non-logged-in users, use also the wp_ajax_nopriv_{action} action hook. Like this

add_action('wp_ajax_nopriv_make_booking', 'makeBooking');

EDIT: Oh, silly me. You're also missing wp_die(); from the end of your ajax response. See codex / AJAX in Plugins for more details.

function makeBooking(){
    echo "Home again";
    wp_die(); // this is required to terminate immediately and return a proper response
}

EDIT 2: You could also use wp_send_json instead of echoing your response.

add below actions

add_action( 'wp_ajax_makeBooking', 'makeBooking');
add_action( 'wp_ajax_nopriv_makeBooking', 'makeBooking');
Post a comment

comment list (0)

  1. No comments so far