Maybe It’s the Appropriate Answer for You!
Accordingly to this question the more reasonable answer is to use wp_send_json()
with (if only necessary) the wp_send_json_success()
and wp_send_json_error()
functions. They’ll return an JSON Object back to the AJAX Request and it will automatically die()
for you. It will look something like this:
add_action( 'wp_ajax_origin', 'create_an_ajax_request_origin_form' );
add_action( 'wp_ajax_nopriv_origin', 'create_an_ajax_request_origin_form' );
function create_an_ajax_request_origin_form() {
$fields = array(
'address' => wp_kses( sanitize_text_field( $_POST[ 'origin' ][ 'address' ] ), array() ),
'number' => wp_kses( intval( absint( $_POST[ 'origin' ][ 'number' ] ) ), array() ),
'address_two' => wp_kses( sanitize_text_field( $_POST[ 'origin' ][ 'address_two' ] ), array() ),
'city' => wp_kses( sanitize_text_field( $_POST[ 'origin' ][ 'city' ] ), array() ),
);
wp_send_json( $fields ); // there's no need to use die() function if you're using wp_send_json()
}
If everything worked properly, now you might be able to reach those $fields
data from inside the AJAX Request, and it’ll look something like this:
$.post( origin.admin_ajax, origin_data, function( response ) {
console.log( response.city ); // this will print out the response sent by the Backend through the wp_send_json() function
} );
Obs: I changed the superglobal
$_REQUEST
variable to$_POST
, which in my opinion is the most appropriate thing to do. Because we are using a$.post
method to send and get the data between the Frontend and the Backend.
The Real World Answer
Till that point I didn’t know that I needed to extend the data into the WordPress Dashboard. So, the only option (in this case) was to get everything filtered by the create_an_ajax_request_origin_form()
function and store it inside the superglobal $_COOKIE
array.
I preferred to make use of JavaScript Cookie Repository to deal with the Cookies in the JavaScript, that way made more sense of why I’m actually using Cookies.