I am having problem with this javascript function.
If I want to submit a form if I do this below it works:
function submitform()
{
var QandAO = document.getElementById("QandA");
QandAO.submit();
}
If I want to add a row into a DB table using AJAX to navigate to the page which INSERTS VALUES, then the code below works:
function submitform()
{
var fieldvalue = $("#QandA").val();
$.post("insertQuestion.php", $("#QandA").serialize ,function(data){
alert("data");
});
}
So I thought to be able to submit the form and add a row into the database, if I do this code below then it should work but it doesn’t. It submits the form but does not add a row in the database. How can this code be fixed so it submits the form and also add a row in DB? Below is the code
function submitform()
{
var fieldvalue = $("#QandA").val();
$.post("insertQuestion.php", $("#QandA").serialize ,function(data){
alert("data");
});
var QandAO = document.getElementById("QandA");
QandAO.submit();
}
InsertQuestion.php looks like this below:
<?php
session_start();
$username="xxx";
$password="xxx";
$database="xxx";
mysql_connect('localhost',$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$insertquestion = array();
$insertquestion[] = "' ". mysql_real_escape_string( $_POST['id'] ) . "'";
$questionsql = "INSERT INTO Question (SessionId)
VALUES (" . implode('), (', $insertquestion) . ")";
mysql_query($questionsql);
mysql_close();
?>
I think the problem is that the second part of your code (the form submit) cuts off the first part before it’s complete. Give the AJAX call a chance to finish by putting the form submit inside the AJAX callback: