简体   繁体   中英

Submitting form through Javascript to PHP not working

Can someone point me in the right direction. I'm not sure why this isn't submitting into my database. I'm trying to create a chat for my website and I can't seem to get this to work properly.

My form:

<form onsubmit="return sendMessage();" class="form-inline">
    <div class="form-group ">
        <input type="text" class="input_custom" id="Message"> 
        <button type="submit" class="btn  btn-default">Send</button>
    </div>
</form>

My JS:

function sendMessage() {
   var message = escape(document.getElementById("Message").value);
   var send = new XMLHttpRequest();
   send.open("GET", "index.php"+"?message="+message, true);
   send.send();
   return false;
}

My PHP:

$sucess = '';
if(isset($_GET['message'])) {
    $message = $_GET['message'];
    $date = new DateTime();
    $date2 = $date->format('l h:i A"');
    $user = $username;
    if(!empty($message)) {
        $db->prepare("INSERT INTO shouts (date, username, shout) VALUES (:date, :username, :shout)");
        $db->execute(array(':date' => $date2, ':username' => $user, ':shout' => $message));
        $sucess = 'shout sent.';
    }
}

See runnable .

Seems your code works :)

Some possible issues ('i'v pointed to them via comments'):

  1. $username variable is undefined, so some sql-constaints prevent inserting row
  2. DB connection is not set.
  3. Some other db related problems. See link about get errors from pdo .

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