2

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.

5
  • Your ajax method type is post, so probably &action_type value and other params can not be sent to controller. Commented Apr 6, 2017 at 10:39
  • then what should be the type? and how to access that data? @AtaurRahmanMunna
    – Sid
    Commented Apr 6, 2017 at 10:40
  • I didn't see any <?php?> tag in your addPost.php file also. Commented Apr 6, 2017 at 11:12
  • Please put end form tag </form> just before </fieldset>. Commented Apr 6, 2017 at 11:30
  • form is not getting submit if put </form> before </fieldset>
    – Sid
    Commented Apr 6, 2017 at 11:47

2 Answers 2

1

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'].

6
  • ok form is getting submit if script is added after form close tag. but I am getting the categories through ajax function, the select tag shows blank if script is added after form closed.
    – Sid
    Commented Apr 6, 2017 at 12:01
  • see the code. remember for select DOM, you must add an empty option,if you don't have any option.I tested the code on my side and this is working. see demo code in pastebin.com/9bvw9u2L Commented Apr 6, 2017 at 12:04
  • why did you comment out getCategories function?
    – Sid
    Commented Apr 6, 2017 at 12:13
  • if script is added above form then I cant see the categories in the select tag also validation is not working
    – Sid
    Commented Apr 6, 2017 at 12:16
  • I didn't have any information what inside getCategories.php. so getting 404 error on load. so i commented the code. you can add them too. Commented Apr 6, 2017 at 12:16
0
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.