Veda Sadhak Veda Sadhak - 4 months ago 12
Ajax Question

jQuery Post Form Data to PHP

I am posting data to PHP from jQuery using data from an HTML form.

Here is the jQuery line that sends the POST

$.post("InsertNewQuestion.php", $("Create_Question_Form").serialize());


Here is the PHP code

<?php
$con = mysql_connect("localhost","root","");

mysql_select_db("Quizzes",$con);

$Quiz_Name = $_POST['Question'];
echo $Quiz_Name;
$Option_1 = $_POST['Option1'];
echo $Option_1;
$Option_2 = $_POST['Option2'];
echo $Option_2;
$Option_3 = $_POST['Option3'];
echo $Option_3;
$Option_4 = $_POST['Option4'];
echo $Option_4;
$Option_5 = $_POST['Option5'];
echo $Option_5;

$rowIDList = mysql_query("SELECT rowID FROM TestQuiz");

$ColumnValues = array();

$CurrentGreatestRowID = -1;

$LCV = 1;

while($row1 = mysql_fetch_assoc($rowIDList)) {

if ($CurrentGreatestRowID < $row1['rowID']) {
$CurrentGreatestRowID = $row1['rowID'];
}
$LCV++;
}

$CurrentRowID = $CurrentGreatestRowID+1;

$sql = "INSERT INTO TestQuiz (rowID,Quiz_Name,Option_1,Option_2,Option_3,Option_4,Option_5,Option_1_Votes,Option_2_Votes,Option_3_Votes,Option_4_Votes,Option_5_Votes)
VALUES(".$CurrentRowID.",'".$Question."','".$Option1."','".$Option2."','".$Option3."','".$Option4."','".$Option5."',0,0,0,0,0);";

if (mysql_query($sql,$con)) {
echo "Inserted values";
}
else {
echo ("Could not insert values: ". mysql_error());
}

mysql_close($con);
?>


Here is the HTML form

<form id="Create_Question_Form" action="" method="POST">
Question Name: input id="Question" class="Create_Question_Text_Box" type="text" name="Question_Name"><span id="Invalid_1"></span><br>
Option 1: input id="Option1" class="Create_Question_Text_Box" type="text" name="Option_1"><span id="Invalid_2"></span><br>
Option 2: input id="Option2" class="Create_Question_Text_Box" type="text" name="Option_2"><span id="Invalid_3"></span><br>
Option 3: input id="Option3" class="Create_Question_Text_Box" type="text" name="Option_3"><span id="Invalid_4"></span><br>
Option 4: input id="Option4" class="Create_Question_Text_Box" type="text" name="Option_4"><span id="Invalid_5"></span><br>
Option 5: input id="Option5" class="Create_Question_Text_Box" type="text" name="Option_5"><span id="Invalid_6"></span><br>
input type="Submit" id="Question_Submit" value="Create Question"></input>
</form>

Answer

Your form selector should be #Create_Question_Form. Note the # indicating that this is an element ID.

$("#Create_Question_Form").serialize()

Update

You are accessing the $_POST values by ID instead of name. Try this:

$Option_1 = $_POST['Option_1'];
$Option_2 = $_POST['Option_2'];
// etc