I have a fairly simple AJAX request for my WordPress site. My PHP function is a switch statement and all the other switch statements work except for the recent one I added (change_due_date).
I commented out the majority of the code in my new 'case' to better try to find the problem.
AJAX (at bottom of page, under my other AJAX request (which works)):
function my_ajax() {
var newDate = <?php echo $new_date; ?>;
var data_string = 'action=do_ajax&fn=change_due_date&newDate=' + newDate;
jQuery.ajax({
type: "POST",
url: '/wp-admin/admin-ajax.php',
data: data_string,
dataType: 'JSON',
success: function(data){
// alert(data);
console.log("success!");
},
error: function(errorThrown){
console.log("error!");
}
});
} // end of my_ajax function
jQuery('a.test').click(function(){
my_ajax();
});
</script>
I tried, at first, just sending 'newDate' as my 'data' value - and that did work (as in AJAX returned 'success!'). In that case my PHP function still didn't run, since it wasn't being called. I suspect something is wrong with my formatting on the AJAX side of things...
Now, when I send 'data_string' as my data I get an AJAX error...
PHP Function:
switch($_POST['fn']){ ...
/* AUTOMATE DUE DATE CREATION - made by Alex */
case 'change_due_date' :
/*$field_key = "field_515b2428887d7"; // Key ID for field
$new_date = $_POST['newDate']; // new date
$new_due_date = DateTime::createFromFormat('Ymd', $new_date);
$new_due_date->format('Ymd'); // formatting */
echo ('<h1>functioning</h1>'); // testing purposes
/*$parent_field = get_field($field_key); // Select parent field
foreach($parent_field as $sub_row) :
// Change value of sub-fields
$sub_row['date_due'] = $new_due_date;
$new_values[] = $sub_row; // Load new values into array
endforeach;
update_field( $field_key, $new_values ); // Update ACF*/
$output = "Successfully updated due dates."; // testing
break;
... }
I've been working on this code for a couple days - I admit I am not the best at AJAX... but I can't seem to find what's wrong? I have looked at the WP Codex for guidance on how to structure my AJAX.