0

I'm running out of ideas why does my ajax function return 0. I'm trying to get stripe payment and after that my function will try and make a booking through checkfront api.

Any ideas or help is more than welcomed at this point!

Here is my theme's function for AJAX call:

add_action( 'wp_ajax_action_varaa_AJAX', 'varaa_AJAX' );
add_action('wp_ajax_nopriv_varaa_AJAX', 'varaa_AJAX');

function varaa_AJAX(){
  global $chargeID;
  global $bookingStatus;

  $amount = $_POST['amount'];
  $token = $_POST['stripeToken'];
  $name = $_POST['name'];
  $cardName = $_POST['cardName'];
  $email = $_POST['email'];
  $phone = $_POST['phone'];
  $accept_terms = $_POST['accept'];
  $insurance = $_POST['insurance'];
  $extradates = $_POST['extradates'];
  $id = $_POST['session_id'];
  $form = array(
    'customer_name' => $name,
    'customer_email' => $email,
    'customer_phone' => $phone,
    'accept_terms' => $accept_terms
  );

  function make_payment($token, $name, $cardName, $email, $phone, $amount, $insurance, $extradates) {
    require_once(get_template_directory() . 'vendor/stripe/stripe-php/init.php');
    global $chargeID;

    $stripe_settings = get_option('stripe_settings');

    // Set your secret key: remember to change this to your live secret key in production
    // See your keys here: https://dashboard.stripe.com/account/apikeys
      if(isset($stripe_settings['test_mode']) && $stripe_settings['test_mode']) {
          $secret_key = $stripe_settings['test_secret_key'];
      } else {
          $secret_key = $stripe_settings['live_secret_key'];
      }

      \Stripe\Stripe::setApiKey($secret_key);

    // ANONYYMI VARAUS

      // Create customer and assign charge with $token
        $customer = \Stripe\Customer::create(array(
            "source" => $token,
            "email" => $email,
            "description" => "Uusi anonyymi varaus.",
            "metadata" => [
              "nimi" => $name,
              "kortissa oleva nimi" => $cardName,
              "puhelin" => $phone,
              "insurance" => $insurance,
              "extradates" => $extradates
            ]
        ));

      // Get customer id from create above
        $stripeID = $customer->id;

      // Charge customer
        $charge = \Stripe\Charge::create(array(
          "amount" => $amount, // Amount in cents
          "currency" => "eur",
          "capture" => false,
          "customer" => $stripeID
        ));

      // Get charge id from charge above
        $chargeID = $charge->id;
  }

  // Create booking
    function create_booking($id, $form){
      require_once(get_template_directory() . 'lib/booking.php');
      require_once(get_template_directory() . 'lib/form.php');
      global $bookingStatus;
      global $bookingId;

      $Booking = new Booking();

      $bookIt = $Booking->create(
        array(
          'session_id' => $id,
          'form' => $form
        )
      );

      $bookingStatus = $bookIt['request']['status'];

      $bookingId = $bookIt['booking']['booking_id'];

      echo $bookIt;

    }

// Run functions above

  // Check WP nonce
    if ( 
        ! isset( $_POST['nonce'] ) 
        || ! wp_verify_nonce( $_POST['nonce'], 'bookNow' ) 
    ) {

       print 'Sorry, your nonce did not verify.';
       exit;

    } else {
    // Create a customer and charge card
      try {
          // Create charge
            make_payment($token, $name, $cardName, $email, $phone, $amount, $insurance, $extradates);

          // Create booking
            create_booking($id, $form);

          // Check if booking went through
            if ( $bookingStatus = 'OK' ) {
              // Capture charge
                $ch = \Stripe\Charge::retrieve( $chargeID );
                $ch->capture();

              // Booking success  
                $value =  array('msg' => 'success', 'bookingStatus' => $bookingStatus, 'bookingID' => $bookingId );
                echo json_encode($value);

            } else {
              // Refund charge
                $re = \Stripe\Refund::create(array(
                  "charge" => $chargeID
                ));

              $value =  array('msg' => 'error' );
              echo json_encode($value);
            }

      } catch(\Stripe\Error\Card $e) {
        // The card has been declined
          $value = array('error' => true); // or $result = array('error' => false);
          echo json_encode($value);
      }
    }
  die();
}

And here is my jQuery AJAX function:

                      var token = response.id,
                          amount = vm.total * 100,
                          name = vm.form.name,
                          cardName = vm.form.cardName,
                          phone = vm.form.phone,
                          email = vm.form.email,
                          terms = vm.form.terms,
                          insurance  = vm.form.insurance,
                          action = 'varaa_AJAX',
                          id = vm.sessionId;

                      var nonce = $('#ilmtrail_nonce').val();
                      var extradates = Object.keys( vm.daysBetweenStartStop ).length * 25 - 25;

                          jQuery.ajax({
                            url: AJAXurl,
                            data: { action: action, nonce: nonce, stripeToken: token, insurance: insurance, extradates: extradates, name: name, phone: phone, email: email, cardName: cardName, amount: amount, accept: terms, session_id: id },
                            type: 'post',
                            success: function(value) {
                              if ( value.msg === 'success' ) {

                                console.log(value);
                                vm.form.sending = false;
                                vm.form.sent = true;
                                $('#receipt').openModal();
                                return true;

                              } else{

                                alert ('Jokin meni mönkään. Tarkista tiedot ja kokeile uudestaan, ja jos virhe toistuu ole yhteydessä meihin niin saadaan varaus läpi!');
                                console.log(value);
                                vm.form.sending = false;
                                $form.find('.submit').prop('disabled', false);
                                return false;

                              }

                            },
                            error: function(data) {
                              vm.form.sending = false;
                              $form.find('.submit').prop('disabled', false); 
                              console.log(data);
                              alert ('Jokin meni mönkään. Tarkista tiedot ja kokeile uudestaan, ja jos virhe toistuu ole yhteydessä meihin niin saadaan varaus läpi!');
                              return false;
                            }
                          });
7
  • Is there any problem with WordPress itself?
    – Max Yudin
    Oct 27, 2016 at 12:56
  • @MaxYudin Well when I migrated the site to live server it had a problem with urls. So when Im accessing to example.com it redirects me to reinstalling WP. I bypassed this by adding different site url (example.com/test, when WP url is still example.com). I know this was due db migration but I couldn't find any solutions to this. My wp-config.php was matching to db settings etc. (might have to make another question from this error.
    – Eljas
    Oct 27, 2016 at 13:00
  • Duplicator
    – Max Yudin
    Oct 27, 2016 at 13:16
  • @MaxYudin I usually use dublicator but this time it didn't work, so I used wp all in one migration.
    – Eljas
    Oct 27, 2016 at 13:20
  • 2
    Please don't just dump a lot of code. make debuging effort and isolate the problem first Oct 27, 2016 at 13:21

2 Answers 2

1

The problem lies here:

add_action( 'wp_ajax_action_varaa_AJAX', 'varaa_AJAX' );
add_action('wp_ajax_nopriv_varaa_AJAX', 'varaa_AJAX');

Specifically:

wp_ajax_action_varaa_AJAX

You didn't replace the word action with varaa_AJAX, it should instead be:

add_action( 'wp_ajax_varaa_AJAX', 'varaa_AJAX' );
add_action('wp_ajax_nopriv_varaa_AJAX', 'varaa_AJAX');

However, I would recommend instead using the WP REST API and register_rest_route, which should simplify your code and eliminate these kinds of mistakes.

2
  • Do you have an example of how this could be simplified?
    – jgraup
    Oct 27, 2016 at 15:13
  • That would be a new question, and would massively expand the scope of the answer by introducing register_rest_route and other things if I were to put it here, but keep in mind with the REST API, you just return what you want to return, no exit or die statements, no wp_json_encode, etc etc
    – Tom J Nowell
    Oct 27, 2016 at 15:31
1

Your function varaa_AJAX() must echo something to ajax. Also, please include wp_die(); after echo statement.

Your code:

 add_action( 'wp_ajax_action_varaa_AJAX', 'varaa_AJAX' );
    add_action('wp_ajax_nopriv_varaa_AJAX', 'varaa_AJAX');    
    function varaa_AJAX(){      
        echo "Ajax Response";
        wp_die(); 
    }

Edit:

add_action( 'wp_ajax_varaa_AJAX', 'varaa_AJAX' );
    add_action('wp_ajax_nopriv_varaa_AJAX', 'varaa_AJAX');    
    function varaa_AJAX(){      
        echo "Ajax Response";
        wp_die(); 
    }
4
  • That returns 0 aswell. I do have die(); in my original function. Is there any main differences using wp_die(); or die();?
    – Eljas
    Oct 27, 2016 at 13:11
  • wp_die() can return WP_Errorobject for analysis.
    – Max Yudin
    Oct 27, 2016 at 13:19
  • 1
    Remove "action_" from below statement and try: add_action( 'wp_ajax_action_varaa_AJAX', 'varaa_AJAX' ); Oct 27, 2016 at 13:20
  • I have edited my answer Oct 27, 2016 at 13:41

Your Answer

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

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