Link to home
Start Free TrialLog in
Avatar of Netty Admin
Netty AdminFlag for United States of America

asked on

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

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.
Avatar of Netty Admin
Netty Admin
Flag of United States of America image

ASKER



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");
        });
    });
});

Open in new window



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' );
}

Open in new window




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));


?>

Open in new window



To get the active user info:

$user = wp_get_current_user();
$id = $user->ID;
$email = $user->user_email;
$username = $user->user_login;

Open in new window

Just need to figure out how to pull the billing zip code:
Will the AJAX request replace the need for the curl call or will it work hand in hand with it?
Avatar of David Favor
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.
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.
I am getting a null response
Post up your JS file and your functions.php file and I'll take a look
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)
            })
        });
    });
})

Open in new window

<?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 );

Open in new window

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
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
Ok the AJAX handler is working now!! 
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
Got it, updating it now and then moving on to the next part/question
It is working well with the security in place now too. So all good on that. Thank you!!
Sweet :)