0

I have dynamically generated nav-pills. Each of them contains a form in which a user will answer a question by checking a radio button. I am using jquery to submit the form so it will not refresh the page. The problem now is that only the first pill submits without refreshing page, others refresh the page at submitting. How will I modify my code below so that all the nav-pills will submit without refreshing the page. My codes are shown below.

HTML

<!--The first pill is always displayed by default-->
if($i == '1'){
    $tab_menu .= "
    <li class='active'><a href='#$test_id' data-toggle='tab'>$i </a></li>
    ";

    $tab_content .= " <div id='$test_id' class='tab-pane fade in active'>
    ";
}
<!--Other nav-pills display when clicked-->
else{
    $tab_menu .= "
    <li><a href='#$test_id' data-toggle='tab'>$i </a></li>
    ";
    $tab_content .= " <div id='$test_id' class='tab-pane fade'>";
}

FORM

$tab_content .= 

"<form id='radioForm' action='radio_no_refresh.php' method='post'>

     <h4>Question No $i</h4>
     <input type='text' name='quest1' value='$question' hidden>
     A <input type='radio' name='radio' value='A'>$option_a
     B <input type='radio' name='radio' value='B'>$option_b
     C <input type='radio' name='radio' value='C'>$option_c
     D <input type='radio' name='radio' value='D'>$option_c

     <button id='subm' name='enter' style='float:right' class='btn btn-success' ><b>Save & Next</b></button>

</form>  ";

Jquery

$("#subm").click( function() {
$.post( $("#radioForm").attr("action"), $("#radioForm").serialize(), function(info){ $("#result").html(info); } );
clearInput();
});

$("#radioForm").submit( function() {
    return false;
});

function clearInput() {

$("#radioForm")[0].reset(); 
}

PHP

$questn1 = $_POST['quest1'];
$radio_ans1 = $_POST['radio'];

$query = "insert into answers (question,answer,) values ('$questn1','$radio_ans1')";
$run_query = mysqli_query($con, $query);
if($run_query){
echo "<script>alert('Answer inserted)</script>";
}
else{
    echo "Insertion Failed";
}
Oponjous
  • 37
  • 7
  • Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use prepared statements with bound parameters, via either the [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php) drivers. [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Aug 28 '17 at 16:09
  • @Alex I am new to this site, what do you by prepared statements with bound parameters, via either the mysqli or PDO drivers? – Oponjous Aug 28 '17 at 16:26
  • Maybe read the pages I linked? – Alex Howansky Aug 28 '17 at 16:28

0 Answers0