1

I'm fairly new with JavaScript, I'm trying to give access to users to update products stock for WooCommerce. I've made "Update" button to run the script, but it won't run, the page only refreshes. But when I execute the script from console, it works (eg. js_update_stock('20');)

I'm working by modifying existing plugin for WordPress, so I'm sorry if the codes are a bit scattered. If you need anything else, please let me know.

HTML side of things:

<input type="number" id="stock'. $postid . '" name="stock'. $postid .'" value="'. get_post_meta( $postid, '_stock', true ) .'">

<button class="button button-primary" style="margin-bottom: 3px; padding-left: 24px; padding-right: 24px;" onclick="js_update_stock(\''. $postid .'\')">'. __('Update','update_button') .'</button>

I put this script on the same page:

echo '<script type="text/javascript">
    function js_update_stock(product_id) {
        var isnum = /^\d+$/.test(document.getElementById("stock" + product_id).value);
        if(isnum){
            if(confirm("Do you really want to update the stock of this product?")){
                var data = {
                    action: \'update_stock\',
                    security: \'' . $ajax_nonce . '\',
                    id: product_id,
                    stock: document.getElementById("stock" + product_id).value
                };
                // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
                jQuery.post(ajaxurl, data, function(response) {
                    if(response == \'true\'){
                        location.reload(true);
                    }
                });
            }
            else{
                // do nothing
            }
        }
        else{
            alert("Please enter a valid stock quantity");
        }
    }
    </script>';

AJAX Callback function:

add_action('wp_ajax_update_stock', 'update_stock_callback');
function update_stock_callback() {
    check_ajax_referer( 'blahblah', 'security' );
    if(isset($_POST['id'])){
        $id = intval( $_POST['id'] );
        $stock = intval( $_POST['stock'] );
        wc_update_product_stock( $id, $stock );
        echo 'true';
    }
    else{
        echo 'false';
    }
    die(); // this is required to return a proper result
}

Any help is appreciated, as this has been bugging me for 2 days now. Thank you.

  • add an `alert` line to the top of the function and try again to see if it does get fired at all. I assume your button is inside a `form` element and thus has a default functionality probably – Dellirium Jul 12 '18 at 08:06

4 Answers4

1

By default a button is of type submit so it's submitting your form, thats why your page refreshes.

You want to define button type as button so form doesn't submit.

<button type="button" class="button button-primary" style="margin-bottom: 3px; padding-left: 24px; padding-right: 24px;" onclick="js_update_stock(\''. $postid .'\')">'. __('Update','update_button') .'</button>
TheDrot
  • 4,246
  • 1
  • 16
  • 26
1

The page is refreshing because I guess the button you are using is in a form. So when you click on it, it will launch the request for the form and leave the page.

So to prevent that, you will just need to add the click event to your function and cancel it before the page has unload :

<button class="button button-primary" 
 style="margin-bottom: 3px; padding-left: 24px; padding-right: 24px;" 
 onclick="js_update_stock(event, \''. $postid .'\')">
      '. __('Update','update_button') .'
</button>

And for javascript :

function js_update_stock(e, product_id) {
    e.preventDefault();
    // more code...

Javascript event prevent default on W3schools

I hope this solved your problem ;)

Onoulade
  • 138
  • 10
0

For most of the new browsers, default type of button element is "Submit". That means, when click on it, your form will get submitted before calling your "onclick" function. Also, in your form you may not have specified action attribute, and that's why form is submitting to self.

You can specify type attribute for your button element to "button" specifically and it will now call to your "onclick" function.

For more information on button default type according to browser, visit : What is the default button type?

0

Instead of button tag, you can use :

<a href='javascript:void(0);' id='updateBtn' class='btn btn-default'>Update</a>

$(document).ready(function () {
  $('#updateBtn').on('click', function () {
    // Make AJAX call here.  
    // Your logic will come here.
    $.ajax({
      url: 'Add url here',
      data: 'Add data which is need to be update in json',
      type: 'POST',
      dataType: 'json',
      success: successCallback,
      complete: completeCallback,
      error: errorCallback
    })
  });

  var successCallback = function () {
                         // AJAX success callback
                       }

  var completeCallback= function () {
                         // AJAX complete callback
                       }
  var errorCallback= function () {
                         // AJAX error callback
                       }
});

NOTE: Also make sure you are not redirecting from backend(PHP) and just giving back response with statusCode.

palash-kulkarni
  • 397
  • 3
  • 17