如何以文本形式显示para或div中的ajax响应?

时间:2017-04-07 05:29:29

标签: javascript php jquery html ajax

我创建了一个带有ajax函数的页面,用于将数据插入到数据库中,所以点击提交数据就会在数据库中插入,但我想显示一条消息,说明数据是否已插入到已创建的div并显示结果在那,但我看不到文字。

    <!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>

            <label for="urlType">Select Url Type :(required)</label>
            <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>


            <label for="postType"> Select Post Type :(required)</label>
            <select name="postType" id="postType">
                <option value="">Select Post Type...</option>
                <option value="0">Normal</option>
                <option value="1">Featured</option>
                <option value="2">Sponsored</option>

            </select>
        </p>
        <p>


            <label for="category"> Select Category :(required)</label>
            <select name="category" id="category">
                <option value="0">Select Category...</option>

            </select>
        </p>



        <p>
            <input type="hidden" name="action_type" id="action_type_id"/>
            <input type="hidden" name="id" id="p_id"/>
<!--            <a href="javascript:void(0);" class="btn btn-warning" onclick="$('#postForm').slideUp();">Cancel</a>
            <a href="javascript:void(0);" class="btn btn-success" onclick="userAction('add')">Add User</a>-->
           <input type="button" name="Submit" id="Submit" value="Submit" onclick="userAction('add')">


        </p>

    </fieldset>

    <div class="result"></div>

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

        $(document).ready(function(){
            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){

            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){

                    $(".result").html(data);

                    location.reload();
                }
            });
        }

    </script>
</form>

</body>
</html>

addPost.php

   <?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,post_type) 
                                    values(?,?,?,?,?,?,?)");
        $stmt->execute(array($_POST['category'], $_POST['title'], $_POST['url'], $_POST['urlType'], $_POST['desc'], $_POST['keywords'],$_POST['postType']));

        $count = $stmt->rowCount();

        if ($count > 0) {

            //if inserted


       //   echo    '<p id="report">Post Submitted</p>';
            echo "Post submitted.";
        } else {
            //if not inserted


        //  echo  '<p id="report">Post Submitted</p>';
       echo "Could not submit post.";
        }

    }

}

?> 

请帮忙..谢谢。

2 个答案:

答案 0 :(得分:1)

以下是您的代码的更新部分。表格重置代码已添加。

$.ajax({
    type: 'POST',
    url: 'addPost.php',
    data: $('#postForm').serialize(),
    success:function(report){
         // replace data to report
         $(".result").html(report);

         //reset form
         $(':input','#form') 
            .not(':button, :submit, :reset, :hidden') 
            .val('') 
            .removeAttr('checked') 
            .removeAttr('selected'); 
    }
});

答案 1 :(得分:0)

请在服务器端和客户端之间制定合同

例如: 每当客户端向服务器发送请求时 服务器处理请求,为这些行构建响应 - 例如({result:“success”}或某些内容并将其发送回客户端 客户端将能够在$ .ajax的成功中访问它 客户现在将根据合同了解何时成功以及何时失败并执行下一步操作

希望这有帮助。