1

I've never used ajax in wordpress before and I'm trying to make a simple ajax request by following some video tutorials on youtube but it always return this error message: Failed to load resource: the server responded with a status of 400 (Bad Request)

My javascript (inside my own template file):

jQuery.ajax({
                url: ajaxurl,
                type: "POST",
                dataType: 'json',
                data: {
                    action: 'my_action'
                },

                success: function ( response ) {
                    console.log("success");
                    alert("success");   
                },
                error: function( error ){
                    console.log("error");
                    alert("error");
                }
            });

my functions.php file:

<?php



add_action('wp_ajax_my_action', 'insertEmail');
add_action('wp_ajax_nopriv_my_action', 'insertEmail');

function insertEmail(){
  echo "<script> alert('functions fil'); </script>"
  die();
}

?>
7
  • 1
    OT: Why are you trying to use ajax instead of the much better REST endpoints?
    – kero
    Jan 3, 2018 at 15:27
  • @kero I don't even know what REST endpoints is :) I'm in a little bit of time pressure so if it's something that's hard to implement into wordpress/learn I'm afraid I don't have the time to learn it.
    – Svante
    Jan 3, 2018 at 15:40
  • I'm sorry I don't really have the time now to explain. From a first look: <script> tags don't belong in the output, it expects pure JavaScript
    – kero
    Jan 3, 2018 at 16:11
  • Have you set ajaxurl? It is only set by default on admin screens, not the front end.
    – Milo
    Jan 3, 2018 at 16:16
  • 1
    For both actions, change add_action('wp_ajax_my_action', 'insertEmail'); to add_action('wp_ajax_my_action', 'my_action');. That is what codex specifies should be done. Which means changing the handler function name to my_action from insertEmail. See: codex.wordpress.org/AJAX_in_Plugins
    – Tony M
    Jan 5, 2018 at 18:02

1 Answer 1

2

Here's a base snippet I use for AJAX submits in Wordpress, it might help you out:

<?php
if (isset($_POST['my_theme_ajax_submit']))
    if ( wp_verify_nonce( $_POST['nonce'], 'my_theme_ajax_submit' ) )
        my_theme_ajax_submit(); 

function my_theme_ajax_submit() {
    // do something
    // some php code that fires from AJAX click of #fire
    wp_mail( '[email protected]', 'my_theme_ajax_submit() fired', time());
    wp_die();
}
?>

<button id='fire'>Fire Something</button>

<script>
    jQuery('#fire').click(function(){
        jQuery.ajax({
            type: 'post',
            data: { 
                "my_theme_ajax_submit": "now",
                "nonce" : "<?php echo wp_create_nonce( 'my_theme_ajax_submit' ); ?>"
            },
            success: function(response) { 
                jQuery('#fire').text("Somthing Done!");
            },
            error: function(response) { 
                jQuery('#fire').text("...error!");
            },
        });
    });
</script>

This can be built better - housing the scripts in wp_enque_script(), having the my_theme_ajax_submit() condition check / firing at an early hook like init (instead of within a template), or using the proper wp_ajax_(action) hooks (never seem to work for me) - but it should give an idea.

1
  • My page doesn't load for some reason if i write my php functions in the template file :/
    – Svante
    Jan 4, 2018 at 8:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.