2

I am integrating AJAX into a WordPress plugin with the following code:

PHP:

add_action( 'wp_ajax_nopriv_myajax-submit', 'myajax_submit' );
add_action( 'wp_ajax_myajax-submit', 'myajax_submit' );

function myajax_submit() {
    $amount = $_POST['amount'];
    $months = $_POST['months'];

    echo('<b>£'.$amount.' over '.$months.' months</b>');

    wp_die();
}

JS:

jQuery("button.compareLoans").click(function() { 
       jQuery.post(
        MyAjax.ajaxurl,
        {

            action : "myajax-submit",

            postID : MyAjax.postID,
            data: "amount="+$( "input#loan-amount" ).val()+"&months="+$( "#slider" ).slider( "value" )
        },
        function( response ) {
            $("#content_update").html(response);
        }
);
 });

The issue I have is that the 'amount' and 'months' variable is not passing through, these come through as blank and the return is simply '£ over months' so missing the variables completely.

Really not sure what the issue is here, any input would be greatly appreciated.

2 Answers 2

1

You aren't sending the data properly. If you checked your $_POST you will have a value for $_POST['data']

jQuery("button.compareLoans").click(function() { 
       jQuery.post(
        MyAjax.ajaxurl,
        {
            action : "myajax-submit",
            postID : MyAjax.postID,
            amount : $( "input#loan-amount" ).val(),
            months : $( '#slider' ).slider( "value" ),
        },
        function( response ) {
            $("#content_update").html(response);
        }
    );
});

Additionally you should be using nonces with check_ajax_referer for security.

Don't forget to validate and sanitize your variables server side too.

Sign up to request clarification or add additional context in comments.

1 Comment

@JamesLeist Glad to help. Please mark the answer as correct. Thanks.
0

In case you may want to stick with using the property 'data', you can try:

function myajax_submit() {
    $amount = explode('=', explode('&', $_POST['data'])[0])[1];
    $months = explode('=', explode('&', $_POST['data'])[1])[1];

    echo('<b>£'.$amount.' over '.$months.' months</b>');

    wp_die();
}

It just simply parses the string value of data, which would allow you to get the values of amount and months, through an array.

Comments

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.