Reputation: 971
I'm working on a website with heavy Ajax, and I'm using codeigniter for building it.
I've got a form with post method, and this form is being posted using ajax request which call a function with if/else statement, like this:
if(isset($_POST['save']))
{
$data['phase'] = 'translating';
}
elseif(isset($_POST['submit']))
{
$data['phase'] = 'waiting_approve';
}
The if/else statement check which button is being clicked, and it works 100% after posting the data of the form in the usual way, but never works when posting it using ajax request.
My ajax request:
$('#workspace-content').delegate('form#article', 'submit', function(){
var that = $('form#article'),
url = that.attr('action'),
type = that.attr('method'),
data = {};
data = that.serialize();
$.ajax({
type: type,
url : url,
data : data,
dataType: 'json',
success: function(data){
$('#header-search-field').append(data.msg).delay(3000).fadeOut(500, function(){
var that = $(this);
that.html('').fadeIn();
});
}
});
return false;
});
Any suggestion or solution?!!
The HTML form:
<button id="save-article" type="submit" name="save" class="btn btn-info btn-xs pull-left">
<span class="glyphicon glyphicon-floppy-save"></span>
</button>
<input name="title" type="text" value="<?php echo $work->title;?>" class="form-control" id="title" placeholder="" />
<textarea row="10" name="article" class="form-control" id="article" placeholder=""><?php echo $work->article;?></textarea>
<button id="submit-article" type="submit" name="submit" class="btn btn-info btn-block">Send</button>
<input name="slug" type="hidden" value="<?php echo $work->slug;?>" />
Upvotes: 0
Views: 207
Reputation: 781058
When you submit a form normally, the button that you used to submit it will be included in the POST data. But when you submit with AJAX, and use that.serialize()
, the POST data just includes the input fields -- the submit button isn't included. You need to attach your submit code to the buttons, so you can add the appropriate values to the data.
$('#workspace-content').on('click', 'form#article .btn', function(){
var that = $(this).closest("form"),
url = that.attr('action'),
type = that.attr('method'),
data = that.serialize();
data += '&' + this.name + '=1';
$.ajax({
type: type,
url : url,
data : data,
dataType: 'json',
success: function(data){
$('#header-search-field').append(data.msg).delay(3000).fadeOut(500, function(){
var that = $(this);
that.html('').fadeIn();
});
}
});
return false;
});
Upvotes: 1