简体   繁体   中英

How to get the date value from html textarea via JS

So I have this function that creates a number of textareas depending on what month it is.

For example:

  • If it's 'February', then 28 'textareas' are created.
  • If it's 'March', then 31 'textareas' are created and so on.

When the user clicks on the 'textareas' and then the forms button, the value of the textareas inserts into the MySQL database.

My problem right now is that the value that goes into the database is not the value of the textareas, eg 2018-02-19 , it is always 2018-02-28 .

Functions:

function daysInMonth(month, year) {
    var days;
    switch (month) {
        case 1: // Feb, our problem child
            var leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
            days = leapYear ? 29 : 28;
            break;
        case 3:
        case 5:
        case 8:
        case 10:
            days = 30;
            break;
        default:
            days = 31;
    }
    return days;
}

var showDate = new Date();
var months = ["January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
];
var weeks = ["Sunday", "Monday", "Tuseday", "Wednesday", "Thursday", "Friday", "Saturday"];

function drawTable(forDate) {
    var daysInMonth = new Date(forDate.getFullYear(), forDate.getMonth() + 1, 0).getDate();
    var cellsToDraw = daysInMonth;
    var newdate = forDate.getFullYear() + "-" + ("0" + (forDate.getMonth() + 1)).slice(-2);
    var table = document.getElementById("table");
    table.innerHTML = "";
    for (var r = 0; r < (daysInMonth / 7); r++) {
        var newRow = document.createElement("tr");
        table.appendChild(newRow);
        for (var c = 0; c < 31 && cellsToDraw > 0; c++) {
            var day1 = ("0" + (c + 1)).slice(-2);
            var textarea = document.createElement("textarea");
            textarea.setAttribute("type", "button");
            textarea.setAttribute("name", "day");
            textarea.setAttribute("value", newdate + "-" + day1);
            textarea.setAttribute("placeholder", day1);
            newRow.appendChild(textarea);
            textarea.setAttribute("name", "day");
            textarea.setAttribute("day", newdate + "-" + day1)
            textarea.innerHTML = newdate + "-" + day1;
            cellsToDraw--;
        }
    }
}

window.onload = function() {
    document.getElementById("displayingMonth").innerHTML = months[showDate.getMonth()];
    drawTable(showDate);
};

html:

<form class="" action="insert.php" method="post">
    <table id="table">
        <input id="day"type="hidden" name="day" value="">
        <input id="btn"  type="submit" name="" value="Press">
</form>

php

$day = mysqli_real_escape_string($conn, $_request['day']);
for ($i = 1; $i < count($day); $i++) {
    $stmt = "INSERT INTO calendar (day) VALUES('$day[$i])')";
    if (empty($day)) {
        $_SESSION['error'] = "Error";

        header('Location: insert.php', true, 303);
        exit();
    } else {
        if (mysqli_query($conn, $stmt)) {
            header('Location: insert.php', true, 303);
            exit;
        } else {
            $error= "Error: " .mysqli_error($conn);
            echo "$error";

        }
    }
}

This is because the data sent to insert.php looks like this(check using network tab)

day=2018-02-01&day=2018-02-02&day=2018-02-03&day=2018-02-04&day=2018-02-05&day=2018-02-06&day=2018-02-07&day=2018-02-08&day=2018-02-09&day=2018-02-10&day=2018-02-11&day=2018-02-12&day=2018-02-13&day=2018-02-14&day=2018-02-15&day=2018-02-16&day=2018-02-17&day=2018-02-18&day=2018-02-19&day=2018-02-20&day=2018-02-21&day=2018-02-22&day=2018-02-23&day=2018-02-24&day=2018-02-25&day=2018-02-26&day=2018-02-27&day=2018-02-28

It seems it is taking the last value because of same key name.

Instead of directly submitting the form,submit it using ajax and send the data in an array or as an object

In this case your date fields should be named as an array. If you name multiple fields as day , it will act as single field take the last field value with the same name. So you have to change in one line and it will work nicely.

 textarea.setAttribute("name", "day[]");

JavaScript

Right, lets first start with the JavaScript.

function drawTable(forDate) {
    // Days in a month
    const daysInMonth = new Date(
        forDate.getFullYear(),
        forDate.getMonth() + 1,
        0
    ).getDate();
    // 28

    // Start of a date
    const date = [
        forDate.getFullYear(),
        (forDate.getMonth() + 1 + '').padStart(2, 0)
    ]
    .join('-');
    // 2018-02

    // Reset the table
    const table = document.getElementById("table");
    table.innerHTML = "";

    // For each day of the month
    // Start at one, go until day > daysInMonth. e.g. (1 -> 28)
    for (let day = 1; day <= daysInMonth; day++) {
        const dateString = date + '-' + (day + '').padStart(2, 0);

        // Create the elements.
        const row = document.createElement("tr");
        const cell = document.createElement("td");
        const textarea = document.createElement("textarea");

        textarea.setAttribute("name", "day[]");
        textarea.setAttribute("value", dateString);
        textarea.innerHTML = dateString;
        textarea.setAttribute("placeholder", day);

        // These do nothing.
        // textarea.setAttribute("type", "button");
        // textarea.setAttribute("day", dateString)

        // Stack the children into the table.
        cell.appendChild(textarea);
        row.appendChild(cell);
        table.appendChild(row);
    }

    return table;
}

PHP

Now, lets move on to the PHP. I'm going to first look at the problems in your code.

// Currently 'day' is an array.
// So this will throw an error.
$day = mysqli_real_escape_string($conn, $_request['day']);

// For every '$day[$i]' in '$day'
for ($i = 1; $i < count($day); $i++) {
    // $day is still an array.
    if (empty($day)) {
        $_SESSION['error'] = "Error";

        // The problem that you'll face here is that
        // one empty day fails the rest of the days
        header('Location: insert.php', true, 303);
        exit();
    } else {
        if (mysqli_query($conn, "INSERT INTO calendar (day) VALUES('$day[$i])')")) {
            // Here this will stop on the first '$day[$i]'
            header('Location: insert.php', true, 303);
            exit;
        } else {
            $error= "Error: " .mysqli_error($conn);
            echo "$error";
        }
    }
}

Now, I'm going to look at a possible solution.

// Currently 'day' is an array.
$days = $_request['day'];

// This is how we can carry our errors.
$error = array();

// For every 'day' in the 'days' array.
if (is_array($days))
foreach ($days as $day) {
    // Escape the day.
    $day = mysqli_real_escape_string($conn, $day);

    // Now this will work as expected.
    if (empty($day)) {
        // We shall use the $error array.
        $error[] = array(
            'day' => $day,
            'error' => 'day was empty'
        );
    }

    // Else if there is an error in the SQL query.
    else if (
        !mysqli_query(
            $conn,
            // You see how the '$day' variable is used
            "INSERT INTO calendar (day) VALUES('$day)')"
        )
    ) {
        // We shall use the $error array again here.
        $error[] = array(
            'day' => $day,
            'error' => mysqli_error($conn)
        );
    }
}

// If there was an error.
if (count($error)) {
    // Print the errors.
    print_r($error);
}

// Do your redirect.
header('Location: insert.php', true, 303);

HTML

Finally, let's look at the HTML. I'm going to first look at the problems in your code.

<!-- You do not need to define the blank 'class' -->
<form class="" action="insert.php" method="post">
    <!-- You should close the <table> tag. -->
    <table id="table">

    <!-- This is currently unneeded and could hinder the php. -->
    <input id="day"type="hidden" name="day" value="">

    <!-- You do not need to define the blank 'name' -->
    <input id="btn" type="submit" name="" value="Press">
</form>

Now, I'm going to look at a possible solution.

<form action="insert.php" method="post">
    <table id="table"></table>
    <input id="btn" type="submit" value="Press" />
</form>

*Note: * I have not tried this code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM