Sid
Sid

Reputation: 2862

How to send data through ajax function to php file?

I want to call one addPost.php file through ajax function, and return the result as post submitted or not.

For that I am calling userAction function onClick of a button but now I am not getting the data through post, when I tried to access the post array data in addPost.php file its sending the error as undefined index category.

Can anyone please help what is going wrong?

  <!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'];


    }

}

EDIT :

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

Now By this edit code the data is getting insert in the database but I want to show the result in para in add.html so I have given the id of para in success method but this is not working, also form validation is not working.

Please help. Thank you.

Upvotes: 2

Views: 116

Answers (2)

Riddhi Rathod
Riddhi Rathod

Reputation: 416

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

in this statement, you are trying to access "category", "title" etc. But you have not passed that fields in ajax(userdata), so you got "undefined index category" - this error

Upvotes: 0

Ataur Rahman Munna
Ataur Rahman Munna

Reputation: 3917

You can use hidden value to send data in server.In your form place this two fields.

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

And your ajax method will be like:

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

Explanation: Before submitting the form, you set type and id value to hidden field and send the entire form to server.now you can able to get all post data by $_POST['action_type'] and $_POST['id'].

Upvotes: 1

Related Questions