如何使用ajax调用将post数据传递给php代码

时间:2017-03-25 10:19:09

标签: php jquery ajax

我已将html写为

        <input type="button" onclick="saveAndSend()">

和用于发送请求的ajax代码

              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");
                        }
                    });
               }                          

和用于保存数据的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代码,以便不刷新页面并将数据保存在mongo db数据库中。上面的代码不起作用。请帮忙!!!

1 个答案:

答案 0 :(得分:0)

尝试此代码,它必须帮助您。

<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();
    }
}