Home > Software design >  Update user meta from checkout page before payment
Update user meta from checkout page before payment

Time:05-21

Could you help me please - I have separated billing/shipping address form on the checkout page with the button Next. I want save the address in DB via AJAX on click button Next. Now I have right return in POST when I change data in the form address, but the data is not updated in a user profile.

function.php

    add_action("wp_ajax_updateAddress", "updateAddress");
add_action("wp_ajax_nopriv_updateAddress", "my_must_login");

function updateAddress($user_id) {


    if (isset($_POST['billing_first_name'])) {
            update_user_meta($user_id, 'billing_first_name', sanitize_text_field(($_POST['billing_first_name'])));
        }

        if (isset($_POST['billing_last_name'])) {
            update_user_meta($user_id, 'billing_last_name', sanitize_text_field(($_POST['billing_last_name'])));
        }


}

file.js

jQuery(document).ready( function($) {

    $( '#update_address' ).click(function(){
        const billing_first_name = $("input[name=billing_first_name]").length ? $("input[name=billing_first_name]").val() : '';
        const billing_last_name = $("input[name=billing_last_name]").length ? $("input[name=billing_last_name]").val() : '';
        $.ajax({
            url : ajax_object.ajaxurl,
            type: 'POST',
            data : {
                action: "updateAddress",
                billing_first_name,
                billing_last_name,
            },
            success: function( data ) {
                alert( data.message );
            }
        });

    })

})

CodePudding user response:

at first, please use only lowercase action name

"updateAddress" -> "updateaddress"

second, you try alert "message", but never returning data from php function.

success: function( data ) {
                alert( data.message );
            }

third, add return data to your php funtion like:

wp_send_json_success(["message" => "done"]);

please make sure your ajax call get response from wordpress with code 200, in case you get a 40x, your php code maybe never run.

in php function add $user_id = get_current_user_id()

  • Related