Question

I am developing a plugin for WordPress.

Looking for a solution

I want to insert record (it may be any CRUD operation) when the user click on the link order-button

I am very much new to Ajax so getting confused how to achieve when the user clicks on the Order link on the product grid it should be added to the custom table.

I have set up all bug not able to get link's data attribute in the Ajax callback function to pass it to the jQuery ajax method.

Enqueue scripts

function gs_enqueue_ajax_scripts()
{
    wp_register_script('gs_ajax', GROUP_SHOP_ROOT . 'public/js/orders-ajax.js', ['jquery'], 1.0, true);
    wp_localize_script('gs_ajax', 'ajax_vars', [
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce'    => wp_create_nonce('gs_nonce')
    ]);
    wp_enqueue_script('gs_ajax');
}

add_action('wp_enqueue_scripts', 'gs_enqueue_ajax_scripts');

Ajax actions and callback function

I have tried passing static data and getting in the console output. Otherwise, it is giving null as it is not considering setting data directly into the AJAX data parameter.
How can I get data dynamically in callback function from the clicked anchor tag?

add_action('wp_ajax_gs_order', 'gs_ajax_callback');
add_action('wp_ajax_nopriv_gs_order', 'gs_ajax_callback');

function gs_ajax_callback()
{
    /**
     * I have set statically to check if it works
     * Of course, this is working since it is static
     * BUT I WANT DATA HERE DYNAMICALLY TO PASS IN AJAX
     */
    /*$data = [
        'product_groups' => 1,
        'products' => 5
    ];*/

    /*echo json_encode($data);*/

    // run the query to add entry
    /*$order = new Group_Shop_Order();
    $order->create_order(194, $products_ids, $product_groups_ids);*/

    wp_die();
}

HTML - Product Grid Item

<li class="gs-p-item">
    <div class="gs-p-item-container">
        <p class="gs-p-name">
            <a href="http://to-product-page" title="Id adipisci dolores dicta">Id adipisci dolores dicta</a>
        </p>
        <p class="gs-p-price">38.90</p>
        <a class="gs-button order-button et_pb_button" data-pid="168" href="javascript:void(0)" id="gs-p-168">Order</a>
    </div>
</li>

Javascript

data parameter is returning null value

var $button = $('.order-button');
console.log(ajax_vars);
$button.attr('href', 'javascript:void(0)');

$button.on('click', function () {

    $.ajax({
        type: "POST",
        url: ajax_vars.ajax_url,
        data: {
            action: 'gs_order',
            nonce_data: ajax_vars.nonce,
            product_groups: $(this).data("pgid"),
            products: $(this).data("pid")
        },
        dataType: 'JSON',
        success: function (data) {
            $('#response').html(data);
            console.log(data);
        },
        error: function (data) {
            $('#response').html(data);
            console.log("Error is there"); //error
        }
    }); // ajax end

}); // on button click

Console output

Object
    ajax_url: "http://wpdev.org/wp-admin/admin-ajax.php"
    nonce: "34cb70d514"
    __proto__: Object


null
Était-ce utile?

La solution

If this is your request data for an AJAX POST:

data: {
    action: 'gs_order',
    nonce_data: ajax_vars.nonce,
    product_groups: $(this).data("pgid"),
    products: $(this).data("pid")
},

Then you access product_groups and products like this:

$data = [
    'product_groups' => $_POST['product_groups'],
    'products'       => $_POST['products'],
];

Just make sure you sanitize and escape the data as required. If they're going to be IDs you can just use absint():

$data = [
    'product_groups' => absint( $_POST['product_groups'] ),
    'products'       => absint( $_POST['products'] ),
];

And to verify the nonce, use:

check_ajax_referer( 'gs_nonce', 'nonce_data' );

So all together:

function gs_ajax_callback()
{
    check_ajax_referer( 'gs_nonce', 'nonce_data' );

    $data = [
        'product_groups' => absint( $_POST['product_groups'] ),
        'products'       => absint( $_POST['products'] ),
    ];

    $order = new Group_Shop_Order();
    $order->create_order( 194, $data['products'], $data['product_groups'] );

    wp_die();
}

PS: I have no idea what Group_Shop_Order is, or how it works, so I can't say whether the usage of $order->create_order() is correct. I'm just going of your code for that.

Licencié sous: CC-BY-SA avec attribution
Non affilié à wordpress.stackexchange
scroll top