issei-kun issei-kun - 1 year ago 111
PHP Question

Insert data AJAX using PHP not working using PDO

How can i add data using AJAX and PHP script?


<form method="POST" >
<td>Enter Question:</td>
<td><input type="text" id="question" name="question"></input></td>
<td colspan="2" align="center"><button name="add-question" id="add-question">+Add Question</button></td>

This is the JS

$(document).ready(function () {
$('#add-question').click(function (e) {
var question = $('#question').val();
var dataString = "question="+question;
type: "POST",
url: "add-question.php",
data: dataString,
success: function (data) {


PHP Script using PDO

if (isset($_POST['add-question'])) {
include 'db.php';
$question = $_POST['question'];
$query = "";
$stmt = $dbh->prepare("INSERT INTO question (name, choices1, choices2, choices3, choices4, answer) VALUES (:name, ':choices1', ':choices2', ':choices3', ':choices4', ':answer')");
$stmt->bindParam(':name', $question);
if ($stmt->execute()) {
echo "Quiz has been added";
} else {
echo "Error adding quiz";


I also included the jquery file. But i don't know why it doens't work. Thanks for those who will help me.

Answer Source

You don't have a POST attribute called "add-question" so this line will fail.

if (isset($_POST['add-question'])) {

Change it to

if (isset($_POST['question'])) {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download