Please check my code and tell me how to make it when click submits button, it goes to a dashboard page. but it does not work. Help.. I think functions not working. I can't figure out what is the problem. I already create my database and I added details in that database.
(I add database and) I will attach GitHub link too. Please check if you have time.
https://github.com/Dushan26/my_assignment.git
<?php
$host="localhost";
$user="root";
$password="";
$db="project_db";
$connect_error = 'Sorry, we\'re experiencing connection issues.';
$con=mysqli_connect($host,$user,$password);
mysqli_select_db($con, 'project_db') or die(mysqli_error($con));
if(isset($_POST['username'])){
$uname=$_POST['txtUsername'];
$password=$_POST['txtPassword'];
$sql="select * from user where email='".$uname."'AND password='".$password."' limit 1";
$result=mysql_query($sql);
if(mysql_num_rows($result)==1){
echo " You Have Successfully Logged in";
exit();
}
else{
echo " You Have Entered Incorrect Password";
exit();
}
}
?>
<html>
<head>
<title>Online class</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" integrity="sha384-y3tfxAZXuh4HwSYylfB+J125MxIs6mR5FOHamPBG064zB+AFeWH94NdvaCBm8qnd" crossorigin="anonymous">
<style>
body{
width: 100%;
height: 400px;
background-image:url(../assets/img/online-class.png);
background-size: cover;
}</style>
</head>
<body>
<div class="container">
<div class="row"><!--row 01-->
<div class="col-sm-9 col-md-7 col-lg-5 mx-auto"><!--row 02-->
<div class="card my-5"> <!-- card-->
<div class="card-body"><!--card body-->
<h5 class="text-center my-2"><b>:::LOGIN:::</h5></b><br>
<form class="form" action="" role="form" method="POST">
<div clss="my-5" id="divEmail"><!--txtusername-->
<input type="text" id="email" name="txtUsername" class="form-control" placeholder="Enter Email">
</div><!--end oftxtusername--><br>
<div clss="my-5" id="divPassword"><!-- password-->
<input type="password" id="password" name="txtPassword" class="form-control" placeholder="Enter Password">
</div><!--end of password--><br>
<div clss="my-4"><!-- button-->
<button type="submit" id="btnSubmit" class="btn btn-danger btn-block text-uppercase col-12">Submit</button>
</div><!--end of button-->
<hr class="my-4"><h6>Enter Your Email & Password</h6>
</form><!--end of form-->
</div><!--end of card body-->
</div><!--end of card-->
</div><!--end row 02-->
</div><!--end of row 01-->
</div><!--end of container-->
I think your submit button is a type of a "submit". when it is inside a form and clicked, by default it submit the form regardless of your click function.
you can change the button type to "button" or change the click function to stop the form submit
$("form").submit(function (e) {
e.preventDefault();
// your code here
});
Related
I am making a site for my website and was wondering how to open the modal that the form is in after I submit the form. I am looking for it to open after I hit the submit button so I can see the errors that are put under the inputs or to show that it sent. I have tried to put the javascript inside the result if or else tag and it wont open the modal and just submits the form or presents the errors but you can't see them until you open the modal. So I was wondering how to open it backup after you submit it.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="FiveM roleplay server, with custom vehicles and scripts. Join today!">
<meta name="Keywords" content="aclfx, aclfxserver, fivem, fivem server, roleplay, gtav roleplay, gta v roleplay, fivem roleplay, fivem roleplay server, fort myers roleplay, fmrp, FMRP, fort myers rp">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="../fmrp_test/styles/animate.css" rel="stylesheet" type="text/css">
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel="stylesheet" href="https://unpkg.com/simplebar#latest/dist/simplebar.css" />
<script src="https://unpkg.com/simplebar#latest/dist/simplebar.js"></script>
<link href="https://fonts.googleapis.com/css?family=Overpass" rel="stylesheet">
<link href="../fmrp_test/styles/extra.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet">
<title>FMRP | Applications</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="../fmrp_test/index.html">FMRP</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse ml-auto" id="navbarNav">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="https://www.fortmyersrp.net/forum/">Forums</a>
</li>
<li class="nav-item">
<a class="nav-link" href="../fmrp_test/help.php">Help</a>
</li>
<li class="nav-item active">
<a class="nav-link" href="../fmrp_test/applications_menu.php">Applications <span class="sr-only">(current)</span></a>
</li>
</ul>
</div>
</div>
</nav>
<br><br>
<div class="container">
<p>
<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
Button with data-target
</button>
</p>
<div class="collapse" id="collapseExample">
<div class="card card-body">
<h1 class="title text-center" id="staff">Staff Member Application (Moderator):</h1>
<?php
if (isset($_POST["submit"])) {
$fullname = $_POST['fullname'];
$age = $_POST['age'];
$discord = $_POST['discord'];
$timezone = $_POST['timezone'];
$roleplaydescription = $_POST['roleplaydescription'];
$experence = $_POST['experence'];
$to = 'blakecharlie239#gmail.com';
$subject = 'Staff Form';
$body = "From: $fullname\n Age: $age\n Discord: $discord\n Timezone: $timezone\n How long have you roleplayed: $roleplaydescription\n Past staff experience: $experence";
// Check if name has been entered
if (!$_POST['fullname']) {
$errName = 'Please enter your full name.';
}
// Check if email has been entered and is valid
//Check if message has been entered
if (!$_POST['age']) {
$errage = 'Please enter your age.';
}
if (!$_POST['discord']) {
$errdiscord = 'Please enter your discord tag.';
}
if (!$_POST['timezone']) {
$errtimezone = 'Please enter your timezone.';
}
if (!$_POST['roleplaydescription']) {
$errroleplaydescription = 'Please enter if you have roleplayed before.';
}
if (!$_POST['experence']) {
$errexperence = 'Please enter your level of staff experience.';
}
// If there are no errors, send the email
if (!$errName && !$errage && !$errdiscord && !$errtimezone && !$errroleplaydescription && !$errexperence) {
if (mail ($to, $subject, $body)) {
$result='<div class="alert alert-success">Thank you for the application! Please allow 4-36 hours from the time of submission for a response. Please do not resubmit an application if we do not respond within that timeframe; we may have other priorities.</div>';
} else {
$result='<div class="alert alert-danger">We are sorry, but there was an error sending your message; please try again. If the error keeps occurring, please pm Spartan78942#0877 on discord for help resolving this.</div>';
} echo "<script>
$('.collapse').css('display', 'show !important');
</script>";
}
}
?>
<?php echo "<p class='text-danger'>$result</p>";?>
<div class="row">
<div class="col-md-12 col-lg-12"> <form action="applications_menu.php" method="post">
<div class="form-group">
<label for="exampleInputEmail1">First & last name:</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter your first & last name here." name="fullname">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Age (MIN 16):</label>
<input type="number" class="form-control" id="exampleInputPassword1" placeholder="Enter your age here." name="age">
<?php echo "<p class='text-danger'>$errage</p>";?>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Discord:</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter your discord tag here. Should look like this: [name]#[4 digits] Ex: aclfx#8109" name="discord">
<?php echo "<p class='text-danger'>$errdiscord</p>";?>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Timezone:</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter your timezone here." name="timezone">
<?php echo "<p class='text-danger'>$errtimezone</p>";?>
</div>
<div class="form-group">
<label for="exampleInputEmail1">How long have you roleplayed?:</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter how long have you been roleplaying." name="roleplaydescription">
<?php echo "<p class='text-danger'>$errroleplaydescription</p>";?>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Past staff experience:</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter and describe your past staff experience." name="experence">
<?php echo "<p class='text-danger'>$errexperence</p>";?>
</div>
<br>
<div class="row"><div class="col-lg-12"><button type="submit" name="submit" value="send" class="subbut btn btn-primary mx-auto d-block" style="width: 190px !important;height: 60px !important;font-size: 25px;">Submit</button></div></div></form>
</div>
</div></div>
</div>
</div>
</div>
</body>
</html>
Just add the following code before closing your body tag
It checks if form submitted and if its submitted it adds a javascript code which triggers collapse which shows your form response or errors.
<?php if(isset($_POST['submit'])){
?>
<script type="text/javascript">
jQuery('#collapseExample').collapse({
toggle:true
})
</script>
<?php
}?>
First, your javascript is targeting multiple elements since you use collapse in the navbar too. You need to target #collapseExample instead.
Second, you have to add the show class to the element, not set its display property.
So the proper js is:
$('#collapseExample').addClass('show');
You also have the script inside the "no errors" condition, so it won't run.
And you can do this in php if you want. Move your error checking before the form and if there's any error set a variable.
<?php
if ($errName || $errage) // Boilerplate to set the error
$error = true;
?>
<div class="collapse<?= $error ? ' show' : '' ?>" id="collapseExample">
Hope this is what you are looking for, since I can find no modal in your code.
This question already has answers here:
jQuery AJAX submit form
(20 answers)
Closed 4 years ago.
I created a contact page.
When I click on the submit button, this form sends my form information to the server-side file (PHP), but the submit button does nothing.
I do not get an answer in the AJAX!
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function() {
$('#submit').attr('value', 'Please wait...');
$.post("sender.php", $("#contactform").serialize(), function(response) {
$('#success').html(response);
$('#submit').attr('value', 'SEND');
});
return false;
});
});
</script>
<!doctype html>
<html>
<head>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<link href="styles/contactform-style.css" rel="stylesheet" id="contact-from-style" >
<meta charset="utf-8">
<title>My Contact form</title>
</head>
<body>
<section id="contact">
<div class="container prop">
<!-- <div class="well well-sm">
<h3><strong>Contact us Pars Coders </strong></h3>
</div>-->
<div class="row" id="p">
<div class="col-md-7">
<img src="img/email-icon.png" class="img-responsive text-center" alt="Pars Codres" />
</div>
<div class="col-md-5">
<h4><strong>Tmas Ba ma </strong></h4>
<form id="#contactform">
<div class="form-group">
<input type="text" class="form-control" name="name" value="" placeholder="Name">
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" value="" placeholder="E-mail">
</div>
<div class="form-group">
<textarea class="form-control" name="description" rows="3" placeholder="Description"></textarea>
</div>
<button class="btn btn-success" type="submit" name="button" id="submit">
<i class="fa fa-paper-plane-o" aria-hidden="true"></i> Send ...
</button>
<div id="success" style="color: red;">؟</div>
</form>
</div>
</div>
</div>
</section>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
</body>
</html>
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['description'];
$to = 's3dhossein#gmail.com';
$subject = 'the subject';
$message = 'FROM: '.$name.' Email: '.$email.'Message: '.$message;
$headers = 'From: s3dhossein#gmail.com' . "\r\n";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) { // this line checks that we have a valid email address
mail($to, $subject, $message, $headers); //This method sends the mail.
echo "Your email was sent!"; // success message
}else{ echo "Invalid Email, please provide an correct email.";
}
?>
Where do you think the problem is?
Can an error come from AJAX?
Found problems:
1) An error is raised: Error: Bootstrap's JavaScript requires jQuery. It means that the bootstrap's js file must be loaded after the jQuery's js file. So invert their positions:
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
2) An error is raised: ReferenceError: $ is not defined for the line $(document).ready(function () {. This means that the jquery is not recognized inside your script. So bring all the js imports in the page head. The times for the js imports at the bottom of the page are long gone.
3) The form tag must be <form id="contactform">, not <form id="#contactform">.
4) If you are submitting through an ajax request, then you must use a button of type "button", not of type "submit". Then you can remove the return false; from the $('#submit').click(function (){...} function too.
Suggestions:
Define an "error" callback for the ajax request.
Define the meta tags as the first ones in the head tags.
Working code:
<!doctype html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>My Contact form</title>
<!-- CSS resources -->
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<link href="styles/contactform-style.css" rel="stylesheet" id="contact-from-style" >
<!-- JS resources -->
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#submit').click(function () {
$('#submit').attr('value', 'Please wait...');
$.post("sender.php", $("#contactform").serialize(), function (response) {
$('#success').html(response);
$('#submit').attr('value', 'SEND');
});
});
});
</script>
</head>
<body>
<section id="contact">
<div class="container prop">
<!-- <div class="well well-sm">
<h3><strong>Contact us Pars Coders </strong></h3>
</div>-->
<div class="row" id="p">
<div class="col-md-7">
<img src="img/email-icon.png" class="img-responsive text-center" alt="Pars Codres" />
</div>
<div class="col-md-5">
<h4><strong>Tmas Ba ma </strong></h4>
<form id="contactform">
<div class="form-group">
<input type="text" class="form-control" name="name" value="" placeholder="Name">
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" value="" placeholder="E-mail">
</div>
<div class="form-group">
<textarea class="form-control" name="description" rows="3" placeholder="Description"></textarea>
</div>
<button class="btn btn-success" type="button" name="button" id="submit">
<i class="fa fa-paper-plane-o" aria-hidden="true"></i> Send ...
</button>
<div id="success" style="color: red;">؟</div>
</form>
</div>
</div>
</div>
</section>
</body>
</html>
I made a login system using Parse.com as a back end and for the life of me I can't figure out why this will not work with the code I have. When the user enters their UserID and password it is supposed to check the parse database and, if found, log them in based upon which role they have. (Send them to menu1, menu2, or menu3 basically). If it can't find them it is supposed to create an alert saying "Username of Password Incorrect" and clear the form.
If you click on the 'Sign In' button as of now it doesn't do anything
The create_account.html successully registers a User in the Parse database with a username and password so I know it connects....I just can't log them in.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--Bootstrap-->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!--Parse-->
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-latest.js"></script>
<script src="//www.parsecdn.com/js/parse-1.6.7.min.js"></script>
<!--Javascript-->
<!--Stylesheet-->
<link rel="stylesheet" type="text/css" href="css/login.css">
<title>index.html</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-12">
<h1>Study App</h1>
<h2>Please Sign In</h2>
<form class="form-signin">
<div class="form-group">
<input type="text" class="form-control" id="userID" placeholder="User ID">
</div> <!--end User ID-->
<div class="form-group">
<input type="password" class="form-control" id="password" placeholder="Password">
</div> <!--end Password-->
Forgot Password? <!--Not implemented yet-->
<button type="button" class="btn btn-lg btn-block btn-primary">Sign In</button>
</form> <!--end SIGN IN FORM-->
</div> <!--END COLUMN-->
</div> <!--END ROW-->
<div class="row">
<div class="col-xs-12">
<div id="add_User">
<img src="img/add_user.png" alt="Add User Icon" height="42" width="42">
<p>Create Account</p>
</div>
</div> <!--END COLUMN-->
</div> <!--END ROW-->
</div> <!--end container-->
<script src="js/login.js"></script>
</body>
</html>
login.js
$(function()
{
Parse.$ = jQuery;
Parse.initialize("x", "y"); <!--Removed for security-->
});
$('.form-signin').on('submit', function(e)
{
e.preventDefault();
var data = $(this).serializeArray(),userID = data[0].value,password = data[1].value;
Parse.User.logIn(username, password, {
success: function (user) {
var queryRole = new Parse.Query(Parse.Role);
if(queryRole.equalTo('name', 'Student')) {
window.location = "menu1.html"
}
else if (queryRole.equalTo('name', 'Tutor')) {
window.location = "menu2.html"
}
else {
window.location = "professor/professor-menu3.html"
}
},
// If there is an error
error: function (user, error) {
console.log(error);
alert("Username or Password incorrect");
$(".form-signin")[0].reset();
}
});
});
You set userID and password:
var data = $(this).serializeArray(),userID = data[0].value,password = data[1].value;
then you use username and password:
Parse.User.logIn(username, password, {
Also, the way you get the userID and passwordseems a bit dangerous to me, if you ever add other fields in your form before those it'll break.
I would recommend you to switch to:
var username = $('#userID').val();
var password = $('#password').val();
instead.
Also, you don't have a submit button in your form. Change:
<button type="button" class="btn btn-lg btn-block btn-primary">Sign In</button>
to:
<button type="submit" class="btn btn-lg btn-block btn-primary">Sign In</button>
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!
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.