0

I have a simple ajax script to send a form in WordPress.

My PHP code to get the ajax URL is:

wp_localize_script( 'custom_child', 'jAjax', array('ajax_url'
=>admin_url('admin-ajax.php')));

Moreover I have in functions.php the following:

function enviar_pedido_clientes() {
    // do something with the data to send an email
    wp_mail( $to, $subject, $message, $headers );
    die();
}
add_action( 'admin_ajax_nopriv_pedido_clientes', 'enviar_pedido_clientes' );
add_action( 'admin_ajax_pedido_clientes', 'enviar_pedido_clientes' );

Finally, in my .js:

$('#enviar_fotos').on('click', function(event) {
            event.preventDefault();
            /* Act on the event */
            data = {
                'action': 'pedido_clientes',
                'nombreCliente': 'pedro', // that's how we get params from wp_localize_script() function
                'emailCliente' : 'hola@gmail.com'
            };
            $.ajax({
                url: jAjax.ajax_url,        // URL to "wp-admin/admin-ajax.php"
                data: data,
                method: "POST",             // use $_POST request to submit data
                // success:function( data ) {
                //  $( '#probando' ).html( data );
                // },
                error: function(){
                    console.log('Ha habido un error'); // error
                }
            });
        });

I went through many posts to try to find the error, but I cannot find it.

2

The hook prefix is wrong — it should be wp_ and not admin_:

add_action( 'admin_ajax_nopriv_pedido_clientes', 'enviar_pedido_clientes' );
add_action( 'admin_ajax_pedido_clientes', 'enviar_pedido_clientes' );

So the correct code is:

add_action( 'wp_ajax_nopriv_pedido_clientes', 'enviar_pedido_clientes' );
add_action( 'wp_ajax_pedido_clientes', 'enviar_pedido_clientes' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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