如何通过ajax函数将数据发送到php文件?

时间:2017-04-06 10:35:22

标签: javascript php jquery html ajax

我想通过ajax函数调用一个addPost.php文件,并将结果作为提交的帖子返回。

为此我调用userAction函数onClick一个按钮,但现在我没有通过post获取数据,当我尝试访问addPost.php文件中的post数组数据时,它将错误发送为未定义的索引类别。

任何人都可以帮助解决出错的问题吗?

  <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Post</title>

</head>
<body>
<form class="postForm" id="postForm" method="post" action="addPost.html">


    <fieldset>
        <legend>Please add the details below </legend>
        <p>
            <label for="title">Title (required, at least 2 characters)</label>
            <input id="title" name="title" minlength="2" type="text" required>
        </p>

        <p>
            <label for="url">URL (required)</label>
            <input id="url" type="url" name="url">
        </p>

        <p>
            <label for="desc">Description (required, at least 2 characters)</label>
            <input id="desc" name="desc" minlength="2" type="text" required>
        </p>

        <p>
            <label for="keywords">Keywords (eg:#facebook)(required, at least 2 characters)</label>
            <input id="keywords" name="keywords" minlength="2" type="text" required>
        </p>

        <p>
            Select Url Type :
            <select name="urlType" id="urlType">
                <option value="">Select Url Type...</option>
                <option value="0">Server Image</option>
                <option value="1">Server Video</option>
                <option value="2">YouTube Video</option>
                <option value="3">Vimeo Video</option>
                <option value="4">Facebook Image</option>
                <option value="5">Facebook Video</option>
                <option value="6">Instagram Image</option>
                <option value="7">Instagram Video</option>
                <option value="-1">Other</option>
            </select>
        </p>
        <p>
            Select Category :
            <select name="category" id="category">



            </select>
        </p>

        <p>
            <input type="button" name="Submit" id="Submit" value="Submit" onclick="userAction('add')">
        </p>
    </fieldset>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>

        getCategories();

        function getCategories() {

            $.ajax({
                type: "POST",
                url: 'getCategories.php',
                dataType: 'text',
                async: false,
                cache: false,
                success: function (result) {

                    $('#category').html(result);
                }
            });
        }

        function userAction(type,id){
            id = (typeof id == "undefined")?'':id;
            var statusArr = {add:"added",edit:"updated",delete:"deleted"};
            var userData = '';
            if (type == 'add') {
                userData = $("#postForm").find('.form').serialize() + '&action_type=' + type + '&id=' + id;
            }
            $.ajax({
                type: 'POST',
                url: 'addPost.php',
                data: userData,
                success:function(report){

                    alert(report)
                }
            });
        }
    </script>
</form>
</body>
</html>

addPost.php

include 'Database.php';
ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);

if(isset($_POST['action_type']) && !empty($_POST['action_type'])) {

    if($_POST['action_type'] == 'add') {

      /*  $database = new Database(Constants::DBHOST, Constants::DBUSER, Constants::DBPASS, Constants::DBNAME);
        $dbConnection = $database->getDB();
        $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $dbConnection->prepare("insert into keywords(keyword) 
                                    values(?)");
        $stmt->execute(array($_POST['keywords']));


        //insert data into posts table
        $stmt = $dbConnection->prepare("insert into posts(category_id,title,url,url_type,description,keywords) 
                                    values(?,?,?,?,?,?)");
        $stmt->execute(array($_POST['category'], $_POST['title'], $_POST['url'], $_POST['urlType'], $_POST['desc'], $_POST['keywords']));

        $count = $stmt->rowCount();

        if ($count > 0) {

            //if inserted
            $response = array("status" => -1, "message" => "Post Submitted");
            return $response;
        } else {
            //if not inserted
            $response = array("status" => -1, "message" => "Could not submit post.");
            return $response;
        }*/

      echo $_POST['category'], $_POST['title'], $_POST['url'], $_POST['urlType'], $_POST['desc'], $_POST['keywords'];


    }

}

编辑:

  <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Post</title>

</head>
<body>
<form class="postForm" id="postForm" method="post" action="addPost.php">


    <fieldset>
        <legend>Please add the details below </legend>
        <p>
            <label for="title">Title (required, at least 2 characters)</label>
            <input id="title" name="title" minlength="2" type="text" required>
        </p>

        <p>
            <label for="url">URL (required)</label>
            <input id="url" type="url" name="url" required>
        </p>

        <p>
            <label for="desc">Description (required, at least 2 characters)</label>
            <input id="desc" name="desc" minlength="2" type="text" required>
        </p>

        <p>
            <label for="keywords">Keywords (eg:#facebook)(required, at least 2 characters)</label>
            <input id="keywords" name="keywords" minlength="2" type="text" required>
        </p>

        <p>
            Select Url Type :
            <select name="urlType" id="urlType">
                <option value="">Select Url Type...</option>
                <option value="0">Server Image</option>
                <option value="1">Server Video</option>
                <option value="2">YouTube Video</option>
                <option value="3">Vimeo Video</option>
                <option value="4">Facebook Image</option>
                <option value="5">Facebook Video</option>
                <option value="6">Instagram Image</option>
                <option value="7">Instagram Video</option>
                <option value="-1">Other</option>
            </select>
        </p>
        <p>
            Select Category :
            <select name="category" id="category">

            </select>
        </p>


        <p>
            <input type="hidden" name="action_type" id="action_type_id"/>
            <input type="hidden" name="id" id="p_id"/>

           <input type="button" name="Submit" id="Submit" value="Submit" onclick="userAction('add')">
        </p>


        <p id="report"></p>

    </fieldset>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>

        getCategories();

        $("#postForm").validate();

        function getCategories() {

            $.ajax({
                type: "POST",
                url: 'getCategories.php',
                dataType: 'text',
                async: false,
                cache: false,
                success: function (result) {

                    $('#category').html(result);
                }
            });
        }
        function userAction(type,id){

            var statusArr = {add:"added",edit:"updated",delete:"deleted"};

            if (type == 'add') {
                $('#action_type_id').val(type);
                $('#p_id').val(id);
            }
            $.ajax({
                type: 'POST',
                url: 'addPost.php',
                data: $('#postForm').serialize(),
                success:function(report){
                    $('#report').html(result);
                }
            });
        }

    </script>
</form>
</body>
</html>

现在通过这个编辑代码,数据在数据库中插入,但我想在add.html中显示para的结果,所以我在成功方法中给出了para的id,但这不起作用,表单验证也是不工作。

请帮忙。谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用隐藏值在服务器中发送数据。在表单中放置这两个字段。

google.maps.OverlayView

您的<input type="hidden" name="action_type" id="action_type_id"/> <input type="hidden" name="id" id="p_id"/> 方法就像:

ajax

说明:在提交表单之前,您将function userAction(type,id){ var statusArr = {add:"added",edit:"updated",delete:"deleted"}; if (type == 'add') { $('#action_type_id').val(type); $('#p_id').val(id); } $.ajax({ type: 'POST', url: 'addPost.php', data: $('#postForm').serialize(), success:function(report){ alert(report); } }); } type值设置为隐藏字段并将整个表单发送到server.now您可以获取所有帖子id$_POST['action_type']的数据。

答案 1 :(得分:0)

echo $_POST['category'], $_POST['title'], $_POST['url'], $_POST['urlType'], $_POST['desc'], $_POST['keywords']

在这个声明中,你试图访问“类别”,“标题”等。但是你没有在ajax(userdata)中传递那些字段,所以你得到了“未定义的索引类别” - 这个错误