Values not inserting into database table - javascript

I am trying to insert the values from drop-down and text box throug web page.
first there will be one drop down box that has numbers from 1 to 25..
when i select the number from the dropdown, the corresponding textboxes and dropdown boxes are created.
But when i enter the data and click the submit button,the values are not going to database, instead only the last row values are inserting into database.
for example:
say i have selected 4 from number dropdown, now 4 rows with textbox and dropdown box appears.
when i enter the data in the textbox and select value from dropdown and click submit. the last row values are getting inserted 4 times.
i want it to insert the values correctly...How can i solve this.?
here is the code i am using..
code:
<html>
<head>
<link rel="stylesheet" href="css/common.css" type="text/css">
<link rel="stylesheet" type="text/css" href="css/page.css">
<link rel="stylesheet" type="text/css" href="css/button.css">
<link href="css/loginmodule.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery.js"></script>
<script type='text/javascript' src='js/jquery.autocomplete.js'></script>
<link rel="stylesheet" type="text/css" href="css/jquery.autocomplete.css" />
<script type="text/javascript">
$().ready(function() {
$("#Fname").autocomplete("get_course_list.php", {
width: 260,
matchContains: true,
//mustMatch: true,
//minChars: 0,
//multiple: true,
//highlight: false,
//multipleSeparator: ",",
selectFirst: false
});
});
</script>
<script>
function showUser(str) {
if(str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if(window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gettheater.php?q="+str,true);
xmlhttp.send();
}
</script>
<script type="text/javascript">
function create(param) {
'use strict';
var i, target = document.getElementById('screens');
target.innerHTML = '';
target.innerHTML = '<input name="RowCount" value="' + param + '" hidden />';
for(i = 0; i < param; i += 1) {
target.innerHTML +='</br>';
target.innerHTML +='New Movie '+i+' ';
target.innerHTML += '<input type="text" name="Fname">';
target.innerHTML +=' '+'Language '+' ';
target.innerHTML += "<?php
try {
$dbh = new PDO('mysql:dbname=theaterdb;host=localhost','tiger','tiger');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = 'SELECT language FROM languages;';
$sth = $dbh->prepare($sql);
$sth->execute();
echo "<select name='language' id='course'>";
echo "<option>----Select Language----</option>";
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['language'] ."'>" . $row['language']. " </option>";
}
echo "</select>";
?>";
target.innerHTML +='</br>';
target.innerHTML +='</br>';
}
}
</script>
<style>
#screens{
color:black;
}
</style>
</head>
<body>
<h1>Welcome <?php echo $_SESSION['SESS_FIRST_NAME'];?></h1>
My Profile | Logout
<p>This is a password protected area only accessible to Admins. </p>
<center>
<div class="pan"><br><br>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" autocomplete="off">
<div class="head">Update Theater Information</div>
<table>
<tr>
<td><label for="screens">New Movies Released</label></td>
<td>
<select id="select" onchange='javascript:create(this.value);' name="range">
<option>--Select Number Of New Movies Released--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<div id="screens">
</div>
</td>
<td></td>
</tr>
<tr>
<td></td>
<td><input type="submit" class="button" name='submit' value="Submit" /></td>
</tr>
</table>
</form><br><br>
</div>
<?php
mysql_connect("localhost", "tiger", "tiger") or die(mysql_error());
mysql_select_db("theaterdb") or die(mysql_error());
for ($i=0; $i < $_POST["range"] ; $i++)
{
$query = mysql_query("INSERT INTO movie (movie_name,language) VALUES('$_POST[Fname]','$_POST[language]') ") or die(mysql_error());
}
?>
</center>
</body>
</html>

You should change you name to array like
target.innerHTML += '<input type="text" name="Fname[]">';
And also in insert query should be
$query = mysql_query("INSERT INTO movie (movie_name,language) VALUES('".$_POST['Fname'][$i]."','".$_POST['language']."') ") or die(mysql_error());

1.Use mysqli_* function instead of mysql_* function...
2. What is error showing up.
If you have insertion query on same page then try it:.....
<?php
if(isset($_POST['submit'])
{
mysql_connect("localhost", "tiger", "tiger") or die(mysql_error());
mysql_select_db("theaterdb") or die(mysql_error());
for ($i=0; $i < $_POST["range"] ; $i++)
{
$query = mysql_query("INSERT INTO movie (movie_name,language) VALUES('$_POST[Fname]','$_POST[language]') ") or die(mysql_error());
}
}
?>
It will triger your query when submit button will hit.... may this help

Use this
$query = mysql_query("INSERT INTO movie (movie_name,language) VALUES('".$_POST['Fname']."','".$_POST['language']."') ") or die(mysql_error());
instead of
$query = mysql_query("INSERT INTO movie (movie_name,language) VALUES('$_POST[Fname]','$_POST[language]') ") or die(mysql_error());
You must keep php code outside of quote and Concate them
2.If The index of $_POST Array is string then it must be with quote. (e.x: $_POST[language] it must be $_POST['language']

Thank god....I resolved My issue.....i used the same logic that was applied to first text box...
and now the dropdown values are also getting inserted....
i added array to language[]
echo "<select name='language[]' id='course'>";
and added the $i in loop
.$_POST['language'][$i]
Thanks all for helping me.....
HaPpY CoDiNg....

I don't want to be an ass, but I would suggest cleaning things up and seperating the JavaScript, jQuery and PHP even loose JavaScript AJAX and use jQuery AJAX. It's no surprise code like this is giving you bugs.

Related

Cant seem to get the first dependency to run on AJAX call

I am having significant issues trying to get the AJAX to fire on this PHP code.
I can get the first field populated without issue, however the AJAX call does not seem to populate the first dependency (and therefore the second). I am an AJAX newbie (and have googled extensively) but cannot seem to crack this one.
Note that the ladb.php file runs fine.
<?php
// Include the database config file
include_once 'ladb.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body style="background: #D5DDE0">
<div class="container">
<form action="" method="post">
<div class="form-group col-md-6">
<!-- Country dropdown -->
<label for="country">Country</label>
<select class="form-control" id="country">
<option value="">Select Country</option>
<?php
$query = "SELECT * FROM City_Index GROUP BY country ORDER BY country ASC";
$result = $ladb->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<option value='{$row["countryid"]}'>{$row['country']}</option>";
}
}else{
echo "<option value=''>Country not available</option>";
}
?>
</select><br>
<!-- State dropdown -->
<label for="admin">Administrative Area</label>
<select class="form-control" id="admin">
<option value="">Select Administrative Area</option>
</select><br>
<!-- City dropdown -->
<label for="city">city_ascii</label>
<select class="form-control" id="city">
<option value="">Select City</option>
</select>
</div>
</form>
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
// Country dependent ajax
$("#country").on("change",function(){
var country = $(this).val();
if (countryid) {
$.ajax({
url :"action.php",
type:"POST",
cache:false,
data:{countryid:countryid},
success:function(data){
$("#admin").html(data);
$('#city').html('<option value="">Select Administrative Area</option>');
}
});
}else{
$('#admin').html('<option value="">Select Country</option>');
$('#city').html('<option value="">Select Administrative Area</option>');
}
});
// state dependent ajax
$("#admin").on("change", function(){
var admin = $(this).val();
if (admin) {
$.ajax({
url :"action.php",
type:"POST",
cache:false,
data:{admin:admin},
success:function(data){
$("#city").html(data);
}
});
}else{
$('#city').html('<option value="">Select Administrative Area</option>');
}
});
});
</script>
The action.php file below
<?php
// Include the database config file
include_once 'ladb.php';
// Get country id through state name
$country = $_POST['country'];
if (!empty($country)) {
// Fetch state name base on country id
$query = "SELECT * FROM CityList WHERE country = {$country} GROUP BY admin_name_ascii";
$result = $ladb->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="'.$row['admin_id'].'">'.$row['admin_name_ascii'].'</option>';
}
}else{
echo '<option value="">State not available</option>';
}
}elseif (!empty($_POST['admin'])) {
$admin = $_POST['admin'];
// Fetch city name base on state id
$query = "SELECT * FROM CityList WHERE admin_id = {$admin}";
$result = $ladb->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="'.$row['cityid'].'">'.$row['city_ascii'].'</option>';
}
}else{
echo '<option value="">City not available</option>';
}
}
?>
Any help greatly appreciated!
Thanks to #zergski I note that one of references were defined (countryid in Line 53). DevTools is my new best friend.

Can I insert php & html inside a multi line php variable?

So I'm a total beginner and I'm working on a project to create dynamic dropdown forms. I have written some code and am wondering now if I can insert php & html inside a multi line php variable. This code below is what I just tried[javascript not included here] but php shows error. Is this not possible at all or is it some error on my part? Thanks in advance.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>php & html inside a multi line php variable</title>
</head>
<body>
<?php
$chooseroom=<<<HERE
<div class="select-boxes">
<?php
//Include database configuration file
include('dbConfig.php');
//Get all occupation data
$query = $db->query("SELECT * FROM occupations WHERE status = 1 ORDER BY occupation_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
?>
<select name="occupation" id="occupation">
<option value="">Select occupation</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['occupation_id'].'">'.$row['occupation_name'].'</option>';
}
}else{
echo '<option value="">occupation not available</option>';
}
?>
</select>
<select name="specification" id="specification">
<option value="">Select occupation first</option>
</select>
<select name="expertise" id="expertise">
<option value="">Select specification first</option>
</select>
</div>
HERE;
echo $chooseroom;
</body>
</html>
OK AS REQUESTED BY SOME OF YOU HERE IS MY JAVASCRIPT:
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#occupation').on('change',function(){
var occupationID = $(this).val();
if(occupationID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'occupation_id='+occupationID,
success:function(html){
$('#specification').html(html);
$('#expertise').html('<option value="">Select specification first</option>');
}
});
}else{
$('#specification').html('<option value="">Select occupation first</option>');
$('#expertise').html('<option value="">Select specification first</option>');
}
});
$('#specification').on('change',function(){
var specificationID = $(this).val();
if(specificationID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'specification_id='+specificationID,
success:function(html){
$('#expertise').html(html);
}
});
}else{
$('#expertise').html('<option value="">Select specification first</option>');
}
});
});
</script>
Yes it is possible to add multi line html and php to a variable. You can add multiple entries in options as given below
while($row = $query->fetch_assoc()){
/* here . operator is used to append
to the existing value of $chooseroom */
$chooseroom .= '<option value="'.$row['occupatio_id'].'">'.$row['occpation_name'].'</option>';
}
Print this variable where it is required as
<?php echo $chooseroom; ?>
You can't do what you're attempting in the way you're attempting it; what you're trying to do is run PHP code inside a HEREDOC block.
However, you can put the PHP code, and create your set of options, before that block and just interpolate it where required (you don't even need to assign the HEREDOC block to a variable, you can use echo it out):
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>php & html inside a multi line php variable</title>
</head>
<body>
<?php
//Include database configuration file
include('dbConfig.php');
//Get all occupation data
$query = $db->query("SELECT * FROM occupations WHERE status = 1 ORDER BY occupation_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
// Create an HTML options string
$htmlOptions = "";
if($rowCount > 0) {
while($row = $query->fetch_assoc()){
$htmlOptions .= '<option value="'.$row['occupation_id'].'">'.$row['occupation_name'].'</option>';
}
} else {
$htmlOptions .= '<option value="">occupation not available</option>';
}
// Output
echo <<<HERE
<div class="select-boxes">
<select name="occupation" id="occupation">
<option value="">Select occupation</option>
$htmlOptions
</select>
<select name="specification" id="specification">
<option value="">Select occupation first</option>
</select>
<select name="expertise" id="expertise">
<option value="">Select specification first</option>
</select>
</div>
HERE;
?>
</body>
</html>
Though, to be honest, the whole HEREDOC thing is slightly superfluous here as you can just break out of the PHP and echo out your options where you need them - makes for slightly better separation between the PHP and HTML code as well:
<?php
//Include database configuration file
include('dbConfig.php');
//Get all occupation data
$query = $db->query("SELECT * FROM occupations WHERE status = 1 ORDER BY occupation_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
// Create an HTML options string
$htmlOptions = "";
if($rowCount > 0) {
while($row = $query->fetch_assoc()){
$htmlOptions .= '<option value="'.$row['occupation_id'].'">'.$row['occupation_name'].'</option>';
}
} else {
$htmlOptions .= '<option value="">occupation not available</option>';
}
// OUTPUT
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>php & html inside a multi line php variable</title>
</head>
<body>
<div class="select-boxes">
<select name="occupation" id="occupation">
<option value="">Select occupation</option>
<?= $htmlOptions; ?>
</select>
<select name="specification" id="specification">
<option value="">Select occupation first</option>
</select>
<select name="expertise" id="expertise">
<option value="">Select specification first</option>
</select>
</div>
</body>
</html>
I've always liked this solution myself:
<?php
include('dbConfig.php');
$query = $db->query("SELECT * FROM occupations WHERE status = 1 ORDER BY occupation_name ASC");
$rowCount = $query->num_rows;
ob_start();
if ( $rowCount > 0 ) {
while( $row = $query -> fetch_assoc() ){
echo '<option value="'.$row['occupation_id'].'">'.$row['occupation_name'].'</option>';
}
} else {
echo '<option value="">occupation not available</option>';
}
$values = ob_get_clean();
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>php & html inside a multi line php variable</title>
</head>
<body>
<div class="select-boxes">
<select name="occupation" id="occupation">
<option value="">Select occupation</option>
<?php echo $values; ?>
</select>
<select name="specification" id="specification">
<option value="">Select occupation first</option>
</select>
<select name="expertise" id="expertise">
<option value="">Select specification first</option>
</select>
</div>
</body>
</html>

PHP- How to disable a hyperlink if option not selected?

I'm trying to disable the hyperlink if an option is not selected. The problem is that the this is an existing project in my company and the original coder isn't here anymore. So I cannot find the HTML source. All I have is this array. I tried using javascript like we do in the <option> tag, but it doesn't work.
array("type"=>"select", "name"=>"agentId", "value"=>getAgentASMOption($partyCode), "title"=>"Select Party" ),
<td class="no-border" align="center">
<a href="<?php echo SITEURL; ?>/productnew/productnew-details/?id=<?php echo $d['mmID']; ?>&mCatID=<?php echo $_REQUEST["mCatID"];?> ">
<label>View</label>
</a>
</td>
function getAgentASMOption($partyCode=0) {
global $DB;
$sel = "";
$sql ="SELECT DISTINCT(A.partyCode), P.NAME1, P.ORT01 FROM`".$DB->pre."agent_party` AS A LEFT JOIN `".$DB->pre."party_master` AS P ON P.KUNNR=A.partyCode where A.agentCode = '".sprintf('%d',$_COOKIE['PARTYCODE'])."' ORDER BY P.NAME1 ASC";
$res = $DB->dbRows($sql);
if($DB->numRows> 0){
foreach($res as $asm) {
$sel = "";
if($asm['partyCode'] == $partyCode) { $sel = "selected"; }
//$str .= '<option value="'.$asm['partyCode'].'" '.$sel.'>'.$asm['NAME1'].'</option>';
$str .= '<option value="'.$asm['partyCode'].'" '.$sel.'>'.$asm['NAME1'].' ----- '.$asm['ORT01'].' ----- '.$asm['partyCode'].' </option>';
}
}
}
Rendered HTML:-
<select id="agentId" name="agentId" title="Select"></select>
<option value="">--Select--</option>
<option value="1002410">(MUMBAI) SANDEEP FABRICS ----- KALBADEVI ----- 1002410 </option>
<option value="1013283">(PALGHAR)BLUE SKIES FASHION AVENUE ----- PALGHAR ----- 1013283 </option>
</select>
$sql = "SELECT NAME1,ORT01 FROM `" . $DB->pre . "party_master`WHERE `KUNNR`= '" .$_SESSION['party_Code']. "'";
$res = $DB->dbRow($sql);
If you give the link an ID or class, it is safer to select than what I had to do now
NOTE: Links do not have disable property so the code below is using CSS and event preventDefault
Assuming the select has a <option value="">Select Party</option>, you can do this:
$(function() {
$("#agentId").on("change", function() {
if ($(this).val() == "") {
$(".proddet").prop("disabled","disabled");
$(".proddet").addClass("disabled");
}
else {
$(".proddet").removeProp("disabled");
$(".proddet").removeClass("disabled");
}
}).change(); // in case a "selected" option is already present
$(".proddet").on("click",function(e) {
if ($(this).prop("disabled") !== undefined) {
e.preventDefault();
}
})
});
a[disabled] { pointer-events:ignore; color:lightgray }
a.disabled { pointer-events:ignore; color:lightgray }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<select id="agentId" name="agentId" title="Select">
<option value="">--Select--</option>
<option value="1002410">(MUMBAI) SANDEEP FABRICS ----- KALBADEVI ----- 1002410 </option>
<option value="1013283">(PALGHAR)BLUE SKIES FASHION AVENUE ----- PALGHAR ----- 1013283 </option>
</select>
<table>
<tr>
<td class="no-border" align="center">
<a class="proddet" href="/productnew/productnew-details/?id=<?php echo $d['mmID']; ?>&mCatID=bla">
<label>View</label>
</a>
</td>
</tr>
</table>

how to call a javascript function from php

I am trying to read selected option (month) from mysql database via tabela.php (php then selects only users and their hours for he month selected). At this moment when i select a option i get results but it is shown in new site which is tabela.php. How can i make ajax or script to show me results on my HTML site.
For example: table on html is first empty, user then selects Januar and below that selection table should autofill with correct results.
HTML:
<form action="tabela.php" method="post">
Mesec: <select name="meseci", onchange="this.form.submit()">
<option value="o"> </option>
<option value="1">Januar</option>
<option value="2">Februar</option>
</select><br><BR>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#results').load('tabela.php');
}, 3000); // the "3000" here refers to the time to refresh the div. it is in milliseconds.
});
php:
$conn = new mysqli($servername, $username, $password, $dbname);
$x = (isset($_POST['meseci']) ? $_POST['meseci'] : null);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysqli_query($conn, "SELECT ime, stevilo_ur FROM smart_ure WHERE mesec = '$x ' ");
echo "<table border='1'>
<tr>
<th>ime</th>
<th>stevilo_ur</th>
</tr>";
while ( $db_v = mysqli_fetch_assoc($result) ) {
echo "<tr>";
echo "<td>" . $db_v['ime'] ."</td>";
echo "<td>" . $db_v['stevilo_ur'] ."</td>";
echo"</tr>";
}
echo "</table>";
mysqli_close($conn);
if (isset ($_GET['update']))
{
echo $tbl;
die ();
}
EDITED:
<form method="post" id="test_form">
Mesec: <select id="meseci">
<option value="o"> </option>
<option value="1">Januar</option>
<option value="2">Februar</option>
</select><br><BR>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({ cache: false });
$(document).on('change','select[#meseci]',function(){
$post('tabela.php',$('#test_form').serialize()).done(function(results){
$('#results').html(results);
});
});
></script>
<div id="results"</div>
Consider you have div in your current page with id=result. Now, in your script file you can use onChange() on the select tag to get the data using ajax.
JS script:
$(document).on('change','select[name="meseci"]',function(){
$.post('tabela.php',$('#test_form').serialize()).done(function(result){
$('#result').html(result);
});
});
Add id to your form, in above script I have used id=test_form.
<form action="tabela.php" method="post" id="test_form">
Update your form tag:
<form method="post" id="test_form">
Also, remove onChange from your select tag.
<select name="meseci">
With the help of #jaysingkar we got it to work. Below is the answer:
<form method="post" id="test_form">
Mesec: <select id="meseci" name="meseci">
<option value="o"> </option>
<option value="1">Januar</option>
<option value="2">Februar</option>
</select><br><BR>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({ cache: false });
});
$(document).on('change','#meseci',function(){
$.post('tabela.php',$('#test_form').serialize()).done(function(result){
$('#result').html(result);
});
});
</script>
<div id="result"</div>

Two submit button - default submit not working because of other

I have two submit buttons in a php file take_test:-
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: index.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to index.php");
}
// Everything below this point in the file is secured by the login system
// We can display the user's username to them by reading it from the session array. Remember that because
// a username is user submitted content we must use htmlentities on it before displaying it to the user.
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-AU">
<head>
<title>OSTA - Take Test</title>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
<link href="css.css" rel="stylesheet" type="text/css" />
<script language="javascript" type="text/javascript" src="editarea/edit_area/edit_area_full.js"></script>
</head>
<body>
<div class="wrapper">
<div class="header">
<h1> OSTA - Take Test</h1>
</div><!-- end header -->
<div class="nav">
<ul>
<li>Hello <?php echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF- 8'); ?></li>
<li>Assignments</li>
<li>Edit Account</li>
<li>Logout</li>
</ul>
</div><!-- end nav -->
<div class="content">
<?php
echo "<form id='code' action='take_test.php' method='post'>";
$con=mysqli_connect($host,$username,$password,$dbname);
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['next']))
{
$aa = $_POST['source'];
//foreach($aa as $k) :
$query = "INSERT INTO student_test(status,user_name,aaid,qqid,answer,submit_time)
VALUES('1','{$_SESSION['user'] ['username']}','{$_POST['edit']}','{$_POST['qid']}','{$aa}',NOW())";
$rest5=mysqli_query($con,$query);
//endforeach;
//}
//if (!$rest)
//{
// die('Error: ' . mysqli_error($con));
//}
$qry="SELECT qid FROM questions where aid={$_POST['edit']}
ORDER BY qid DESC
LIMIT 1";
$restfinal=mysqli_query($con,$qry);
$rowfinal = mysqli_fetch_array($restfinal);
$qidfinal = $rowfinal['qid'];
if ($qidfinal==$_POST['qid'])
{
echo "Test Submitted Successfully.";
sleep( 3 );
header("Location: s_assignments.php");
echo "Test Submitted Successfully.";
}
}
if(isset($_POST['edit']))
{
$id2 = $_POST['edit'];
if(isset($_POST['next']))
{
$a=$_POST['a'];
if(!isset($a)){
$a=0;
}}
if(!isset($a)){
$a=0;
}
//$res=mysqli_query($con,"Select * from assignments where a_id='$id'");
$res1 = mysqli_query($con,"Select n_question from assignments where a_id='$id2'");
$row1 = mysqli_fetch_array($res1);
$n_q = $row1['n_question'];
$res8=mysqli_query($con,"Select * from questions where aid='$id2' LIMIT 1 OFFSET $a");
}
echo "<table border='0' cellspacing='1' cellpadding='1'>";
echo "<tr>
<th>Question</th>
</tr>";
while($rowt = mysqli_fetch_array($res8))
{
echo "<tr>";
echo "<td>" . $rowt['question'] . "</td>";
echo "</tr>";
echo "<td>"."<input type ='hidden' id='qid' name ='qid' value=".$rowt['qid']."></td>";
echo "<td>"."<input type ='hidden' id='aid' name ='edit' value=".$rowt['aid']."></td>";
//echo "<td>"."<input type ='hidden' id='id' name ='id' value=".$id."> </td>";
echo "<tr>";
echo "<tr>";
echo "<td>"."<hr>"."<td>";
echo "</tr>";
echo "<td>"."<label for='lang'>Select Language:</label>
<select name='lang' id='lang'>
<option value='7'>Ada (gnat-4.3.2)</option>
<option value='13'>Assembler (nasm-2.07)</option>
<option value='45'>Assembler (gcc-4.3.4)</option>
<option value='104'>AWK (gawk) (gawk-3.1.6)</option>
<option value='105'>AWK (mawk) (mawk-1.3.3)</option>
<option value='28'>Bash (bash 4.0.35)</option>
<option value='110'>bc (bc-1.06.95)</option>
<option value='12'>Brainf**k (bff-1.0.3.1)</option>
<option value='11'>C (gcc-4.3.4)</option>
<option value='27'>C# (mono-2.8)</option>
<option value='1' selected='selected'>C++ (gcc-4.3.4)</option>
<option value='44'>C++0x (gcc-4.5.1)</option>
<option value='34'>C99 strict (gcc-4.3.4)</option>
<option value='14'>CLIPS (clips 6.24)</option>
<option value='111'>Clojure (clojure 1.1.0)</option>
<option value='118'>COBOL (open-cobol-1.0)</option>
<option value='106'>COBOL 85 (tinycobol-0.65.9)</option>
<option value='32'>Common Lisp (clisp) (clisp 2.47)</option>
<option value='102'>D (dmd) (dmd-2.042)</option>
<option value='36'>Erlang (erl-5.7.3)</option>
<option value='124'>F# (fsharp-2.0.0)</option>
<option value='123'>Factor (factor-0.93)</option>
<option value='125'>Falcon (falcon-0.9.6.6)</option>
<option value='107'>Forth (gforth-0.7.0)</option>
<option value='5'>Fortran (gfortran-4.3.4)</option>
<option value='114'>Go (gc-2010-07-14)</option>
<option value='121'>Groovy (groovy-1.7)</option>
<option value='21'>Haskell (ghc-6.8.2)</option>
<option value='16'>Icon (iconc 9.4.3)</option>
<option value='9'>Intercal (c-intercal 28.0-r1)</option>
<option value='10'>Java (sun-jdk-1.6.0.17)</option>
<option value='35'>JavaScript (rhino) (rhino-1.6.5)</option>
<option value='112'>JavaScript (spidermonkey) (spidermonkey-1.7)</option>
<option value='26'>Lua (luac 5.1.4)</option>
<option value='30'>Nemerle (ncc 0.9.3)</option>
<option value='25'>Nice (nicec 0.9.6)</option>
<option value='122'>Nimrod (nimrod-0.8.8)</option>
<option value='43'>Objective-C (gcc-4.5.1)</option>
<option value='8'>Ocaml (ocamlopt 3.10.2)</option>
<option value='119'>Oz (mozart-1.4.0)</option>
<option value='22'>Pascal (fpc) (fpc 2.2.0)</option>
<option value='2'>Pascal (gpc) (gpc 20070904)</option>
<option value='3'>Perl (perl 5.12.1)</option>
<option value='54'>Perl 6 (rakudo-2010.08)</option>
<option value='29'>PHP (php 5.2.11)</option>
<option value='19'>Pike (pike 7.6.86)</option>
<option value='108'>Prolog (gnu) (gprolog-1.3.1)</option>
<option value='15'>Prolog (swi) (swipl 5.6.64)</option>
<option value='4'>Python (python 2.6.4)</option>
<option value='116'>Python 3 (python-3.1.2)</option>
<option value='117'>R (R-2.11.1)</option>
<option value='17'>Ruby (ruby-1.9.2)</option>
<option value='39'>Scala (scala-2.8.0.final)</option>
<option value='33'>Scheme (guile) (guile 1.8.5)</option>
<option value='23'>Smalltalk (gst 3.1)</option>
<option value='40'>SQL (sqlite3-3.7.3)</option>
<option value='38'>Tcl (tclsh 8.5.7)</option>
<option value='62'>Text (text 6.10)</option>
<option value='115'>Unlambda (unlambda-2.0.0)</option>
<option value='101'>Visual Basic .NET (mono-2.4.2.3)</option>
<option value='6'>Whitespace (wspace 0.3)</option>
</select>". "</td>";
echo "</tr>";
echo "<tr>";
echo "<td>"."<label for='source'>Source Code:</label>"."</td>";
echo "</tr>";
echo "<tr>";
echo "<td>"."<textarea cols='80' rows='12' name='source' id ='source'> </textarea>"."</td>";
echo "</tr>";
}
echo "<tr>";//echo "<br />";
echo "<td>"."<label for='input'>Input: <span class='description'>(Data that will be given to the program on the stdin.)</span></label>";
//echo "<br />";
echo "</tr>";
echo "<tr>";
echo "<td>"."<textarea cols='40' rows='3' name='input' id='input'></textarea>". " </td>";
echo "</tr>";
$a=$a+1;
echo "<input type='hidden' value='$a' name='a'>";
// echo "<td>"."<a href='take_test.php'> "
//echo "<td>"."<input type ='submit' name ='compile' value='Compile Code'>"."</td>";
echo "<td>"."<input type='submit' name='compile' id='compile' value='Compile Code'>"."</td>";
echo "<td>"."<input type ='submit' name ='next' value='Next Question'>"."</td>";
echo "</table>";
echo"</form>";
?>
<div id="response">
<div class="meta"></div>
<div class="output"></div>
</div>
</div><!-- end content -->
<div class="footer">
<p>designed by | © </p>
</div><!-- end footer -->
</div><!-- end wrapper -->
<script language="javascript" type="text/javascript">
editAreaLoader.init({
id : "source" // textarea id
,syntax: "css" // syntax to be uses for highgliting
,start_highlight: true // to display with highlight mode on start-up
});
</script>
<script type="text/javascript" src="jquery.min.js"></script>
<script src="script.js"></script>
<!-- <script src="../jquery/jquery-1.4.1.min.js"></script> -->
</body>
</html>
One submit name=next i am detecting through
if(isset($_POST['next']))
and the other through
Here is the code for script.js
jQuery(document).ready(function($) {
//$('input[name=compile]').on('click',function(){
// $(this).closest("#code")[0].submit();})
//$('#compile').on('click', function() {
$('#code').submit( function(){
var data = $(this).serialize();
var source = $('textarea#source').val();
if( source == '' ) {
alert( 'No source code provided');
return false;
}
$(this).append('<div class="loading">Processing...</div>');
$.ajax({
type: 'post',
url: 'process.php',
dataType: 'json',
data: data + '&process=1',
cache: false,
success: function(response){
$('.loading').remove();
$('.cmpinfo').remove();
$('#response').show();
//alert(response);
console.log(response.raw);
if( response.status == 'success' ) {
$('.meta').text( response.meta );
$('.output').html('<strong>Output</strong>: <br><br><pre>' + response.output + '</pre>');
if( response.cmpinfo ) {
$('.cmpinfo').remove();
$('.meta').after('<div class="cmpinfo"></div>');
$('.cmpinfo').html('<strong>Compiler Info: </strong> <br><br>' + response.cmpinfo );
}
} else {
//$('.output').html('<pre>' + response + '</pre>');
alert( response.output );
}
//alert( response.msg );
}
});
return false;
});
});
The problem is whenever I click on either compile button or next button it considers compile button only. If i remove script file the next button runs perfectly.
Please give any suggestion.
I have tried a lot of solutions but nothing is working.
The $('#code').submit function in the JS file seems to be the problem. Since both buttons in your PHP are submit buttons, clicking on either of those two buttons will trigger the form submit action and it in-turn is triggering the AJAX request for process.php.
If the script file is commented out, then the default action page mentioned in your form tag is called and that is the reason why your next button works when the script is commented out.
You should add a control within the JS file to check which of those submit buttons was actually clicked by the user and then do the appropriate action. The below is a very basic sample for your reference:
HTML
<form id="code" action="aa.php" method="post">
<input type="submit" class="button" name="compile" value="compile"/>
<input type="submit" class="button" name="next" value="next"/>
</form>
JS (to be executed on DOM ready)
var buttonpressed;
$('.button').click(function() {
buttonpressed = $(this).attr('name');
}); //This will set the name of the button that was clicked to the buttonpressed variable whenever a button is clicked
$('#code').submit(function() {
//The below lines check for the button's name upon form submit and then process accordingly
if(buttonpressed=="next") alert("Add code to next");
else alert("Add code to compile");
buttonpressed='';
return false;
});

Categories

Resources