1

I want to post my form by ajax to php then get values from inputs ( I did it and it works fine ) but I also want to post a JS variable i one ajax.

There is my FORM section.

<form action="new_alias.php" method="post" id="theForm">
                <div class="form-group">
                    <label for="exampleInputEmail1">Wpisz nazwę aliasu</label>
                    <input type="text" name="alias" id="alias" class="form-control" id="exampleInputEmail1"
                        aria-describedby="emailHelp" placeholder="Nazwa aliasu">
                </div>
                <div class="form-group">
                    <label class="col-form-label">Wybierz domenę</label>
                    <?php
                                    if ($resultt->num_rows > 0) {
                                    echo '<select name="name" class="custom-select">';
                                        // output data of each row
                                        while ($row = $resultt->fetch_assoc()) {
                                        echo "<option value='$row[name],$row[id]'>$row[name]</option>";
                                        }

                                        echo '</select>';
                                    } else {
                                    echo "0 results";
                                    }
                                    ?>
                </div>

                <div class="form-group">
                    <label for="exampleInputEmail1">Wpisz adresy docelowe</label>
                    <input type="text" name="source" id="source" placeholder="Adresy mailowe" autocomplete="nope"
                        autocomplete="off" class="typeahead tm-input form-control tm-input-info" />
                </div>

                <button type="submit" name="add" id="add" class="btn btn-primary mt-4 pr-4 pl-4">Utwórz</button>
            </form>

and there is my script

<script>
        $(document).ready(function () {
            var tagApi = $(".tm-input").tagsManager({
                hiddenTagListName: 'hiddenTagListA'
            });
            var x = '';
            var test = '';


            jQuery(".typeahead").typeahead({
                name: 'source',
                displayKey: 'source',
                source: function (query, process) {
                    return $.get('ajaxpro.php', {
                        query: query
                    }, function (data) {
                        data = $.parseJSON(data);
                        console.log(data);
                        return process(data);
                    });
                },
                afterSelect: function (item) {
                    tagApi.tagsManager("pushTag", item);
                    x = document.getElementsByName("hiddenTagListA");
                    test = x[0].value;
                    console.log('to jest z afterSlect: ', test);
                }

            });
            $(".btn").click(function (e) {
                e.preventDefault();
                $.ajax({
                    type: "post",
                    url: 'new_alias.php',
                    data: {
                        $("#theForm").serialize()
                    },
                    success: function () {
                        alert("Form Submitted: ");
                    },
                });
            });
        }); 
    </script>

I am using tagsManager which created hidden input with ID hiddenTagListA I am trying to put all values from hiddenTagListA to var testand it works. But now I want to post this variable also to my php because I want to put it into my DB. Taking all values from form woks but I must also post test variable.

In my console I am getting value from test like: something, something2, something3... ( tags separated by comma) It can be just string

Defus
  • 789
  • 2
  • 12
  • 22
  • You can put hidden input field "hiddenTagListA" in the html form, then $("#theForm").serialize() will make sure that value of "hiddenTagListA" will also be posted along with other data. – Prasad Wargad Nov 29 '18 at 08:34

2 Answers2

1

if you got the value in test, just put it in ajax

$(".btn").click(function (e) {
    e.preventDefault();
    $.ajax({
        type: "post",
        url: 'new_alias.php',
        data: {
            form: $("#theForm").serialize(),
            hiddenTagListA: test
        },
        success: function () {
            alert("Form Submitted: ");
        },
    });
});
  • but now how can I get data from my from? Before I did it like: $alias = mysqli_real_escape_string($conn, $_REQUEST['alias']); – Defus Nov 29 '18 at 08:49
  • using $_REQUEST['data']['hiddenTagListA'] – Vernon Jian Hao Nov 29 '18 at 08:54
  • for every input field should be now ['data']['AnyNameFromInput'] ?? – Defus Nov 29 '18 at 09:01
  • by right it should be getting from ['data'] since it was placed inside data in ajax. But i forgot to stringify 1st before passing to backend `data: JSON.stringify({ form: $("#theForm").serialize(), hiddenTagListA: test })` then backend use `json_decode( $_REQUEST['data'])` to get the data – Vernon Jian Hao Nov 29 '18 at 09:21
  • like this? $alias = json_decode($_REQUEST['data']['alias']); – Defus Nov 29 '18 at 09:26
  • something is wrong because I get good value from test but from my form I get nothing – Defus Nov 29 '18 at 09:36
1

If you use .serialize then you need to parse the string first to get posted data using AJAX. PHP function parse_str reads string & convert that into array.

Refer: http://php.net/manual/en/function.parse-str.php

You can use .serializeArray function instead of .serialize which make sure to give data in array format, which is easily retrievable in PHP using $_POST variable.

JS CODE

$(".btn").click(function (e) {
    e.preventDefault();
    var inputData = $("#theForm").serializeArray(); // .serializeArray gives data in array format instead of string format.
    // you can insert new variables like below
    inputData.push({"name":"hiddenTagListA", "value": document.getElementsByName("hiddenTagListA")[0].value});
    $.ajax({
        type: "post",
        url: 'new_alias.php',
        data: inputData,
        success: function () {
            alert("Form Submitted: ");
        },
    });
});
Prasad Wargad
  • 737
  • 2
  • 7
  • 11
  • Now I have in my DB: [object NodeList] when I did $data = $_POST['test'] – Defus Nov 29 '18 at 08:52
  • You can do print_r($_POST) which will give a better idea, like what are all variables are getting posted to PHP. From their you can figure out, which variable you need to assign what value. – Prasad Wargad Nov 29 '18 at 09:48
  • I can't see print_R when click submit button – Defus Nov 29 '18 at 09:52
  • I did alert(); and it's empty – Defus Nov 29 '18 at 09:53
  • You need to use "Developer Tools" from browser, where "Network" tab is present which shows AJAX request being sent. – Prasad Wargad Nov 29 '18 at 09:54
  • Cool i see now: The problem is here: hiddenTagListA: test@gmail.com hiddenTagListA: [object NodeList] How Can I take only test@gmail.com instead of object NodeList – Defus Nov 29 '18 at 10:00
  • ok. In given JS code hiddenTagListA is mapped with document.getElementsByName("hiddenTagListA") because of which it might be giving you [object NodeList]. Just a correction needed, which I did in my answer. OLD: document.getElementsByName("hiddenTagListA"); NEW: document.getElementsByName("hiddenTagListA").value; – Prasad Wargad Nov 29 '18 at 10:03
  • great it works. How can I clear all form and hiddenTagListA after submit? – Defus Nov 29 '18 at 10:13
  • 1
    Refer an existing answer link: https://stackoverflow.com/questions/16452699/how-to-reset-a-form-using-jquery-with-reset-method#24505433 For this you need to have a "Reset" button in your HTML form. Then after submit you can trigger click event of that "Reset" button to clear up the form details. – Prasad Wargad Nov 29 '18 at 10:17