当前位置: 动力学知识库 > 问答 > 编程问答 >

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.
分享给朋友:
您可能感兴趣的文章:
随机阅读: