AppleTattooGuy AppleTattooGuy - 2 months ago 11
Ajax Question

Wordpress AJAX not passing POST data

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.

Answer

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.

Comments