AJAX:将数据从网页发送到PHP API

时间:2017-04-25 13:30:41

标签: javascript php jquery html ajax

我正在尝试从网页向服务器API发送数据,但它一直在下降 '没联系!'正如您将在代码中看到的那样。 注意:服务器,数据库和API正在运行,因为我也在手机应用程序上使用它,就像我在这里尝试做的那样,它将事件发布到数据库。 这是网页代码:

        function onAddEvent(){
        var title = document.getElementById("title").value;
        var desc = document.getElementById("desc").value;
        var date = document.getElementById("date").value;
        var userid = localStorage.getItem("userid");
        $.ajax({
            url: API_URL,
            type: 'POST',
            data: {eventname: title, eventdate: date, eventdesc: desc, user_id: userid},
            async: true, // set the property here
            success: function(data) {
                if(data.result == "success"){
                    alert("Add Event Successfully!");
                }
                else{
                    alert("Can't add event");
                }
            },
            error: function(xhr, error) {
                //It is falling here
                alert('No Connection!');
            }
        });
    }

以下是它将连接到的PHP API:

    function addevent()
{
    $new_member_insert_data = array(
        'eventname' => $this->input->post('eventname'),
        'eventdate' => $this->input->post('eventdate'),
        'eventdesc' => $this->input->post('eventdesc'),
        'user_id' => $this->input->post('user_id')
    );
    $insert = $this->db->insert('event', $new_member_insert_data);
    return $insert;
}

1 个答案:

答案 0 :(得分:0)

从函数中删除代码或尝试调用API中的函数。

//Call the function from your API
addevent();

function addevent()
{
   $new_member_insert_data = array(
     'eventname' => $this->input->post('eventname'),
     'eventdate' => $this->input->post('eventdate'),
     'eventdesc' => $this->input->post('eventdesc'),
     'user_id' => $this->input->post('user_id')
   );
   $insert = $this->db->insert('event', $new_member_insert_data);
   return $insert;
}