We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x
Private

Wordpress - Javascript - JQuery - AJAX - PHP - need assitance with button AJAX request

High Priority
16 Views
Last Modified: 2020-06-26
Need assistance getting our newly configure button to pull the correct active user data from the WordPress database and then send it via a Curl Call.
Comment
Watch Question

Netty AdminNetwork Administrator

Author

Commented:


Have the following in a javascript file saved within the child theme(order-scripts.js):


jQuery( function( $ ) {
    $(document).ready(function() {
        $( document.body ).on( "click", "#payment #get_cc_order_url.get_cc_order_url", function(e) {
            e.preventDefault();
            console.log("Testing the ADD CARD Button");
        });
    });
});


Having the following inserted into the child theme's functions.php file:

add_action( 'wp_enqueue_scripts', 'setup_order_scripts', 15 );
function setup_order_scripts() {
 wp_register_script( 'netty_order_scripts', get_stylesheet_directory_uri() . '/order-scripts.js', array('jquery'), null, true);
 wp_localize_script( 'netty_order_scripts', 'nettyOrderParams', array( 'url' => admin_url( 'admin-ajax.php' )));
 wp_enqueue_script( 'netty_order_scripts' );
}



Have this curl call as a test curl call. Uploaded it via FTP to the site to test its ability to send to the custom URL. We need to pull the active user's ID, username, Email, and Billing Zip code and then send it via this curl call in JSON form.

<?php
$postData = [
    'UserID' => '223',
    'Email' => 'howaboutnow@test.com'
];
$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => 'https://someUrl.com',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_POSTFIELDS => json_encode($postData),
    CURLOPT_HTTPHEADER => ['Content-Type:application/json'],
]);
$response = curl_exec($curl);
var_dump(json_decode($response));


?>
Netty AdminNetwork Administrator

Author

Commented:


To get the active user info:

$user = wp_get_current_user();
$id = $user->ID;
$email = $user->user_email;
$username = $user->user_login;
Just need to figure out how to pull the billing zip code:
Netty AdminNetwork Administrator

Author

Commented:
Will the AJAX request replace the need for the curl call or will it work hand in hand with it?
David FavorFractional CTO
CERTIFIED EXPERT
Distinguished Expert 2019
Note: It appears you've posted your actual/real authorization credentials.

Please change them immediately at https://prod-95.eastus.logic.azure.com, else anyone can use your account.
CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019
Unlock this solution with a free trial preview.
(No credit card required)
Get Preview
Netty AdminNetwork Administrator

Author

Commented:
Hey guys, thanks for noticing that but I did not post the actual creds. I redacted them and changed them.

Going to try this now Chris, Thank you.
Netty AdminNetwork Administrator

Author

Commented:
I am getting a null response
CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019
Post up your JS file and your functions.php file and I'll take a look
Netty AdminNetwork Administrator

Author

Commented:
jQuery( function( $ ) {
    $(document).ready( function() {
        /**
         * AJAX Call to grab the Order URL from the server via the custom url coworker created in Azure logics
         */
        $( document.body ).on( "click", "#payment #get_cc_order_url.get_cc_order_url", function(e) {
            e.preventDefault();
            $.ajax({
                url  : ccOrderParams.url,
                data : { action: 'get_order_url' },
                type : 'post',
            }).done(function(response) {
                console.log(response)
            }).fail(function(error) {
                console.log("ERROR", error)
            })
        });
    });
})
Netty AdminNetwork Administrator

Author

Commented:
<?php

/**
 *  the AJAX handler
 */
add_action('wp_ajax_get_order_url', 'get_order_url');
function get_order_url()
{
    $data = [
        'message' => 'This has come from the Servers AJAX Handler',
    ];
    wp_send_json(json_decode($data));
}


/*
 * Enqueue scripts for cc button on checkout page
 */


add_action( 'wp_enqueue_scripts', 'setup_order_scripts', 15 );
function setup_order_scripts() {
 wp_register_script( 'cc_order_scripts', get_stylesheet_directory_uri() . '/order-scripts.js', array('jquery'), null, true);
 wp_localize_script( 'cc_order_scripts', 'ccOrderParams', array( 'url' => admin_url( 'admin-ajax.php' )));
 wp_enqueue_script( 'cc_order_scripts' );
}
/** Adding child theme's style.css **/
function tm_fixology_child_style_css(){
 wp_enqueue_style( 'fixology-child-style', get_stylesheet_directory_uri() . '/style.css' );
}
add_action( 'wp_enqueue_scripts', 'tm_fixology_child_style_css', 18 );


// Disable auto-complete on form.
add_filter( 'gform_form_tag', function( $form_tag ) {
 return str_replace( '>', ' autocomplete="off">', $form_tag );
}, 11 );
// Diable auto-complete on each field.
add_filter( 'gform_field_content', function( $input ) {
 return preg_replace( '/<(input|textarea)/', '<${1} autocomplete="off" ', $input );
}, 11 );
CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019
Ahhh - sorry Netty. I jumped the gun a little. At this stage, we don't need to be decoding JSON (that'll come later). Change the get_order_url() function to this:

function get_order_url()
{
    $data = [
        'message' => 'This has come from the Servers AJAX Handler',
    ];
    wp_send_json($data);
}

Open in new window

You'll see we're now just sending the array without first decoding it
CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019
Bit of bonus tip - keep your code organised - as a developer you start to get an 'eye' for code, and having organised code really helps with that:

<?php

/**
 * the AJAX handler
 */
add_action('wp_ajax_get_order_url', 'get_order_url');
function get_order_url()
{
    $data = [
        'message' => 'This has come from the Servers AJAX Handler',
    ];
    wp_send_json($data);
}


/**
 * Enqueue scripts for cc button on checkout page
 */
add_action( 'wp_enqueue_scripts', 'setup_order_scripts', 15 );
function setup_order_scripts() {
    wp_register_script( 'cc_order_scripts', get_stylesheet_directory_uri() . '/order-scripts.js', array('jquery'), null, true);
    wp_localize_script( 'cc_order_scripts', 'ccOrderParams', array( 'url' => admin_url( 'admin-ajax.php' )));
    wp_enqueue_script( 'cc_order_scripts' );
}


/**
 * Adding child theme's style.css
 */
add_action( 'wp_enqueue_scripts', 'tm_fixology_child_style_css', 18 );
function tm_fixology_child_style_css() {
    wp_enqueue_style( 'fixology-child-style', get_stylesheet_directory_uri() . '/style.css' );
}


/**
 * Disable auto-complete on form.
 */
add_filter( 'gform_form_tag', function( $form_tag ) {
    return str_replace( '>', ' autocomplete="off">', $form_tag );
}, 11 );


/**
 * Disable auto-complete on each field.
 */
add_filter( 'gform_field_content', function( $input ) {
    return preg_replace( '/<(input|textarea)/', '<${1} autocomplete="off" ', $input );
}, 11 );

Open in new window

I know it seems trivial, but scanning over organised code is just so much quicker - paricularly as your file grow
Netty AdminNetwork Administrator

Author

Commented:
Ok the AJAX handler is working now!! 
CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019
Excellent stuff Netty,

One final bit before you move on from this - security. Wehn dealing with AJAX like this, we need to make sure the call to your AJAX handler is secure. WP has a built in way of doing this using something called a nonce (It means Number Used Once!).

In your PHP functions file, change the setup_order_scripts() function to this:

 function setup_order_scripts() {
    $params = [
        'url' => admin_url( 'admin-ajax.php' ),
        'nonce' => wp_create_nonce('security_matters'),
    ];

    wp_register_script( 'cc_order_scripts', get_stylesheet_directory_uri() . '/order-scripts.js', array('jquery'), null, true);
    wp_localize_script( 'cc_order_scripts', 'ccOrderParams', $params);
    wp_enqueue_script( 'cc_order_scripts' );
}

Open in new window

And add the security check to the beginning of your get_order_url() function:

function get_order_url()
{
    check_ajax_referer('security_matters', 'security');
    ...

Open in new window


And finally change your JS Ajax call to this:

$.ajax({
    url  : ccOrderParams.url,
    data : {
        action : 'get_order_url',
        security : ccOrderParams.nonce,
    },
    type : 'post',
}).done(function(response) {
    console.log(response)
}).fail(function(error) {
    console.log("ERROR", error)
})

Open in new window

Reload your site and run through the test once more, just to make sure it's still working
Netty AdminNetwork Administrator

Author

Commented:
Got it, updating it now and then moving on to the next part/question
Netty AdminNetwork Administrator

Author

Commented:
It is working well with the security in place now too. So all good on that. Thank you!!
CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019
Sweet :)
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a free trial preview!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.