0

I have the following jQuery function in my custom-js.js file:

$(function() {

        $(".product-vote-button-up").click(function(){
            var productID = $(this).attr('productID');      

            var request = $.ajax({
                url: "/wordpress/wp-content/themes/my-theme/js/ajax/vote-database-update.php",
                type: "POST",
                data: {id : productID},
            });

            request.done(function() {
                $("#product-" + productID + " .item-product-footer-vote-container").html('Thanks for your vote!');
            });

            request.fail(function(jqXHR, textStatus) {
              alert( "Request failed: " + textStatus );
            });
        });

    }); 

Using AJAX, I want to update the count of my vote in my custom product database with SQL commands. To do so, I want to have a access to the WordPress function in vote-database-update.php such as $wpdb. The only way I managed to make it work so far, is by adding:

require_once( explode( "wp-content" , __FILE__ )[0] . "wp-load.php" );

in my PHP file. However, I think this is not really clean and after reading some of the documentation, I think there is another way around with admin-ajax.php. In most of the documentation, it describes how to add AJAX in a plugin with admin-ajax.php. I'm kind of confused since my vote-database-update.php is not really a plugin (or I might not have the correct definition of a WordPress plugin). What would be the right way to include the WordPress functions in my vote-database-update.php` file?

  • in general, trying to access directly any php file in your theme (or plugin) is going to fail for various reasons. Your core assumption that might fail are that 1. you can run scripts on that directory 2. the location og the wp-content directory. There might be other gotcha that escape my mind right now – Mark Kaplun Mar 5 '17 at 16:20
1

Yes, using admin-ajax.php is the way to go here. To use it, you would do something like the following:

in vote_database_update.php

// hook into admin-ajax
// the text after 'wp_ajax_' and 'wp_ajax_no_priv_' in the add_action() calls
// that follow is what you will use as the value of data.action in the ajax
// call in your JS

// if the ajax call will be made from JS executed when user is logged into WP,
// then use this version
add_action ('wp_ajax_call_your_function', 'your_function') ;
// if the ajax call will be made from JS executed when no user is logged into WP,
// then use this version
add_action ('wp_ajax_nopriv_call_your_function', 'your_function') ;

function
your_function ()
{
    if (!isset ($_REQUEST['id'])) {
        // set the return value you want on error
        // return value can be ANY data type (e.g., array())
        $return_value = 'your error message' ;

        wp_send_json_error ($return_value) ;
        }

    $id = intval ($_REQUEST['id']) ;
    // do processing you want based on $id

    // set the return value you want on success
    // return value can be ANY data type (e.g., array())
    $return_value = 'your success message/data' ;

    wp_send_json_success ($return_value) ;
}

in custom-js.js

(function ($) {
    $('.product-vote-button-up').click (function () {
        var productID = $(this).attr ('productID') ;

        $.ajax ({
            url: '/wp-admin/admin-ajax.php',
            type: 'POST',
            dataType: 'JSON',
            data: {
                // the value of data.action is the part AFTER 'wp_ajax_' in
                // the add_action ('wp_ajax_xxx', 'yyy') in the PHP above
                action: 'call_your_function',
                // ANY other properties of data are passed to your_function()
                // in the PHP global $_REQUEST (or $_POST in this case)
                id : productID
                },
            success: function (resp) {
                if (resp.success) {
                    // if you wanted to use the return value you set 
                    // in your_function(), you would do so via
                    // resp.data, but in this case I guess you don't
                    // need it
                    $('#product-' + productID + ' .item-product-footer-vote-container').html ('Thanks for your vote!') ;
                    }
                else {
                    // this "error" case means the ajax call, itself, succeeded, but the function
                    // called returned an error condition
                    alert ('Error: ' + resp.data) ;
                    }
                },
            error: function (xhr, ajaxOptions, thrownError) {
                // this error case means that the ajax call, itself, failed, e.g., a syntax error
                // in your_function()
                alert ('Request failed: ' + thrownError.message) ;
                },
            }) ;
        }) ;
    })(jQuery) ;

I hope this helps.

  • Hei paul, i am trying what you've suggested in your answer but it gives me an error "500", can you suggest me what i should do? – sumit chauhan Feb 15 '18 at 11:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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