I need an example of how to use php and ajax to insert data into the database

Am new to ajax and I can retrieve data from the database using ajax but to insert data into database using ajax is not working but this is the script i have on ground.

This is the PHP script

        try {
            $linkas = 2;
            require_once 'db/DBConnect.php';
            $errors = [];
            $good = true;
            if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['testimony'])):
                $testimony = filter_input(INPUT_POST, 'testimony', FILTER_SANITIZE_STRING);

                if (strlen($testimony) < 20):
                    //report error and do not go
                    $errors[] = 'It has to be more than 20 characters' . '<br>';
                    $good = false;
                    $good = true;
                    if ($good):
                        $insertTestimony = 'INSERT INTO testimony(content, j_member_id, time_send) ';
                        $insertTestimony .= 'VALUES (:testimony, :user_id, NOW())';
                        $insert = $conn1->prepare($insertTestimony);
                        $insert->bindValue(':testimony', $testimony, PDO::PARAM_STR);
                        $insert->bindValue(':user_id', $linkas, PDO::PARAM_INT);
                        if ($insert->rowCount() == 1):
                            //success message
                            $_SESSION['msg'] = 'Thanks for the testimony';
                            header('Location: index.php');
                            //fail message
                            echo 'Something is wrong, please resubmit';
        } catch (Exception $e) {
            echo 'Database error: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine();

This is the HTML script

        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <section class="">
                <div id="testifyForm">
                    <form action="" method="post" id="testimony" accept-charset="utf-8">
                            <legend>Your testimony</legend>
                            <label for="testimony"></label>
                            <textarea id="testimony" name="testimony" maxlength="300"></textarea>
                        <input type="submit" name="testify" id="testify" value="Testify">
        <script src="js/ajax.js"></script>
        <script src="testify.js"></script>

And this is the javascript

function validateForm() {
    'use strict';
    var testimony = document.getElementById('testimony');
    if ((testimony.value.length > 20)) {
        var ajax = getXMLHttpRequestObject();

        ajax.onreadystatechange = function () {
            if (ajax.readyState == 4) {
                if ((ajax.status >= 200 && ajax.status < 300) || (ajax.status == 300)) {
                    //return ajax.responseText
                    document.getElementById('testifyForm').innerHTML = ajax.responseText;
                } else {
                    //return ajax.statusText
                }//End of status
                ajax = null;
            }//End of readyState
        };//End of onreadystatechange
        //return true;
        ajax.open('POST', 'empty.php', true);
        ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        var data = 'testimony=' + encodeURIComponent(testimony.value);
        return false;
    } else {
        document.getElementById('error').innerHTML = 'Characters must be more than 20 words';
        return false;
    }//End of testimony

function init() {
    'use strict';
    if (document && document.getElementById) {
        var testifyForm = document.getElementById('testifyForm');
        testifyForm.onsubmit = validateForm;

window.onload = init;

The script is the same as your previous topic where it was suggested to use error reporting. Apparently you managed to solve the problem and declined to enlighten other users with the solved solution.

Why do you think it is not necessary to use error reporting on this new problem?

Also as mentioned before the script is confusing, one particular aspect is the unnecessary toggling of the $good variable. A simplified version was given which is not implemented. Why insist on using the original script?

apparently since that time I haven’t login since last night(morning here in Nigeria), and I just posted the new challenge without checking for other comments. I will check that right away

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.