我有一个表单,它有2个提交按钮。
<form name="posting" id="posting" method="post" action="posting_bk.php" role="form">
<input type="text" name="title" id="title" class="form-control" required="required">
....some form fields...
<input class="btn btn-home" type="submit" name="publish" id="publish" alt="Publish" value="Preview and Post" />
<input class="btn btn-home" type="submit" name="save" id="save" onclick="return confirm('Are you sure you want to Submit.')" alt="Save" value="Save as Draft" /></center>
</form>
我正在使用ajax发送/接收数据。
$('#posting input[type="submit"]').on("click", function(e) {
e.preventDefault;
var btn = $('#publish');
var el = $(this).attr('id');
$.ajax({
type: 'post',
url: $('form#posting').attr('action'),
cache: false,
dataType: 'json',
data: {
data: $('form#posting').serialize(),
action: el
},
beforeSend: function() {
$("#validation-errors").hide().empty();
},
success: function(data) {
if (data.success == false) {
var arr = data.errors;
$.each(arr, function(index, value) {
if (value.length != 0) {
$("#validation-errors").append('<div class="alert alert-danger"><strong>' + value + '</strong><div>');
}
});
$("#validation-errors").show();
btn.button('reset');
} else {
$("#success").html('<div class="alert alert-success">Basic details saved successfully. <br> If you want to edit then please goto <a href="edit.php">Edit</a>. <div>');
$('#title').val('');
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
btn.button('reset');
}
});
return false;
});
这是我的php文件。 posting_bk.php
if ($_POST['action'] == 'publish') {
if($title == 'test'){
array_push($res['errors'], 'data received by php.');
}else{
array_push($res['errors'], 'No data received by php.');
}
$res['success'] = true;
echo json_encode($res);
}
elseif ($_POST['action'] == 'save') {
array_push($res['errors'], 'Save button clicked.');
$res['success'] = true;
echo json_encode($res);
}
如果我点击发布按钮,我会一直
没有数据通过php
获取
当我签入firebug时,它会在帖子下显示数据。 喜欢这个
行动发布
data title = test&amp;
我不确定我在这里做错了什么。请指教。
答案 0 :(得分:1)
更改AJAX调用以使用:
data: $('form#posting').serialize() + '&action=' + el,\
然后使用
访问参数$title = $_POST['title'];
您正在这样做,表单数据在POST
数据中嵌套了一个级别,因此您必须这样做:
$data = parse_str($_POST['data']);
$title = $data['title'];