1

Im trying to take form data and send it to WordPress with an ajax call. The call goes through, but the variable does not reach the PHP script. Why is that?

I have checked, that formData holds a variable.

This is my js:

$( document ).ready( function() {
    $( 'form' ).submit( function( event ) {
        var formData = {'title': $('input[name=title]').val() };
        $.ajax( {
            url: '<?php echo  admin_url( 'admin-ajax.php' ); ?>',
            data: {
                action : 'my_ajax_action',
                data : formData,
            },
            success:function( data ) {
                console.log( data );
            },
            error: function( errorThrown ) {
                console.log( errorThrown );
            },
        } );
    event.preventDefault();
    } );
});

This is my PHP:

add_action( 'wp_ajax_my_ajax_action', 'my_ajax_action_callback' );

function my_ajax_action_callback() {
    $title =isset( $_POST['data'] ) ? $_POST['data'] : 'N/A';
    echo $title;
    die();
}
1
  • you will have to use wp_create_nonce to get your js data back to php. When the nonce is created inside php you will have to set it inside your data:{} in your JS. Sorry for the short answer but I'm on the move. Anyway look up wp_create_nonce its pretty straight forward Commented Jan 16, 2019 at 22:51

1 Answer 1

2

The default jQuery ajax method is GET, so maybe that's your issue? Try adding method: 'POST' to your options:

$.ajax({
  method: 'POST',
  ... etc
Sign up to request clarification or add additional context in comments.

2 Comments

adding method: 'POST',
Adding method: 'POST' doesn't change anything. I still get nothing back.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.