0

I am unable to get this insert to db function to work using ajax and a form. When I execute this, I receive a blank alert box on success.

HTML

<div id="rsvpContent">  
     <form id="Attendevent" action="">
     <input id="attend" name="attend" type="checkbox" value="yes" /><label for="attent">Yes, I plan to attend.</label>
     <input type="hidden" value="<?php echo get_the_ID(); ?>" name="event_id"/>
     <input type="hidden" value="<?php echo $current_user->ID; ?>" name="user_id"/>
     </form>
</div>

PHP

 add_action('wp_ajax_Attending', 'eventAttend');
 add_action('wp_ajax_nopriv_Attending', 'eventAttend');

 function eventAttend() {
  global $wpdb;

  $fields = array();
  parse_str($_POST['data'], $fields);

if($fields['attend'] == 'yes') {

   $wpdb->insert('wp_event_attendants', array( 'event_id' => $fields['event_id'], 'user_id' => $fields['user_id'])); 

    echo $wpdb->print_error();
    }
    echo 'Not working.';
   die();
}

JS (In header.php)

    $("#attend").click(function(){
    var form = $("#Attendevent").serialize();

    $.ajax({
      url: "<?php echo admin_url('admin-ajax.php'); ?>",
      beforeSend: function() {
          alert(form);
      },
      type:'POST',
      data:{
          action: "Attending",
          "data": form 
          },
      dataType:  'html',
      success: function(data) {
            alert(data);
      }
    }); 
});

DEBUGGING INFO

[07-Mar-2013 17:47:09] PHP Notice: Undefined index: attend in /wp-content/plugins/event-calendar-reg/functions.php on line 198

2
  • Are your JS alerts firing? And if so, what do they say? By the way, I wouldn't use 'form' as a JS variable name. That seems to be inviting problems.
    – vancoder
    Commented Mar 7, 2013 at 17:37
  • I'd also advise using Firebug to see what's going on.
    – vancoder
    Commented Mar 7, 2013 at 17:38

1 Answer 1

1

You are serializing your form data before posting it to your PHP function, but you do not unserialize it at the other end. Therefore your check for $_POST['attend'] == 'yes'will always fail.

Try the following (untested).

    function eventAttend() {
    $fields = array( );
    parse_str( $_POST['data'], $fields );
               if($fields['attend'] == 'yes') {

global $wpdb;

                    $wpdb->insert('wp_event_attendants', array( 'event_id' => $fields['event_id'], 'user_id' => $fields['user_id'])); 

                    echo $wpdb->print_error();
                }
     die();
    }
2
  • Is the unserializing always required or only in wordpress?
    – MF1
    Commented Mar 7, 2013 at 18:35
  • 1
    You always have to unserialize stuff that's serialized. serialization is just for storage/transit purposes.
    – vancoder
    Commented Mar 7, 2013 at 18:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.