如何使用ajax调用将post数据传递给php代码
我已经将html编写为如何使用ajax调用将post数据传递给php代码,php,jquery,ajax,Php,Jquery,Ajax,我已经将html编写为 <input type="button" onclick="saveAndSend()"> 和用于保存数据的php代码 public function saveAndSend() { // Send Logic // Save Logic $new_item = $this->apicaller->sendRequest(array(
<input type="button" onclick="saveAndSend()">
和用于保存数据的php代码
public function saveAndSend()
{
// Send Logic
// Save Logic
$new_item = $this->apicaller->sendRequest(array(
'controller' => 'Broadcast',
'action' => 'save',
'studentList' => $_POST['studentList'],
'employeeList' => $_POST['employeeList'],
'mailTitle' => $_POST['mailTitle'],
'broadcastMessage' => $_POST['broadcastMessage'],
'emailSent' => $_POST['emailSent']
));
echo $new_item;
}
我试图使用ajax调用将数据传递给php代码,这样页面就不会刷新,数据保存在MongoDB数据库中。上述代码不起作用。请帮忙 试试这段代码,它一定对你有帮助
<input type="button" onclick="saveAndSend()">
<script>
// JS function
function saveAndSend()
{
var studentList = "1,2,3";
var employeeList = "";
var mailTitle = "Hello";
var broadcastMessage = "How are you";
var emailSent = "0";
$.ajax({
url: 'index.php?action=saveAndSend',
type: 'POST',
data: {'studentList': studentList, 'employeeList': employeeList, 'mailTitle': mailTitle, 'broadcastMessage': broadcastMessage, 'emailSent': emailSent},
success: function () {
alert("hello");
},
error: function () {
alert('sorry');
}
});
}
</script>
<?php
if($_GET['action'] = 'saveAndSend'){
saveAndSend();
}
// PHP Function
function saveAndSend() {
if (isset($_POST)) {
echo '<pre>';
print_r($_POST);
echo '</pre>';
die();
}
}
//JS函数
函数saveAndSend()
{
var studentList=“1,2,3”;
var employeeList=“”;
var mailttitle=“你好”;
var broadcastMessage=“你好”;
var emailSent=“0”;
$.ajax({
url:'index.php?action=saveAndSend',
键入:“POST”,
数据:{'studentList':studentList,'employeeList':employeeList,'mailTitle':mailTitle,'broadcastMessage':broadcastMessage,'emailSent':emailSent},
成功:函数(){
警惕(“你好”);
},
错误:函数(){
警惕(“对不起”);
}
});
}
控制台中有错误吗?控制台中没有错误,但我认为它不会传递数据或运行php代码。请尝试设置contentType参数contentType不是必需的var\u dump($\u POST)代码>来检查@Nida您正在ajax调用中添加TYPE=POST,并发送index.php?action=saveAndsend,这是作为GET类型的查询字符串url。
<input type="button" onclick="saveAndSend()">
<script>
// JS function
function saveAndSend()
{
var studentList = "1,2,3";
var employeeList = "";
var mailTitle = "Hello";
var broadcastMessage = "How are you";
var emailSent = "0";
$.ajax({
url: 'index.php?action=saveAndSend',
type: 'POST',
data: {'studentList': studentList, 'employeeList': employeeList, 'mailTitle': mailTitle, 'broadcastMessage': broadcastMessage, 'emailSent': emailSent},
success: function () {
alert("hello");
},
error: function () {
alert('sorry');
}
});
}
</script>
<?php
if($_GET['action'] = 'saveAndSend'){
saveAndSend();
}
// PHP Function
function saveAndSend() {
if (isset($_POST)) {
echo '<pre>';
print_r($_POST);
echo '</pre>';
die();
}
}