1

I have created a plugin where I am recieving the data via rest url and I am getting the correct output when I use var_dump($final_price_return); and no return in success call. PHP code that returns the value:

function handle_query($data) {
    // Handle the form data that is posted
    // Get all parameters from form
    $output = $data->get_params();

    // Check if nonce is valid, if not, respond back with error
    if (!wp_verify_nonce($output['_wpnonce'], 'wp_rest')) {
        return new WP_Rest_Response('Oops - Invalid request', 422);
    }

    // done calculations here - skipped that code for now

    var_dump($final_price_return);
    return new WP_REST_Response($final_price_return, 200);
}

JQuery Code

jQuery(document).ready(function () {
        $('#calx').on('click', function (e) {
          $('#msform').validate({
            rules: {
              // simple rule, converted to {required:true}
              service: 'required',
              square_feet: 'required',
            },
            messages: {
              service: 'Please select service',
              square_feet: 'Please select your square feet area',
            },
            submitHandler: function () {
              var formData = $('#msform').serialize()
              jQuery.ajax({
                url: "<?php echo get_rest_url(null, 'bohio/v1/submit'); ?>",
                type: 'POST',
                data: formData,
                cache: false,
                success: function (res) {
                  console.log(res)
                  $('#total_amount').html(res)
                  $('#totalbox').removeClass('d-none')
                  $('#email_form').removeClass('d-none')
                },
              })
            },
          })
        })

1 Answer 1

0

You can try this... ...rather than returning the value, send a JSON success message.

$response = new WP_REST_Response($final_price_return, 200);
wp_send_json_success( $response );
wp_die();  
//you have to end the process, so if you're getting just a 0 returned in your JS success, it's because of this.

Then, in your JS/jQuery:

success: function (success, data) {
  var res = success.data;
  console.log(res)
  $('#total_amount').html(res)
  $('#totalbox').removeClass('d-none')
  $('#email_form').removeClass('d-none')
},

It may even just be that your lack of wp_die() or lack of exit() at the end of your AJAX callback is the issue.

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.