Reputation: 85
I have a form with action=""
and many AJAX codes to validate or chain-select the form elements as below.
** My current code (Simplified) **
<?php
if( isset( $_POST['create_transaction'] ) ) {
// do something
}
?>
<div>
<!-- period information will be filled up by ajax -->
<input type="text" name="period" class="form-control" id="period" readonly />
</div>
<form id="form" method="post" action="">
<input name="r_date" type="date" value="<?php echo isset( $_POST['r_date'] ) ? $_POST['r_date'] : date( "Y-m-d" ); ?>" class="transaction_date" />
<input type="submit" name="create_transaction" value="Create" />
</form>
<script>
jQuery(document).ready(function($) {
// Do this and that...
/* Get period information if date is already filled up on page load */
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
var $transaction_date = $(".transaction_date").val();
if( $transaction_date ) {
// call ajax for period <-- THIS IS THE PROBLEM CHILD.
jQuery.ajax({
url: ajaxurl,
data: 'action=get_period_by_date&transaction_date='+$transaction_date,
type: 'GET',
success:function(results) {
jQuery("#period").val(results);
}
});
}
});
</script>
Here I am retrieving a period name using the input date. For example, if the date is 2014-01-01, then the #period
div will be filled up with PERIOD-01. If the date is 2014-08-25, then the #period
div will be filled up with PERIOD-08. This date field is auto-filled up with today's date when the page loads.
The problem is that if I insert the AJAX code to retrieve period information using the date input, submitting the form (clicking the 'create' button) leads to 404 error. If I remove the code, the form works well.
There doesn't seem to be a problem in the get_period_by_date
function since it correctly retrieves and shows period name.
What would be the cause of my problem?
Upvotes: 0
Views: 1747
Reputation: 1107
404 error means that your AJAX request leads to an unexisting path. Thats the first issue you should solve :).
Use your console to debug this one:
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
You are using this var in a jQuery method. I think it will be literally interpreted. I don't think it's possible to use php syntax here.
I'm not sure if it's a good practice, but for a quick fix you could make a hidden field in your html page with that tag. And then you could easily get the value from it with the use of jQuery or javascript
Upvotes: 1