403 error with ajax post request
-
Hello i have a worpdress sit on my localhost i try to create a form that send a email via ajax request but i’m block i have a 403 error that don’t know how to fix
i create a js file with the right structure the data is sent correctly but but i don’t know why the ajax request can’t pass i check the cachefunction javascript_variables(){ ?> <script type="text/javascript"> var ajax_url = '<?php echo admin_url( "admin-ajax.php" ); ?>'; var ajax_nonce = '<?php echo wp_create_nonce( "secure_nonce_name" ); ?>'; </script><?php } add_action ( 'wp_head', 'javascript_variables' ); //AJAX REQUEST function twentytwentychild_asset() { // ... wp_enqueue_script('jquery'); // Charger notre script wp_enqueue_script( 'twentytwentychild', get_stylesheet_directory_uri(). '/assets/js/script.js', array('jquery'), '1.0', true ); // Envoyer une variable de PHP à JS proprement wp_localize_script('twentytwentychild', 'ajaxurl', admin_url('admin-ajax.php')); } add_action('wp_enqueue_scripts', 'twentytwentychild_asset');the jsfile :
(function ($) { $(document).ready(function () { jQuery('form[name="form_result"]').on('submit', function() { var form_data = jQuery(this).serializeArray(); console.log('hello'); form_data.push({"name" : "security", "value" : ajax_nonce }); console.log(form_data); // Here is the ajax petition jQuery.ajax({ url : ajax_url, type : 'post', data : form_data, success : function( response ) { // You can craft something here to handle the message return alert(response); }, fail : function( err ) { alert("there was an error: " + err ); } }); // This return prevents the submit event to refresh the page. return false; }); }); })(jQuery);function send_form(){ // This is a secure process to validate if this request comes from a valid source. check_ajax_referer( 'secure-nonce-name', 'security' ); /** * First we make some validations, * I think you are able to put better validations and sanitizations. =) */ if ( empty( $_POST["name"] ) ) { echo "Insert your name please"; wp_die(); } if ( ! filter_var( $_POST["email"], FILTER_VALIDATE_EMAIL ) ) { echo 'Insert your email please'; wp_die(); } if ( empty( $_POST["fcPhone"] ) ) { echo "Insert your phone please"; wp_die(); } $to = 'test@gmail.com'; $subject = 'Un potentiel consultant viens de faire une simulation!'; $body = 'From: ' . $_POST['name'] . '\n'; $body .= 'Email: ' . $_POST['email'] . '\n'; $body .= 'Message: ' . $_POST['fcPhone'] . '\n'; $headers = array('Content-Type: text/html; charset=UTF-8'); wp_mail( $to, $subject, $body, $headers ); echo 'Done!'; wp_die(); }
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
The topic ‘403 error with ajax post request’ is closed to new replies.