I want to pop a modal when fname already exist in DB - javascript

Form:
<form class="form-horizontal" data-toggle="validator" method="post" role="form" id="enquiryForm">
<div class="form-group">
<label class="col-lg-2 control-label">Full Name :</label>
<div class="col-lg-8">
<input type="text" name="fname" class="form-control" id="inputFirstName" data-error="Please fill out this field." placeholder="Full Name" required>
<div class="help-block with-errors"></div>
</div>
<button type="button" class="btn btn-info" id="existName">Next</button>
</div>
</form>
AJAX:
$('#existName').click(function(){
var fname = $('#inputFirstName').val();
var datas = "fname="+fname;
console.log(datas);
$.ajax({
url : "exist.php",
data : datas,
method : "POST"
}).done(function(exist){
console.log(exist);
$('#existNameModal').html(exist);
})
})
PHP:
<?php
session_start();
$companydata = $_SESSION['company'];
$idCompany = $companydata['id'];
$fnameCompany = $companydata['fname'];
$lnameCompany = $companydata['lname'];
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Latest compiled and minified CSS -->
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<?php
$dbhost = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "gym";
$conn = mysqli_connect($dbhost, $dbusername, $dbpassword, $dbname) or die ("could not connect");
if($_POST){
$existName = $_POST['fname'];
$sql = "SELECT count(fname) from enquiry where fname = '$existName' AND cmpId = '$idCompany'";
$result = mysqli_query($conn, $sql);
$row = mysqli_num_rows($result);
print_r($row);
/*exit;*/
if(($row)>0) {
$modal = '
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>';
echo $modal;
}
}
?>
</body>
</html>
Modal HTML
<!-- Name exist Modal -->
<div id="existNameModal" class="modal fade" role="dialog">
</div>
I am trying to get this Modal display when count(fname) in DB is more than 0. I tried everything but nothing worked.

From with Modal (form and modal both will be on same page)
<form class="form-horizontal" data-toggle="validator" method="post" role="form" id="enquiryForm">
<div class="form-group">
<label class="col-lg-2 control-label">Full Name :</label>
<div class="col-lg-8">
<input type="text" name="fname" class="form-control" id="inputFirstName" data-error="Please fill out this field." placeholder="Full Name" required>
<div class="help-block with-errors"></div>
</div>
<button type="button" class="btn btn-info" id="existName">Next</button>
</div>
</form>
<div id="myModal" class="modal fade" role="dialog">
<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">Modal Header</h4>
</div>
<div class="modal-body">
<div id="existNameModal"></div> //this is where message will show
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
In Ajax, you are using click function, better do it with change function on input and check the record if exist like
$('#inputFirstName').change(function(){
var fname = $(this).val();
//rest of code
});
The Ajax with click function
$('#existName').click(function(){
var fname = $('#inputFirstName').val();
var datas = "fname="+fname;
console.log(datas);
$.ajax({
url : "exist.php",
data : datas,
method : "POST"
})
});
Now to show modal and message if record exist
.done(function(exist){
console.log(exist);
if(exist.status=='error') {
$('#myModal').modal('show');
$('#existNameModal').html(exist.message);
}
});
The php exist.php
<?php
header('Content-Type: application/json');
$dbhost = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "gym";
$conn = mysqli_connect($dbhost, $dbusername, $dbpassword, $dbname) or die ("could not connect");
if($_POST['fname']){
$existName = $_POST['fname']; //escape the string
$sql = "SELECT count(fname) from enquiry where fname = '$existName' AND cmpId = '$idCompany'";
$result = mysqli_query($conn, $sql);
$row = mysqli_num_rows($result);
//print_r($row);
if(($row)>0) {
$response['status'] = "error";
$response['message'] = "<div class='alert alert-danger'>Record Already Exist</div>";
}
echo json_encode($response);
}
?>

Related

How to avoid page refresh after the alert came for wrong entry in php

<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Captcha Implementation</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" style="width: 600px">
<br/>
<br/>
<div class="panel panel-default">
<div class="panel-body">
<div id="message"></div>
<h4 align="center">Submit the word you see below:</h4>
<p id="captImg" align="center">
<img src="image.php" id="captcha_image"/>
</p>
<!-- <p align="center">Can't read the image? click here to refresh.</p> -->
<form action="index.php" method="post" id="captch_form" name="captch_form">
<div class="form-group">
<label>Enter the Captcha</label>
<input type="text" name="captcha_word" id="captcha_word" class="form-control" placeholder="" value="" autocomplete="off"/>
<div id="message" align="center" class='text-danger'></div>
</div>
<div class="form-group">
<label>Contact Number</label>
<input type="text" name="contact_number" id="contact_number" class="form-control" value="" autocomplete="off"/>
</div>
<div class="form-group" align="center">
<input type="submit" name="submit" id="submit" class="btn btn-info" value="SUBMIT" onclick="captcha_submit()"/>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
<script>
function captcha_submit()
{
var Data = $("#captch_form").serializeArray();
console.log(Data);
$.ajax(
{
url : "action.php?name=captcha_save",
type: "POST",
data : Data,
success:function(data)
{
$('#message').html(data);
}
});
$("#message").slideDown("slow");
e.preventDefault();
}
</script>
<?php
$host = "localhost";
$database = "pmcrb_ambabajaj";
$user = "root";
$password= "";
$db = $database;
$con = mysqli_connect($host,$user,$password,$db);
$Action = #$_GET['name'];
if($Action == 'captcha_save')
{
$captcha_word = #$_POST['captcha_word'];
$contact_number = #$_POST['contact_number'];
$created_date = time();
if($captcha_word == '')
{?>
<div class="alert alert-danger alert-dismissible">
×
Please Enter Captcha.
</div>
<?php }
/*else if($captcha_word == $_SESSION['captcha_code'])
{?>
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong style="color:#fff;text-align:center;font-size:14px;font-family:Times New Roman, Times, serif;margin-left:50px;">Warning!</strong> Invalid Captcha Code
</div>
<?php }*/
else if($contact_number == '')
{?>
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong style="color:#fff;text-align:center;font-size:14px;font-family:Times New Roman, Times, serif;margin-left:50px;">Warning!</strong> Please Enter Contact Number
</div>
<?php }
else
{
$sql = "insert into pm1captcha(`created_date`,`contact_number`,`captcha_word`)values('$created_date','$contact_number','$captcha_word')";
$qry = mysqli_query($con,$sql);
?>
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong style="color:#fff;text-align:center;font-size:14px;font-family:Times New Roman, Times, serif;margin-left:50px;">Success!</strong> Data Saved Successfully
</div>
<?php }
}
?>
I have written some to code to save the captcha details to database table, the data is saving correctly but the page is getting refresh every time if the filed is left empty. How to avoid the page refresh after the alert came every time in php. Can anyone please help me. here i written html code in index.php page and php code is written in action.php page

How to write success message of form in bootstrap modal?

SOLVED
Ok, I solved the problem with AJAX but I had to delete my WordPress because it didn't work with it so later I will upload back by individual directory. Luckily I don't need it for my index. The working code is by CodexWorld. I hope I help someone who is helpless.
I am searching for solution all day but I don't get relevant solution anywhere. Other similar questions here are old, maybe there are fresh solution.
So I am using Bootstrap the first time (files are on the themes of Wordpress). I started to build a contact form in Modal and if I hit submit the window closes, I get the e-mail, but the success-message only shows if I reopen it. I tried every solution I found on internet.
I am not familiar with javascript and jquery, I don't know how to use it.
In the footer I implemented:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
In index there is the form with Modal:
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form class="form-horizontal clearfix" id="contact-form" name="contact" role="form" method="post" action="index.php">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Küldj egy üzenetet</h4>
</div>
<div class="modal-body">
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Itt landol</label>
<div class="col-sm-10">
<input class="form-control" id="disabledInput" type="text" placeholder="hello#kanizsaipatricia.hu" disabled>
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Név</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" placeholder="Minta János" value="<?php echo htmlspecialchars($_POST['name']); ?>">
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" name="email" placeholder="valaki#email.hu" value="<?php echo htmlspecialchars($_POST['email']); ?>">
<?php echo "<p class='text-danger'>$errEmail</p>";?>
</div>
</div>
<div class="form-group">
<label for="message" class="col-sm-2 control-label">Üzenet</label>
<div class="col-sm-10">
<textarea class="form-control" placeholder="Ide írd az üzenetet" rows="4" name="message"><?php echo htmlspecialchars($_POST['message']);?></textarea>
<?php echo "<p class='text-danger'>$errMessage</p>";?>
</div>
</div>
</div>
<?php echo $result; ?>
<div class="modal-footer">
<button type="button" class="btn btn-cancel hvr-fade" data-dismiss="modal">Mégsem</button>
<input type="submit" id="submit" name="submit" data-toggle="modal" data-target="#resultModal" value="Elküldöm" class="btn btn-info hvr-wobble-horizontal">
</div>
</pop:form>
</div>
</div>
The php code behind the form:
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'Üzenetküldő űrlap';
$to = 'hello#kanizsaipatricia.hu';
$subject = 'Új üzenet formon keresztül';
$body = "Feladó: $name\n E-Mail: $email\n Üzenet:\n $message";
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Kérlek, add meg a neved!';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Nem érvényes e-mail cím!';
}
//Check if message has been entered
if (!$_POST['message']) {
$errMessage = 'Nem írtál üzenetet.';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage) {
if (mail ($to, $subject, $body, $from)) {
$result='<div class="alert alert-success noshadow">Elküldve.</div>';
} else {
$result='<div class="alert alert-danger noshadow">Sajnálom, hiba lépett fel az üzenet küldése közben. Próbáld újra!</div>';
}
}
}
I'm open minded for any solution in any language! Please help!
Ok, I solved the problem with ajax but I had to delete my WordPress because it didn't work with it so later I will upload back by individual directory. Luckily I don't need it for my index. Thanks to CodexWorld.
Bootstrap & jQuery Library
Bootstrap is used to create modal popup and design HTMl form, include the bootstrap and jQuery library first.
<!-- Latest minified bootstrap css -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<!-- Latest minified bootstrap js -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
Bootstrap Modal Popup Form
<!-- Button to trigger modal -->
<button class="btn btn-success btn-lg" data-toggle="modal" data-target="#modalForm">
Open Contact Form
</button>
<!-- Modal -->
<div class="modal fade" id="modalForm" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">Contact Form</h4>
</div>
<!-- Modal Body -->
<div class="modal-body">
<p class="statusMsg"></p>
<form role="form">
<div class="form-group">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" placeholder="Enter your name"/>
</div>
<div class="form-group">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="inputEmail" placeholder="Enter your email"/>
</div>
<div class="form-group">
<label for="inputMessage">Message</label>
<textarea class="form-control" id="inputMessage" placeholder="Enter your message"></textarea>
</div>
</form>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary submitBtn" onclick="submitContactForm()">SUBMIT</button>
</div>
</div>
</div>
</div>
JavaScript Code: Validate and Submit Form
<script>
function submitContactForm(){
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var name = $('#inputName').val();
var email = $('#inputEmail').val();
var message = $('#inputMessage').val();
if(name.trim() == '' ){
alert('Please enter your name.');
$('#inputName').focus();
return false;
}else if(email.trim() == '' ){
alert('Please enter your email.');
$('#inputEmail').focus();
return false;
}else if(email.trim() != '' && !reg.test(email)){
alert('Please enter valid email.');
$('#inputEmail').focus();
return false;
}else if(message.trim() == '' ){
alert('Please enter your message.');
$('#inputMessage').focus();
return false;
}else{
$.ajax({
type:'POST',
url:'submit_form.php',
data:'contactFrmSubmit=1&name='+name+'&email='+email+'&message='+message,
beforeSend: function () {
$('.submitBtn').attr("disabled","disabled");
$('.modal-body').css('opacity', '.5');
},
success:function(msg){
if(msg == 'ok'){
$('#inputName').val('');
$('#inputEmail').val('');
$('#inputMessage').val('');
$('.statusMsg').html('<span style="color:green;">Thanks for contacting us, we\'ll get back to you soon.</p>');
}else{
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
$('.submitBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
}
});
}
}
</script>
Send Contact Request Email (submit_form.php)
<?php
if(isset($_POST['contactFrmSubmit']) && !empty($_POST['name']) && !empty($_POST['email']) && (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) && !empty($_POST['message'])){
// Submitted form data
$name = $_POST['name'];
$email = $_POST['email'];
$message= $_POST['message'];
/*
* Send email to admin
*/
$to = 'admin#example.com';
$subject= 'Contact Request Submitted';
$htmlContent = '
<h4>Contact request has submitted at CodexWorld, details are given below.</h4>
<table cellspacing="0" style="width: 300px; height: 200px;">
<tr>
<th>Name:</th><td>'.$name.'</td>
</tr>
<tr style="background-color: #e0e0e0;">
<th>Email:</th><td>'.$email.'</td>
</tr>
<tr>
<th>Message:</th><td>'.$message.'</td>
</tr>
</table>';
// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$headers .= 'From: CodexWorld<sender#example.com>' . "\r\n";
// Send email
if(mail($to,$subject,$htmlContent,$headers)){
$status = 'ok';
}else{
$status = 'err';
}
// Output status
echo $status;die;
}

How to get the specific id from foreach using codeigniter

Just want to ask on how to get the ID in a specific foreach
My Controller
public function validate_subtopic(){
$data = array('success' => false, 'messages' => array());
$this->form_validation->set_rules("subtopicname", "SubTopicName", "trim|required");
$this->form_validation->set_rules("subtopicdescription", "SubTopicDescription", "trim|required");
$this->form_validation->set_error_delimiters('<p class="text-danger">', '</p>');
if($this->form_validation->run()){
$data['success'] = true;
$subtopic_data = array(
'subtopicname' => $this->input->post('subtopicname'),
'subtopicdescript' => $this->input->post('subtopicdescription'),
'subjectID' => $this->input->post('subjectID'),
'topicID' => $this->input->post('topicID'),
);
$this->addtopic_model->insert_subtopic($subtopic_data);
}
else{
foreach ($_POST as $key => $value) {
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
My Model
public function insert_subtopic($subtopic_data){
$this->db->insert('subtopics', $subtopic_data);
}
My view from bootstrap modal
<div class="modal inmodal fade" id="addSubTopic" tabindex="-1" role="dialog" aria-hidden="true">
<?php
$att = array(
'method' => 'POST',
'id' => "form-user_sub");
echo form_open("topicAdd_Controller/validate_subtopic", $att);
?>
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h5 class="modal-title">Please Input SubTopic</h5>
</div>
<div id="the-message"></div>
<div class="modal-body">
<form role="form">
<div class="form-group">
<label>Sub Topic Name</label>
<input class="form-control" name="subtopicname" id="subtopicname" type="text">
</div>
<div class="form-group">
<label>Sub Topic Description</label>
<textarea name="subtopicdescription" id="subtopicdescription" class="form-control">
</textarea>
</div>
<?php foreach($sample as $row){
?>
<?php $index = current($sample); ?>
<input type="text" value="<?php echo $row['topicID']; ?> name="topicID">
<?php } ?>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</div>
<?php form_close();?>
</div>
This is the output of $sample:
The problem is I can't get the ID from the specific foreach loop I choose. how can I solve this?
Please help
You can use while(){} method, so your script will be like this
$i = 0;
$res = array();
while($data = $_POST){
$res[$i] = $data;
$i++;
}
echo json_encode($res);

AJAX POST in same window instead of new

I tried to make a contact form within a bootstrap modal.
An alert should show up right after submitting the form in the modal.
It is working fine on my site which I use for testing.
But when I integrate the code in my main site the alert is shown as text in a new window. Same code. Different response. What could cause this behavior?
HTML:
<div class="container">
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<form id="contact-form" method="post" action="contact.php" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_name">Name</label>
<input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *" data-error="Firstname is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_email">Email</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_message">Message *</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Message for me *" rows="4" required="required" data-error="Please,leave us a message."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-send" value="Send message">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
<!-- /.container-->
PHP:
<?php
// configure
$from = 'noreplay#xy.de';
$sendTo = 'webmaster#xy.de';
$subject = 'New message from contact form';
$fields = array('name' => 'Name', 'email' => 'Email', 'message' => 'Message'); // array variable name => Text to appear in email
$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
$errorMessage = 'There was an error while submitting the form. Please try again later';
// let's do the sending
try
{
$emailText = "You have new message from contact form\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
else {
echo $responseArray['message'];
}
JS:
$(function () {
$('#contact-form').validator();
$('#contact-form').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#contact-form').find('.messages').html(alertBox);
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});
The action parameter in form tag action="contact.php" is forcing the page to refresh try using this as form tag :-
<form id="contact-form">
and change $(this).serialize() in your ajax post code to :-
$('#contact-form').serialize()

PHP Login not working

I have been working on a ban management system for a little bit but I encountered a error with the login system where it does not work
Live example:
http://lotus.pe.hu/lbans/index.php/
username: admin
pass: anmol123
Their is no error or anything with the code from where I can tell if you need the code I will post it
index.php
<html>
<head>
<link rel="stylesheet" href="css/bootstrap.min.css"/>
<title>LotusBans [BETA] [V 1.0] ~ Home</title>
</head>
<body>
<?php
require("api/api.php");
require("header.php");
?>
<div class="jumbotron">
<div class="container">
<h2>LotusBans [BETA] [v1.0]</h2>
<p>View the players banned on the LotusNetwork Here</p>
</div>
</div>
<?php if (isset($_SESSION["username"])) { ?>
<div class="container">
<input type="button" value="+" data-toggle="modal" data-target="#modal" class="btn btn-primary pull-right"/>
<br/><br/>
</div>
<?php } ?>
<div class="container">
<table class="table table-bordered">
<tr>
<th>ID</th>
<th>UUID</th>
<th>Date</th>
<th>Reason</th>
</tr>
<?php
$bans = get_bans();
while ($ban = $bans->fetch_assoc()) {
?>
<tr>
<td><?php echo $ban["id"] ?></td>
<td><?php echo $ban["uuid"] ?></td>
<td><?php echo $ban["date"] ?></td>
<td><?php echo $ban["reason"] ?></td>
</tr>
<?php } ?>
</table>
</div>
<div class="modal fade" id="modal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Add Ban</h4>
</div>
<form id="form">
<div class="modal-body">
<div class="form-group">
<input type="text" id="uuid" name="uuid" placeholder="UUID" class="form-control"/>
</div>
<div class="form-group">
<input type="text" id="reason" name="reason" placeholder="Reason" class="form-control"/>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary"/>
</div>
</form>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$("#form").submit(function(e) {
e.preventDefault();
var uuid = $("#uuid").val();
var reason = $("#reason").val();
$.post("api/add.php", { uuid: uuid, reason: reason }, function(data) {
location.href = "ban.php?id=" + data;
});
});
});
</script>
</body>
header.php
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">LotusBans</a>
</div>
<?php session_start(); if (!isset($_SESSION["username"])) { ?>
<form method="post" action="login.php" class="navbar-form navbar-right">
<div class="form-group">
<input type="text" name="username" placeholder="Username" class="form-control">
<input type="password" name="password" placeholder="Password" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Log In</button>
</form>
<?php } else { ?>
<div class="navbar-right">
<p class="navbar-text">Welcome, <?php echo $_SESSION["username"]; ?></p>
</div>
<?php } ?>
</div><!-- /.container-fluid -->
api.php
<?php
define("key", file_get_contents("http://lotus.pe.hu/lbans/can'tenterthis as this is a key"));
function get_mysql() {
$mysql = new mysqli("", "", "", "");
if ($mysql->connect_error) {
die($mysql->connect_error);
}
return $mysql;
}
function add($uuid, $reason) {
$date = date("Y-m-d H:i:s");
get_mysql()->query("insert into bans (uuid, date, reason) values ('$uuid', '$date', '$reason')");
return get_mysql()->query("select id from bans where uuid = '$uuid' and date = '$date' and reason = '$reason'")->fetch_assoc()["id"];
}
function update($id, $uuid, $reason) {
get_mysql()->query("update bans set uuid = '$uuid', reason = '$reason' where id = $id");
}
function remove($uuid) {
get_mysql()->query("delete from bans where uuid = '$uuid'");
}
function remove_by_id($id) {
get_mysql()->query("delete from bans where id = $id");
}
function get($uuid) {
return get_mysql()->query("select * from bans where uuid = '$uuid'")->fetch_assoc();
}
function get_by_id($id) {
return get_mysql()->query("select * from bans where id = $id")->fetch_assoc();
}
function get_bans() {
return get_mysql()->query("select * from bans");
}
function login($username, $password) {
$password = hash("sha256", $password);
return get_mysql()->query("select count(*) from users where username = '$username' and password = '$password'")->fetch_assoc()["count(*)"] > 0;
}
function register($username, $password) {
$password = hash("sha256", $password);
get_mysql()->query("insert into users (username, password) values ('$username', '$password')");
}
?>
Try to add this to this..
<?php
session_start(); //Transfer the session_start() here ..
require("api/api.php");
if( isset($_POST['username']) )
{
if( login( $_POST['username'], $_POST['password'] ) )
{
$_SESSION['username'] = $_POST['username'];
}
else
{
echo 'Invalid username/password';
}
}
require("header.php");
?>

Categories

Resources