Kbcoder Kbcoder - 1 month ago 8
jQuery Question

Need help converting the ajax and php for wordpress

From guides I have gotten this far:

add_action('wp_enqueue_scripts', 'do_enqueue_scripts');

function do_enqueue_scripts()
{
wp_enqueue_script('Java', plugins_url( '/js/form.js', __FILE__ ), array('jquery'), '1.0', true);

wp_localize_script( 'Java', 'start', array(
'code' => admin_url( 'admin-ajax.php' )
));
}

add_action('wp_ajax_nopriv_func', 'func');
add_action('wp_ajax_func', 'func');

function func()
{
$From = $_POST['dateTo'];
$To = $_POST['dateFrom'];
$Name = $_POST['Name'];
echo $From . " - " . $To . " - " . $Name;
die();
}


$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: start.code,
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data) {
alert(data);
}
});
}));


My problem comes in with the AJAX call. I am still getting used to this action system WordPress is using and I am not sure what I need to change my data to. I have a generic form with 2 dates and a name; nothing crazy. However the returned data to my AJAX call is zero.

I believe my issue now is how I m either returning data to my ajax or with the data type I am send to my PHP function
func()
.

No errors in chrome or mozilla consoles.

Answer

Add a hidden input field to your form with the name of the action so wp can execute the right function

<input type="hidden" name="action" value="func">

change your ajax to:

$("#form").on('submit',(function(e) {
    e.preventDefault();
    $.ajax({
        url: start.code, 
        type: "POST",       
        data: $(this).serialize(),   
        cache: false,           
        success: function(data) {
            alert(data);
        }
    });
}));