Dynamic html form values are not being stored in database - javascript

I am developing a game portal in which professor should be able to add any type of questions in a game. I have created the question type(multiple choice or descriptive ) functions in form.php and i am calling them in my main file. First of all in the loop I am calling main box(simple html box) in which i have to add the question. And its working fine. Now i have to store the dynamically changed boxes values in database. But i don't know where i am wrong. Following is my form.php in which i am creating forms to call in the main file.
<?
$i=$_post['i'];
$_SESSION["input_type"][$i]= $_POST["type"];
if($_SESSION["input_type"][$i]==1)
{
form($i);
}
elseif($_SESSION["input_type"][$i]==2)
{
form1();
}
function form($i)
{
?>
<div class="control-group">
<div class="controls">
<textarea class="large m-wrap" placeholder=" Statement " cols="50"rows="3" name="statement<?echo $i;?>" style="text-align:center;" id="statement<?echo $i;?>"></textarea>
</div>
</div>
<div class="name">
<input name="option<?echo $i.'1';?>" id="option<?echo $i.'1';?>" placeholder="Option 1" style="width:170px;" type="text"/>
<input name="option<?echo $i.'2';?>" id="option<?echo $i.'2';?>" type="text" style="width:170px;" placeholder="Option 2"/>
<input name="option<?echo $i.'3';?>" id="option<?echo $i.'3';?>" type="text" style="width:170px;" placeholder="Option 3"/>
<input name="option<?echo $i.'4';?>" id="option<?echo $i.'4';?>" type="text" style="width:170px;" placeholder="Option 4"/>
</div>
<div class="control-group">
<div class="controls">
&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp
<label class="radio">
<input type="radio" name="option<?echo $i.'1';?>_default" id="option<?echo $i.'1';?>_default" />
Option 1
</label>
&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp
<label class="radio">
<input type="radio" name="option<?echo $i.'2';?>_default" id="option<?echo $i.'2';?>_default" checked />
Option 2
</label>
&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp
<label class="radio">
<input type="radio" name="option<?echo $i.'3';?>_default" id="option<?echo $i.'3'?>_default" />
Option 3
</label>
&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp
<label class="radio">
<input type="radio" name="option<?echo $i.'4';?>_default" id="option<?echo $i.'4';?>_default" />
Option 4
</label>
</div>
</div>
<?php
}
//end
?>
<?php
function form1()
{ ?>
<div class="control-group" id ="field" name="field">
<label class="control- label">Answer</label>
<div class="controls">
<input type="text" placeholder="Answer" id ="ans" name="ans" class="m-wrap small" />
</div>
</div>
<?
}
?>
This is my main file in which i am cakking the form.php functions to add questions
<!-- BEGIN PAGE -->
<div class="page-content">
<form action="storeGame.php" method="POST">
<div class="control-group">
<label class="control-label">Game Name</label>
<div class="controls">
<input type="text" id="game_name" name="game_name" placeholder="Enter Game Name" class="m-wrap large" />
</div>
</div>
<!-- BEGIN BORDERED TABLE PORTLET-->
<?
$q_no=5;
for ($i=0;$i<$_SESSION["q_inc"]; $i++)
{
?>
<div class="portlet box yellow">
<div class="portlet-title">
<h4><i class="icon-coffee"></i>#<?echo $i+1;?> </h4>
<div class="tools">
</div>
</div>
<div class="portlet-body">
<table class="table table-bordered table-hover">
<thead>
</thead>
<tbody>
<form action="newGame.php" method="POST" id="input_type" name="input_type">
<div class="control-group">
<label class="control-label" > Add Input</label>
<div class="controls">
<select class="medium m-wrap question_type" data-question-no="<?echo $i;?>" tabindex="1" id="type<?echo $i;?>" name="type<?echo $i;?>">
<option value="">Input Type</option>
<option value="1">Multiple Choice</option>
<option value="2">Input Field</option>
</select>
</div>
<div id="answer_no_<?php echo $i ?>"></div>
</div>
</form>
</tbody>
</table>
</div>
</div>
<script>
$(document).ready(function(){
$('.question_type').change(function(){
var question_no=$(this).attr('data-question-no');
$.ajax({
url: "form.php",
type:'post',
data:{
type:$(this).val(),
i:question_no
},
success:function(data){
$('#answer_no_'+question_no).html(data);
}
});
});
});
</script>
<?
}
?>
<!-- END BORDERED TABLE PORTLET-->
<!-- BEGIN PAGE CONTAINER-->
<div class="container-fluid">
<!-- BEGIN PAGE HEADER-->
<div class="row-fluid">
<div class="span12">
<!-- BEGIN STYLE CUSTOMIZER -->
<div class="color-panel hidden-phone">
<div class="color-mode-icons icon-color"></div>
<div class="color-mode-icons icon-color-close"></div>
<div class="color-mode">
<p>THEME COLOR</p>
<ul class="inline">
<li class="color-black current color-default" data-style="default"></li>
<li class="color-blue" data-style="blue"></li>
<li class="color-brown" data-style="brown"></li>
<li class="color-purple" data-style="purple"></li>
<li class="color-white color-light" data-style="light"></li>
</ul>
<label class="hidden-phone">
<input type="checkbox" class="header" checked value="" />
<span class="color-mode-label">Fixed Header</span>
</label>
</div>
</div>
<!-- END BEGIN STYLE CUSTOMIZER -->
<!-- BEGIN PAGE TITLE & BREADCRUMB-->
<h3 class="page-title">
</h3>
<!-- END PAGE TITLE & BREADCRUMB-->
</div>
</div>
<!-- END PAGE HEADER-->
<!-- BEGIN PAGE CONTENT-->
<div class="row-fluid">
<div class="span12" >
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" >
<input type="hidden" id="session" data="#Request.RequestContext.HttpContext.Session['questNo']" />
<!-- <a class="btn green" type="submit" ><i class="icon-plus" ></i></a> -->
<button type="submit" id="add_q" name="add_q" class="btn green"><i class="icon-plus"></i></button>
</form>
</div>
<!-- END PAGE CONTENT-->
</div>
<!-- END PAGE CONTAINER-->
<button type="submit" class="btn yellow btn-block" id="getGames" name="getGames" class="btn green">Create Game <i &nbsp class="m-icon-big-swapright m-icon-white"></i></button>
</form>
</div>
</div>
<!-- END PAGE -->
And below is my storeGame.php file in which i am getting values of question fields and saving in the database but the dynamic box values are not being saved but all other box values are being saved.
<?
session_start();
include_once("../Includes/db_connection.php");
$lecturer_id = $_SESSION["lecturer_id"];
$game_name=mysql_real_escape_string($_POST['game_name']);
echo $_SESSION["lecturer_id"];;
echo $game_name;
mysql_query("insert into games(game_name, lecturer_id) values ('$game_name', '$lecturer_id')");
for($i=0;$i<$_SESSION["q_inc"];$i++)
{
$input_type = mysql_real_escape_string($_POST['type'.$i]);
if($input_type=='1')
{
$question= $_POST['statement'.$i];
$val1= $_POST['option'.$i.'1'];
$val2= $_POST['option'.$i.'2'];
$val3= $_POST['option'.$i.'3'];
$val4= $_POST['option'.$i.'4'];
$default1= $_POST['option'.$i.'1'.'_default'];
$default2= $_POST['option'.$i.'2'.'_default'];
$default3= $_POST['option'.$i.'3'.'_default'];
$default4= $_POST['option'.$i.'4'.'_default'];
mysql_query("insert into subgames(game_id, input_id, statement, option1, option2, option3, option4, default1, default2, default3, default4) values ((SELECT id
FROM games WHERE game_name = '$game_name'), '$input_type', '$question', '$val1', '$val2', '$val3', '$val4', '$default1', '$default2', '$default3', '$default4')");
$error= mysql_error();
}
elseif($input_type=='2')
{
$question= $_POST['quest'];
$answer= $_POST['ans'];
// it is not implemented so leave it
}
}
Kindly help me i have tried a lot but i don't know where i am wrong. Thanks in advance

First of all I want to tell you that there are lots of problem in your code. Those I got are as follows.
1: There is no need to paste the entire html code of header and footer as well. This causes to skipped from the people who can give you answer, they run away after seeing lots of code. i.e. unnecessary.
2: You have defined multiple form tags, and these forms are nested to each other. every form should be closed before opening any other form tag.
3: Radio button tag's name should have the same for every group of the option, their value should be different not the name. for example for gender there should be two radio input tag with same name name="gender" and with different value like value="male" & value="female". you'll get the only one value for the radio button with same name.
4: if you are going to use session anywhere on the page, it first of all should be started before printing any output.
5: You have not given any value for the default value of radio button. So there should be a value attribute with different value inside that
6: whenever you are going to name a funtion, name it according to its functionality, not like a, b, c. Here I'm going to change your form to form_multiple() and form1 to form_input()
7: when you are going to choose input field for more than one question, then you'll have two input field with the same name, that is not allowed. So, let here also pass the i to the function.
====================
here is the solution for your code.
1: I have removed the numbers from default in radio button.
form.php
<?php
$i = $_POST['i'];
$_SESSION["input_type"][$i] = $_POST["type"];
if ($_SESSION["input_type"][$i] == 1) {
form_multiple($i);
} elseif ($_SESSION["input_type"][$i] == 2) {
form_input($i);
}
function form_multiple($i)
{
?>
<div class="control-group">
<div class="controls">
<textarea class="large m-wrap" placeholder=" Statement " cols="50" rows="3" name="statement<?php echo $i; ?>" style="text-align:center;" id="statement<?php echo $i; ?>"></textarea>
</div>
</div>
<div class="name">
<input name="option<?php echo $i . '1'; ?>" id="option<?php echo $i . '1'; ?>" placeholder="Option 1"
style="width:170px;" type="text"/>
<input name="option<?php echo $i . '2'; ?>" id="option<?php echo $i . '2'; ?>" type="text" style="width:170px;"
placeholder="Option 2"/>
<input name="option<?php echo $i . '3'; ?>" id="option<?php echo $i . '3'; ?>" type="text" style="width:170px;"
placeholder="Option 3"/>
<input name="option<?php echo $i . '4'; ?>" id="option<?php echo $i . '4'; ?>" type="text" style="width:170px;"
placeholder="Option 4"/>
</div>
<div class="control-group">
<div class="controls">
Choose Default Option
<br/>
<label class="radio">
<input type="radio" value="1" name="option<?php echo $i; ?>_default" id="option<?php echo $i . '1'; ?>_default"/>
Option 1
</label>
<br/>
<label class="radio">
<input type="radio" value="2" name="option<?php echo $i; ?>_default" id="option<?php echo $i . '2'; ?>_default"
checked />
Option 2
</label>
<br/>
<label class="radio">
<input type="radio" value="3" name="option<?php echo $i; ?>_default" id="option<?php echo $i . '3' ?>_default"/>
Option 3
</label>
<br/>
<label class="radio">
<input type="radio" value="4" name="option<?php echo $i; ?>_default" id="option<?php echo $i . '4'; ?>_default"/>
Option 4
</label>
</div>
</div>
<?php
}
//end
?>
<?php
function form_input($i)
{
?>
<div class="control-group" id="field" name="field">
<label class="control- label">Answer</label>
<div class="controls">
<input type="text" placeholder="Answer" id="ans" name="ans_<?php echo $i; ?>" class="m-wrap small"/>
</div>
</div><?php
}
?>
=====================================
In the below page I have removed some of the tags to shorten the answer
and I also have commented the form tags, so that you can analyze your errors. These two forms were inside another form tag
I don't know where you have defined $_SESSION["q_inc"] variable. I assume that this variable will have some integer value inside.
main content page
<?php
session_start();
include_once("../Includes/db_connection.php");
//include_once("form.php");
if(isset($_POST['total_q'])){
$_SESSION["q_inc"]=$_POST['total_q'];
}
if (!isset($_SESSION["q_inc"])) {
$_SESSION["q_inc"] = 2;
}
$_SESSION["questNo"] = $_SESSION["q_inc"];
if (!isset($_SESSION["lecturer_id"])) {
header("Location:../login.php");
}
//if($_SERVER['add_q'] == 'POST')
//$counter=0;
if (isset($_POST['add_q'])) {
$_SESSION["q_inc"]++;
}
?>
<!DOCTYPE html>
<!--[if IE 8]>
<html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9]>
<html lang="en" class="ie9"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en"> <!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
<script type="text/javascript" src="../includes/jquery.js"></script>
<meta charset="utf-8"/>
<title>ClassEx</title>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<meta content="" name="description"/>
<meta content="" name="author"/>
<link href="../assets/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>
<link href="../assets/css/metro.css" rel="stylesheet"/>
<link href="../assets/bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet"/>
<link href="../assets/font-awesome/css/font-awesome.css" rel="stylesheet"/>
<link href="../assets/fullcalendar/fullcalendar/bootstrap-fullcalendar.css" rel="stylesheet"/>
<link href="../assets/css/style.css" rel="stylesheet"/>
<link href="../assets/css/style_responsive.css" rel="stylesheet"/>
<link href="../assets/css/style_default.css" rel="stylesheet" id="style_color"/>
<link rel="stylesheet" type="text/css" href="../assets/chosen-bootstrap/chosen/chosen.css"/>
<link rel="stylesheet" type="text/css" href="../assets/uniform/css/uniform.default.css"/>
<link rel="shortcut icon" href="../assets/img/favicon.ico"/>
</head>
<!-- END HEAD -->
<!-- BEGIN BODY -->
<body class="fixed-top">
<!-- BEGIN HEADER -->
<div class="header navbar navbar-inverse navbar-fixed-top">
<!-- BEGIN TOP NAVIGATION BAR -->
<div class="navbar-inner">
<div class="container-fluid">
<!-- BEGIN LOGO -->
<a class="brand" href="#">
<img src="../assets/img/logoclassex.jpg" alt="logo" height="35px" width="35px""/>
</a>
<!-- END LOGO -->
<!-- BEGIN RESPONSIVE MENU TOGGLER -->
<a href="javascript:;" class="btn-navbar collapsed" data-toggle="collapse" data-target=".nav-collapse">
<img src="../assets/img/menu-toggler.png" alt=""/>
</a>
<!-- END RESPONSIVE MENU TOGGLER -->
<!-- BEGIN TOP NAVIGATION MENU -->
<ul class="nav pull-right">
<!-- BEGIN NOTIFICATION DROPDOWN -->
<!-- END NOTIFICATION DROPDOWN -->
<!-- BEGIN INBOX DROPDOWN -->
<!-- END INBOX DROPDOWN -->
<!-- BEGIN TODO DROPDOWN -->
<!-- END TODO DROPDOWN -->
</ul>
<!-- END TOP NAVIGATION MENU -->
</div>
</div>
<!-- END TOP NAVIGATION BAR -->
</div>
<!-- END HEADER -->
<!-- BEGIN CONTAINER -->
<div class="page-container row-fluid">
<!-- BEGIN SIDEBAR -->
<div class="page-sidebar nav-collapse collapse">
<!-- BEGIN SIDEBAR MENU -->
<ul>
<li>
<!-- BEGIN SIDEBAR TOGGLER BUTTON -->
<div class="sidebar-toggler hidden-phone"></div>
<!-- BEGIN SIDEBAR TOGGLER BUTTON -->
</li>
<li class="start ">
<a href="lecturer.php">
<i class="icon-home"></i>
<span class="title">Dashboard</span>
</a>
</li>
<li class="">
<a href="../includes/logout.php">
<i class=" icon-off"></i>
<span class="title">Logout</span>
</a>
</li>
</ul>
<!-- END SIDEBAR MENU -->
</div>
<!-- END SIDEBAR -->
<!-- BEGIN PAGE -->
<div class="page-content">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" >
<input type="hidden" id="session" data="#Request.RequestContext.HttpContext.Session['questNo']" />
<!-- <a class="btn green" type="submit" ><i class="icon-plus" ></i></a> -->
Enter no of question<input name="total_q" type="text" />
<input type="submit" />
<!--<button type="submit" id="add_q" name="add_q" class="btn green"><i class="icon-plus"></i></button>-->
</form>
<form action="storeGame.php" method="POST">
<div class="control-group">
<label class="control-label">Game Name</label>
<div class="controls">
<input type="text" id="game_name" name="game_name" placeholder="Enter Game Name"
class="m-wrap large"/>
</div>
</div>
<!-- BEGIN BORDERED TABLE PORTLET-->
<?php
$q_no = 5;
for ($i = 0; $i < $_SESSION["q_inc"]; $i++) {
$temp = $i;
?>
<div class="portlet box yellow">
<div class="portlet-title">
<h4><i class="icon-coffee"></i>#<?php echo ($temp + 1); ?></h4>
<div class="tools">
</div>
</div>
<div class="portlet-body">
<table class="table table-bordered table-hover">
<div class="control-group">
<label class="control-label"> Add Input</label>
<div class="controls">
<select class="medium m-wrap question_type" data-question-no="<?php echo $i; ?>"
tabindex="1" id="type<?php echo $i; ?>" name="type<?php echo $i; ?>">
<option value="">Input Type</option>
<option value="1">Multiple Choice</option>
<option value="2">Input Field</option>
</select>
</div>
<div id="answer_no_<?php echo $i; ?>"></div>
</div>
</tbody>
</table>
</div>
</div>
<?php
}
?>
<script>
$(document).ready(function () {
$('.question_type').change(function () {
var question_no = $(this).attr('data-question-no');
$.ajax({
url: "form.php",
type: 'post',
data: {
type: $(this).val(),
i: question_no
},
success: function (data) {
$('#answer_no_' + question_no).html(data);
}
});
});
});
</script>
<!-- END BORDERED TABLE PORTLET-->
<!-- BEGIN PAGE CONTAINER-->
<div class="container-fluid">
<!-- BEGIN PAGE CONTENT-->
<div class="row-fluid">
<div class="span12">
<!-- <form action="-->
<?php //echo $_SERVER['PHP_SELF']; ?><!--" method="POST" >-->
<!-- <input type="hidden" id="session" data="#Request.RequestContext.HttpContext.Session['questNo']" />-->
<!-- <button type="submit" id="add_q" name="add_q" class="btn green"><i class="icon-plus"></i></button>-->
<!-- </form>-->
</div>
<!-- END PAGE CONTENT-->
</div>
<!-- END PAGE CONTAINER-->
<button type="submit" class="btn yellow btn-block" id="getGames" name="getGames" class="btn green">
Create Game <i &nbsp class="m-icon-big-swapright m-icon-white"></i></button>
</form>
</div>
</div>
<!-- END PAGE -->
</div>
<!-- END CONTAINER -->
<!-- BEGIN FOOTER -->
<div class="footer">
University of Passau ClassEx Team
<div class="span pull-right">
<span class="go-top"><i class="icon-angle-up"></i></span>
</div>
</div>
<!-- END FOOTER -->
<!-- BEGIN JAVASCRIPTS -->
<!-- Load javascripts at bottom, this will reduce page load time -->
<script src="../assets/js/jquery-1.8.3.min.js"></script>
<script src="../assets/breakpoints/breakpoints.js"></script>
<script src="../assets/jquery-slimscroll/jquery-ui-1.9.2.custom.min.js"></script>
<script src="../assets/bootstrap/js/bootstrap.min.js"></script>
<script src="../assets/js/jquery.blockui.js"></script>
<script src="../assets/js/jquery.cookie.js"></script>
<script src="../assets/fullcalendar/fullcalendar/fullcalendar.min.js"></script>
<script type="text/javascript" src="../assets/uniform/jquery.uniform.min.js"></script>
<script type="text/javascript" src="../assets/chosen-bootstrap/chosen/chosen.jquery.min.js"></script>
<!-- ie8 fixes -->
<!--[if lt IE 9]>
<script src="../assets/js/excanvas.js"></script>
<script src="../assets/js/respond.js"></script>
<![endif]-->
<script src="../assets/js/app.js"></script>
<script>
jQuery(document).ready(function () {
// initiate layout and plugins
App.setPage('calendar');
App.init();
});
</script>
<!-- END JAVASCRIPTS -->
</body>
<!-- END BODY -->
</html>
===============================
There should be only one default option field in the database. Here I have removed all those and added one named "default_option"
storeGame.php
<?php
session_start();
include_once("../Includes/db_connection.php");
$lecturer_id = $_SESSION["lecturer_id"];
$game_name=mysql_real_escape_string($_POST['game_name']);
echo $_SESSION["lecturer_id"];;
echo $game_name;
$sql="insert into games(game_name, lecturer_id) values ('$game_name', '$lecturer_id')";
if(!mysql_query($sql)){
echo "Error in storing into database!<br/>";
}
for($i=0;$i<$_SESSION["q_inc"];$i++)
{
$input_type = mysql_real_escape_string($_POST['type'.$i]);
if($input_type=='1')
{
$question= $_POST['statement'.$i];
$val1= $_POST['option'.$i.'1'];
$val2= $_POST['option'.$i.'2'];
$val3= $_POST['option'.$i.'3'];
$val4= $_POST['option'.$i.'4'];
//Here should be only one default value
$default_option= $_POST['option'.$i.'_default'];
/*$default1= $_POST['option'.$i.'1'.'_default'];
$default2= $_POST['option'.$i.'2'.'_default'];
$default3= $_POST['option'.$i.'3'.'_default'];
$default4= $_POST['option'.$i.'4'.'_default'];*/
$sql=" insert into subgames( game_id, input_id, statement, option1, option2, option3, option4, default_option)
values ( (SELECT id FROM games WHERE game_name = '$game_name' limit 1), '$input_type', '$question', '$val1', '$val2', '$val3', '$val4', '$default_option')";
if(!mysql_query($sql)){
echo "Error";
}
else{
echo "Success";
}
//$error= mysql_error();
}
elseif($input_type=='2')
{
$question= $_POST['quest'];
$answer= $_POST['ans'];
// it is not implemented so leave it
}
}

Related

How to get the success message after clicking on submit button

I have my code where it should show a success message after submitting (click on add) but for some reason this success message is showing all the time even if I don't add anything, it is just showing on the top of the page.the problem is if I removed the message that is below if statement, the message will not show. the action is working fine it is just the success message. Can you please see what is the problem?
Add.php
<?php
include('header.php');
?>
<link rel="stylesheet" href="../../validation/dist/css/bootstrapValidator.css"/>
<script type="text/javascript" src="../../validation/dist/js/bootstrapValidator.js"></script>
<!-- =============================================== -->
<?php
include('../../form.php');
$frm=new formBuilder;
?>
<!-- =============================================== -->
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Add Coming Soon Movie
</h1>
<?php
if(isset($_SESSION['add']))
{?>
<div class="alert alert-success">
<strong>Success!</strong> News added successfully..
</div>
<?php
}?>
<ol class="breadcrumb">
<li><i class="fa fa-home"></i> Home</li>
<li class="active">Add Coming Soon Movie</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<!-- Default box -->
<div class="box">
<div class="box-body">
<form action="process_add_news.php" method="post" enctype="multipart/form-data" id="form1">
<div class="form-group">
<label class="control-label">Movie name</label>
<input type="text" name="name" class="form-control"/>
<?php $frm->validate("name",array("required","label"=>"Movie Name")); // Validating form using form builder written in form.php ?>
</div>
<div class="form-group">
<label class="control-label">Type</label>
<input type="text" name="type" class="form-control">
<?php $frm->validate("type",array("required","label"=>"Type","regexp"=>"text")); // Validating form using form builder written in form.php ?>
</div>
<div class="form-group">
<label class="control-label">Release Date</label>
<input type="date" name="date" class="form-control"/>
<?php $frm->validate("date",array("required","label"=>"Release Date")); // Validating form using form builder written in form.php ?>
</div>
<div class="form-group">
<label class="control-label">Description</label>
<input type="text" name="description" class="form-control">
<?php $frm->validate("description",array("required","label"=>"Description")); // Validating form using form builder written in form.php ?>
</div>
<div class="form-group">
<label class="control-label">Images</label>
<input type="file" name="attachment" class="form-control" placeholder="Images">
<?php $frm->validate("attachment",array("required","label"=>"Image")); // Validating form using form builder written in form.php ?>
</div>
<div class="form-group">
<label class="control-label">Trailer Youtube Link</label>
<input type="text" name="video" class="form-control"/>
<?php $frm->validate("video",array("label"=>"Image","max"=>"500")); // Validating form using form builder written in form.php ?>
</div>
<div class="form-group">
<button class="btn btn-success">Add Movie</button>
</div>
</form>
</div>
<!-- /.box-footer-->
</div>
<!-- /.box -->
</section>
<!-- /.content -->
</div>
<?php
include('footer.php');
?>
<script>
<?php $frm->applyvalidations("form1");?>
</script>
processToAdd.php:
<?php
include('../../config.php');
extract($_POST);
$uploaddir = '../Coming-soon/';
$uploadfile = $uploaddir . basename($_FILES['attachment']['name']);
move_uploaded_file($_FILES['attachment']['tmp_name'],$uploadfile);
$flname="Coming-soon/".basename($_FILES["attachment"]["name"]);
mysqli_query($con,"INSERT INTO tbl_news values (NULL,'$name','$type','$date','$description','$flname','$video')");
$_SESSION['add']=1;
header('location:add_movie_news.php');
?>
I try this and found that, you need to start session
You just need to add session_start();
<?php
session_start();
if(isset($_REQUEST['submit_btn']))
{
$name = $_POST["names"];
$_SESSION['add'] = $name;
print_r($_SESSION);
}
?>
<html>
<head>
</head>
<body>
<?php
if(isset($_SESSION['add'])) {
?>
<div class="">
<strong>Success!</strong> News added successfully..
</div>
<?php
}
?>
<form action="" method="POST">
<input type="text" name="names" id="names">
<input type="submit" value="submit" name="submit_btn">
</form>
<script>
</script>
</body>
</html>
It seems like the issue is the line if(isset($_SESSION['add'])). So as long as $_SESSION['add'] is set the you have to see the message. Its either you unset it immediately after the message and reset it again on each button click or if the button you click is named 'submit', just use
if(isset($_POST['add'])){
//output message here
}
I try your code as example and remove validation and extra things
I also redirect Add.php to processToAdd.php and then again redirect processToAdd.php to Add.php
Please have a look and try this.
Hope this will resolve your problem.
Add.php:
<?php
session_start();
?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Add Coming Soon Movie
</h1>
<?php
if(isset($_SESSION['add'])) {
?>
<div class="alert alert-success">
<strong>Success!</strong> News added successfully..
</div>
<?php
}
?>
</section>
<!-- Main content -->
<section class="content">
<!-- Default box -->
<div class="box">
<div class="box-body">
<form action="processToAdd.php" method="post" enctype="" id="form1">
<div class="form-group">
<label class="control-label">Movie name</label>
<input type="text" name="name" class="form-control"/>
</div>
<div class="form-group">
<button class="btn btn-success" type="submit">Add Movie</button>
</div>
</form>
</div>
<!-- /.box-footer-->
</div>
<!-- /.box -->
</section>
<!-- /.content -->
</div>
processToAdd.php:
<?php
session_start();
extract($_POST);
$_SESSION['add']=1;
header('location:add.php');
?>

Warning: Cannot modify header information - headers already sent by (output started at /home/cabox/workspace/Project/ShoppingCart

Having difficulty identifying what is throwing the error. Have removed all white space. Using CodeAnywhere as my IDE as it is a requirement for me. Any help would be appreciated.
Full error:
Warning: Cannot modify header information - headers already sent by (output started at /home/cabox/workspace/Project/ShoppingCart.php:134) in /home/cabox/workspace/Project/ShoppingCart.php on line 169
Code:
<?php
session_start();
$connect = mysqli_connect("localhost", "root", "", "lab"); //connect to the db
if(isset($_POST["add_to_cart"])) //if the add to cart value is set
{
if(isset($_SESSION["shopping_cart"])) //if the shopping cart session is set
{
$item_array_id = array_column($_SESSION["shopping_cart"], "item_id");
//if there are values in your shopping cart loop through and display them
if(!in_array($_GET["id"], $item_array_id))
{
$count = count($_SESSION["shopping_cart"]);
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["shopping_cart"][$count] = $item_array;
}
else
{
echo '<script>alert("Item Already Added")</script>';
//restriction on design - can only add one instance of each product, delete if you want to add more
}
}
else
{
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["shopping_cart"][0] = $item_array;
}
}
if(isset($_GET["action"]))
{
if($_GET["action"] == "delete")
//when you select 'Remove', delete the values based on id. Alert box will show on completition
{
foreach($_SESSION["shopping_cart"] as $keys => $values)
{
if($values["item_id"] == $_GET["id"])
{
unset($_SESSION["shopping_cart"][$keys]);
echo '<script>alert("Item has been removed from Shopping Cart")</script>';
echo '<script>window.location="ShoppingCart.php"</script>';
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Shopping Cart</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<!-- AJAX is about loading data in the background and display it on the webpage, without reloading the whole page.-->
<link rel="stylesheet" type="text/css" href="thePerfectPair.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script>
// Get the modal
var modal = document.getElementById('id01');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</head>
<body>
<nav class="navigationBar">
<!--Establishing the top left hand side of the Navigation Bar-->
<div class="leftTopNavBar">
€ EUR |
<!--The following produces a pop up sign up form that is validated through javascript functions in the following code.
I implemented this pop up form to create a different design element as opposed to just referring users to another page.
All design element are assigned in the css file and it involved calling many different classes in order not to conflict
with other forms and input boxes contained in the website-->
<button onclick="document.getElementById('id01').style.display='block'" style="width:auto;" class="SignUpBtn0">SIGN UP |</button>
<div id="id01" class="modal">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
<form class="modal-content" action="/action_page.php">
<div class="container1">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account with Perfect Pair!</p>
<hr>
<b>Email</b>
<input type="text" placeholder="Enter Email" name="email" required>
<b>Password</b>
<input type="password" placeholder="Enter Password" name="psw" required>
<b>Repeat Password</b>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<label>
<input type="checkbox" checked="checked" name="remember" style="margin-bottom:15px"> Remember me</label>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</div>
SAVED ITEMS
</div>
<!--Establishing the right side of the navBar-->
<div class="rightTopNavBar">
<input type="search" placeholder="Search..." name="search">
<button type="submit"><i class="fa fa-search"></i></button>
LOGIN | CART
<i class="fa fa-shopping-cart" style="font-size:20px"></i>
</div>
<!--Establishing the middle of the navBar-->
<div class="middleTopNavBar">
<img src="Images/perfectPairLogo.png" class="logoHeader" alt="logo" width="100" height="100">
</div>
<!--Establishing bottom navBar-->
<div class="bottomNavBar">
<i class="fa fa-home" style="font-size:36px"> </i>
 HEELS 
 SANDALS 
 BOOTS 
 TRAINERS 
 FLATS 
 SHOPPING CART </div></nav>
<div class="container">
<br><?php $query="SELECT*FROM tbl_product1 ORDER BY id ASC"; $result=mysqli_query($connect, $query); if(mysqli_num_rows($result)>0){while($row=mysqli_fetch_array($result)){?><div class="col-md-4">
<form method="post" class="phpForm" action="ShoppingCart.php?action=add&id=<?php echo $row["id"];?>" >
<div class="formStyleDiv" style=" background-color:#f1f1f1; border-radius:1px; padding:16px; width:25%;" align="center">
<img src="Images/<?php echo $row["image"];?>" class="img-responsive" style="height: 200px;" />
<h4 class="text-info"><?php echo $row["name"];?></h4><br />
<h4 class="text-danger">€<?php echo $row["price"];?></h4>
<input type="text" name="quantity" value="1" class="form-control" />
<input type="hidden" name="hidden_name" value="<?php echo $row["name"];?>" />
<input type="hidden" name="hidden_price" value="<?php echo $row["price"];?>" />
<input type="submit" name="add_to_cart" style="margin-top:5px;" class="submitBtn" class="btn btn-success" value="Add to Cart" /></div>
</form>
</div><?php
}
}
?><div style="clear:both"></div>
<br />
<h3>Order Details</h3>
<div class="table-responsive" >
<table>
<tr>
<th width="40%" align="left">Item Name</th>
<th width="10%" align="left">Quantity</th>
<th width="20%" align="left">Price</th>
<th width="15%" align="left">Total</th>
<th width="5%" align="left">Action</th>
</tr><?php if(!empty($_SESSION["shopping_cart"])) { $total = 0; foreach($_SESSION["shopping_cart"] as $keys => $values){?><tr>
<td><?php echo $values["item_name"];?></td>
<td><?php echo $values["item_quantity"];?></td>
<td>€<?php echo $values["item_price"];?></td>
<td>€<?php echo number_format($values["item_quantity"] * $values["item_price"], 2);?></td>
<td><span class="text-danger">Remove</span></td>
</tr><?php $total = $total + ($values["item_quantity"] * $values["item_price"]);}?><tr>
<td colspan="3" align="right">Total</td>
<td align="right">€<?php echo number_format($total, 2); ?></td>
<td></td>
</tr><?php $cookie_name="Total"; setcookie($cookie_name, $total, time()+(86400*30),"/");}?></table></div>
<input type="button" class="submitFormBtn" name="submit" value= "Submit" onclick="window.open ('success.php','_self',false)" /><br />
</div>
</div>
<br />
</body>
</html>

Contact form doesn't send predefined values

I'm currently making a form wich works, but it doesn't send predefined values.
I have a few fields that I have predefined such as the user and total amount.
So it does send the values I enter, but not the ones that I have predefined
Can someone please help me, so that this thing can work as it should?
<?php require('includes/config.php');
//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: index.php'); }
?>
<html>
<head>
<title>*****</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!--[if lte IE 8]><script src="siteassets/assets/js/ie/hsiv.js"></script><![endif]-->
<link rel="stylesheet" href="siteassets/assets/css/main.css" />
<!--[if lte IE 8]><link rel="stylesheet" href="siteassets/assets/css/ie8.css" /><![endif]-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#next').keyup(calculate);
$('#nextprice').keyup(calculate);
$('#current').keyup(calculate);
$('#currentprice').keyup(calculate);
});
function calculate(e)
{
$('#total').val($('#next').val() * $('#nextprice').val() + $('#current').val() * $('#currentprice').val());
}
</script>
</head>
<body class="landing">
<div id="page-wrapper">
<!-- Header -->
<header id="header" class="alt">
<nav id="nav">
<ul>
<li>
Menu
<ul>
<li>Current Project</li>
<li>Next Projects</li>
<li>Previous Projects</li>
<li>Who are we?</li>
</ul>
</li>
<li>Tickets</li>
<li><a href='logout.php'>Logout</a></li>
</ul>
</nav>
</header>
<!-- Banner -->
<section id="banner">
<h2>********</h2>
<p>*******</p>
<ul class="actions">
<li>Current Project</li>
<li>Next Projects</li>
<li>Previous Projects</li>
<li>Who are we?</li>
<li>Tickets</li>
</ul>
</section>
<!-- Main -->
<section id="main" class="container 75%">
<div class="box">
<?
if($_SERVER['REQUEST_METHOD']=="POST")
{
if(strlen($_POST['name2']) == 0)
{ $error_msg ="- Please, provide us with your name.<br>"; }
if(!empty($error_msg))
{
//Field error
echo "<b>Your message can't be send due to the following reason:</b><br><br>";
echo $error_msg;
echo "<br>Click on <a href='javascript:history.back(1)'>Go back</a> and provide us with your name.<br><br>";
}
else
{
$recipient = "*********";
$subject = "******";
$header = "From: " . $_POST['uwemail'] . "\n";
$mail_body = "Contact script werd op " . date("d-m-Y") . " om " . date("H:i") . " uur uitgevoerd.\n";
$mail_body .= "De volgende persoon zou graag kaarten bestellen:\n\n";
$mail_body .= "Naam: " . $_POST['name2'] . "\n";
$mail_body .= "Met als kaartnummer: " . $_POST['card2'] . "\n";
$mail_body .= "Aantal kaarten voor de lopende productie: " . $_POST['current2'] . "\n";
$mail_body .= "Aantal kaarten voor de komende productie: " . $_POST['next2'] . "\n";
$mail_body .= "Voor een totaal: " . $_POST['total2'] . "\n";
$mail_body .= "\n\n -- Einde van het contact bericht --";
mail($recipient, $subject, $mail_body, $header);
print "<b>IMPORTANT!</b>";
print "<br><br>Thank you for your reservation.";
print "<br><br>Please note that this will be final upon receipt of payment of the total amount of";
print " POST TOTAAL";
print "EUR to Mazzini Theatre Productions";
print "<br><br>Confirmation of reservation and payment instruction details will be sent to you via email.";
print "<br><br>We are looking forward to meet you.";
}
}
else
{
?>
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="POST" name="contact">
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
Your personal card number
<input type="text" name="card2" id="card" value="<?php echo $_SESSION['username']; ?>" placeholder="Card Number" disabled/>
</div>
<div class="6u 12u(mobilep)">
Please enter your name. (mandatory)
<input type="text" name="name2" id="name" value="" placeholder="Your name" />
</div>
</div>
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
Current Project - Smile
<input type="text" name="current2" id="current" value="" placeholder="How many tickets would you like?" />
</div>
<div class="6u 12u(mobilep)">
Next Project - Sand
<input type="text" name="next2" id="next" value="" placeholder="How many tickets would you like?" />
</div>
</div>
<div class="row uniform 50%">
<div class="6u 12u(mobilep)">
<input type="hidden" id="currentprice" value="10" />
</div>
<div class="6u 12u(mobilep)">
<input type="hidden" id="nextprice" value="10" placeholder="" />
</div>
</div>
<div class="6u 12u(mobile)">
<input name="uwemail" placeholder="Email" type="hidden" value="**THIS WORKS**"/>
</div>
<div class="6u 12u(mobilep)">
Total price.(In EUR)
<input type="text" name="total2" id="total" value="" disabled/>
</div>
</div>
<div class="row uniform">
<div class="12u">
<ul class="actions align-center">
<li><input type="submit" name="submit"value="Place Order"/></li>
</ul>
</div>
</div>
</form>
<?php
}
?>
</div>
</section>
<!-- Footer -->
<footer id="footer">
<ul class="copyright">
<li>© **DISCLAIMER**</li>
</ul>
</footer>
</div>
<!-- Scripts -->
<script src="siteassets/assets/js/jquery.min.js"></script>
<script src="siteassets/assets/js/jquery.dropotron.min.js"></script>
<script src="siteassets/assets/js/jquery.scrollgress.min.js"></script>
<script src="siteassets/assets/js/skel.min.js"></script>
<script src="siteassets/assets/js/util.js"></script>
<!--[if lte IE 8]><script src="siteassets/assets/js/ie/respond.min.js"></script><![endif]-->
<script src="siteassets/assets/js/main.js"></script>
</body>
</html>
For your calculated fields you set attribute disabled. Fields with this attribute are not sent by form. Remove that attribute. You can set in that place readonly attribute
Forms do not send disabled fields. You alternatively can use readonly instead of disabled.
your hidden inputs are missing name= that's why they are not sent

Send data from AJAX function to PHP file

I have an AJAX function that take data form a submit form and should pass varaibles to process.php
index.html is the main page
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>League of Legends Straw Poll</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/styles.css" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h1 class="text-center">Game Straw Poll</h1>
</div>
</div>
<br>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-default">
<div class="panel-body">
<!-- FORM -->
<form name="form" id="form" method="post">
<div class="row">
<div class="col-md-12">
<!-- GAME -->
<select class="form-control" id="game-group" name="game" onchange="ChangeBackground();">
<option selected disabled>Select your Game...</option>
<option value="League_of_Legends">League of Legends</option>
<option value="Heartstone">Hearthstone</option>
</select>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<!-- QUESTION -->
<div class="input-group" id="question-group">
<input type="text" class="form-control" name="question" id="question" placeholder="Start typing your question...">
<span class="input-group-addon">
<i class="glyphicon glyphicon-question-sign"></i>
</span>
</div>
</div>
</div>
<br>
<div class="row">
<!-- OPTIONS -->
<div class="form-group form-group-options col-md-12 col-sm-12 col-xs-12">
<div class="input-group input-group-option col-md-12 col-sm-12 col-xs-12" id="options-group">
<input type="text" name="option[]" id="option" class="form-control" placeholder="Options...">
<span class="input-group-addon input-group-addon-remove">
<span class="glyphicon glyphicon-remove"></span>
</span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<!-- CHOICE -->
<div class="checkbox" id="choice-group">
<label>
<input type="checkbox" id="choice" name="choice" value="Yes">Allow multiple choice
</label>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button type="button" class="btn btn-primary btn-lg pull-left" name="submit_button" id="submit_button" data-toggle="modal" data-target="#myModal">Create Poll</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Poll created</h4>
</div>
<div class="modal-body">
<p>Share it: http://gamepoll.net/<?php echo $rand_value; ?></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>
<button type="button" class="btn btn-primary">Invia</button>
</div>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<script type='text/javascript' src='js/addfield.js'></script>
<script type='text/javascript' src='js/changebackground.js'></script>
<script type='text/javascript' src='magic.js'></script>
</body>
</html>
This is magic.js file
$(document).ready(function()
{
$("#submit_button").click(function()
{
var game = $("#game-group:selected").val();
var question = $("#question").val();
var option = $("#option[]").val();
var choice = $("#choice").val();
if (game == '' || question == '' || option == '' || choice == '')
{
alert("Insertion Failed Some Fields are Blank....!!");
}
else
{
// Returns successful data submission message when the entered information is stored in database.
$.post("process.php", {
game1: game,
question1: question,
option1: option,
choice1: choice
},
function(data)
{
alert(data);
$('#form')[0].reset(); // To reset form fields
});
}
});
});
And this is process.php file
<?php
//Include configuration file
include('includes/config.php');
//Define variables
$game2=$_POST['game'];
$question2=$_POST['question'];
$option2=$_POST['option'];
$choice2=$_POST['choice'];
//Generate random number
$rand_value=rand();
//Create temporary folder
mkdir($rand_value);
//Copy page of Ask Poll
copy('page.php', $rand_value . '/page.php');
rename($rand_value . '/page.php', $rand_value . '/index.php');
//Add data into database
mysql_connect($db_host, $db_username, $db_password) or die ("Errore di connessione!");
mysql_select_db($db_name) or die ("Impossibile selezionare database!");
$sql1="CREATE TABLE `" . $rand_value . "` (Question VARCHAR(200), Options VARCHAR(200), Choice INT(11))";
mysql_query($sql1) or die ("Impossibile eseguire la query!");
//Count number of Options available
$count=count($option);
for ($i=0; $i<($count-1); $i++)
{
${$sql . $i}="INSERT INTO `" . $rand_value . "` (Question, Options, Choice) VALUES ('$question2', '$option2[$i]', '$choice2')";
mysql_query(${$sql . $i});
}
?>
The problem is that the AJAX function doesn't pass data to process.php in fact i don't see any folder into my server or data saved into the database
change
var option = $("#option[]").val();
to
var option = $("#option").val();
you have assign [] operater in id selecter
Your javascript property names dont match your php array keys:
{
game1: game,
question1: question,
option1: option,
choice1: choice
}
$game2=$_POST['game'];
$question2=$_POST['question'];
$option2=$_POST['option'];
$choice2=$_POST['choice'];
change one or the other, eg:
{
game: game,
question: question,
option: option,
choice: choice
}
The only issue I see is when calling the POST vars in your php you need to use the key names from your object. Not the variable names.
//Define variables
$game2=$_POST['game1'];
$question2=$_POST['question1'];
$option2=$_POST['option1'];
$choice2=$_POST['choice1'];
Hope this helps!

Don't refresh page after submit

I have a site http://gamepoll.net and I want that when I click Create Poll, the page doesn't refresh. This is the HTML code:
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>League of Legends Straw Poll</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/styles.css" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h1 class="text-center">Game Straw Poll</h1>
</div>
</div>
<br>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-default">
<div class="panel-body">
<form name="submitForm" id="submitForm" action="" method="post">
<div class="row">
<div class="col-md-12">
<select class="form-control" id="theme" name="game" onchange="ChangeBackground();">
<option selected disabled>Select your Game...</option>
<option value="League_of_Legends">League of Legends</option>
<option value="Heartstone">Hearthstone</option>
</select>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<div class="input-group">
<input type="text" class="form-control" name="question" id="question" placeholder="Start typing your question...">
<span class="input-group-addon">
<i class="glyphicon glyphicon-question-sign"></i>
</span>
</div>
</div>
</div>
<br>
<div class="row">
<div class="form-group form-group-options col-md-12 col-sm-12 col-xs-12">
<div class="input-group input-group-option col-md-12 col-sm-12 col-xs-12">
<input type="text" name="option[]" id="option" class="form-control" placeholder="Options...">
<span class="input-group-addon input-group-addon-remove">
<span class="glyphicon glyphicon-remove"></span>
</span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="checkbox">
<label>
<input type="checkbox" id="choice" name="choice" value="Yes">Allow multiple choice
</label>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button type="submit|button" class="btn btn-primary btn-lg pull-left" name="submit_button" id="submit_button" onclick="SubmitForm();" data-toggle="modal" data-target="#myModal">Create Poll</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Poll created</h4>
</div>
<div class="modal-body">
<p>Share it: http://gamepoll.net/<?php echo $rand_value; ?></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>
<button type="button" class="btn btn-primary">Invia</button>
</div>
</div>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<script type='text/javascript' src='js/addfield.js'></script>
<script type='text/javascript' src='js/changebackground.js'></script>
<script type='text/javascript' src='norefresh.js'></script>
</body>
</html>
JS Code
function SubmitForm(e) {
e.preventDefault();
var game = $("#game").val();
var question = $("#question").val();
var option = $("#option").val();
$.post("submit.php", { game: game, question: question, option: option },
}
submit.php Code
<?php
//Include configuration file
include('includes/config.php');
//Define variables
$question=$_POST['question'];
$game=$_POST['game'];
$option=$_POST['option'];
$choice=$_POST['choice'];
//Generate random number
$rand_value=rand();
//Create temporary folder
mkdir($rand_value);
//Copy page of Ask Poll
copy('page.php', $rand_value . '/page.php');
rename($rand_value . '/page.php', $rand_value . '/index.php');
//Add data into database
mysql_connect($db_host, $db_username, $db_password) or die ("Errore di connessione!");
mysql_select_db($db_name) or die ("Impossibile selezionare database!");
$sql1="CREATE TABLE `" . $rand_value . "` (Question VARCHAR(200), Options VARCHAR(200), Choice INT(11))";
mysql_query($sql1) or die ("Impossibile eseguire la query!");
//Count number of Options available
$count=count($option);
for ($i=0; $i<($count-1); $i++)
{
${$sql . $i}="INSERT INTO `" . $rand_value . "` (Question, Options, Choice) VALUES ('$question', '$option[$i]', '$choice')";
mysql_query(${$sql . $i});
}
?>
All works perfectly but the only problem is that when i click Create Poll button, the browser redirect me to submit.php blank page
UPDATE
This code doesn't work
function SubmitForm(e) {
e.preventDefault();
var game = $("#game").val();
var question = $("#question").val();
var option = $("#option").val();
$.post("submit.php", { game: game, question: question, option: option }
return false;
}
Can you write me an AJAX function as the last comment says?
place return false; at the end of your SubmitForm function and loose the comma at the end of the last sentence
function SubmitForm(e) {
e.preventDefault();
var game = $("#game").val();
var question = $("#question").val();
var option = $("#option").val();
$.post("submit.php", { game: game, question: question, option: option }
return false;
}
Either place return false; at the end of the function SubmitForm or change onclick="SubmitForm();" to onclick="SubmitForm(); return false;"
You can just add onsubmit="return false;" to your form:
<form onsubmit="return false;">
*****
****
</form>
use Ajax function if you want that the page doesn't refresh on click the "Create Poll" button.
It loads the part of the page without refresh the whole page.

Categories

Resources