javascript - WordPress AJAX call not executing PHP -


i'm trying custom ajax action on wordpress isn't working. have following form:

<form method='post' name='form-bid-<?php echo get_the_id() ?>' class="bid-form">     <input type='submit' name='<?php echo get_the_id()?>' value='licitar' class='bidvalue'>     <?php wp_nonce_field('ajax-bid-nonce', $post->id); ?> </form> 

the form way because it's generated inside loop, 1 every post on site, therefore use post id unique name input.

then, capture form submit on custom javascript file:

jquery(document).ready(function($) {  // perform ajax bid on form submit $('form.bid-form').on('submit', function(e) {      var action = 'ajaxbid';     var auction_id = e.target.name.substring('form-bid-'.length);     var security_container = "#".concat(auction_id);     var security = $(security_container).val();      $.ajax({         type: 'post',         datatype: 'json',         url: ajax_bid_object.ajaxurl,          data: {              'action': action,             'id': auction_id,             'security': security         },          success: function(data) {             console.log(data);         }     });      e.preventdefault(); });  }); 

this part works, , prints 0 on console upon success.

finally, have php file register script , have function want call upon form submission:

function ajax_bid_init() {     wp_register_script('ajax-bid-script', get_template_directory_uri() .'/js/ajax-bid-script.js', array('jquery') );      wp_enqueue_script('ajax-bid-script');      wp_localize_script( 'ajax-bid-script', 'ajax_bid_object', array(          'ajaxurl' => admin_url( 'admin-ajax.php' )     ));      // enable user no privileges run ajax_bid() in ajax     add_action( 'wp_ajax_nopriv_ajaxbid', 'ajax_bid' ); }  add_action('init', 'ajax_bid_init');  function ajax_bid() {     // first check nonce, if fails function break     check_ajax_referer( 'ajax-bid-nonce', 'security');     echo json_encode(array('message'=>__('success')));       die(); } 

for now, wanted function return array , display on console. however, code never seems run through here, , ajax response 0.

i have done quite similar approach both login , registration on website , both work. i've compared 3 endless times , cannot seem find i'm missing here.

found issue! forgot mention trying logged user, problem line:

add_action( 'wp_ajax_nopriv_ajaxbid', 'ajax_bid' ); 

it should instead:

add_action( 'wp_ajax_ajaxbid', 'ajax_bid' ); 

i copied first login , register forms, made sense available non-logged users. bids exact opposite.

just future reference, can register both (wp_ajax , wp_ajax_nopriv) same function if want executable both logged , non-logged users.


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -