I want to try no fresh my login after the user insert their username & password. I'm using on submit on form field like this to returning the same function without be refreshing. onsubmit="return login();
view
<?php $this->load->view('header');?>
<body>
<nav class="navbar navbar-default">
<div class="navbar-header">
Store
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<div class="panel panel-default login">
<div class="panel-heading">Sign In</div>
<div class="panel-body">
<form data-toggle="validator" role="form" method="POST" onsubmit="return login();">
<div class="form-group">
<label for="username">Username</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" class="form-control" name="username" id="username" placeholder="Username" required>
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-star"></span></span>
<input type="password" class="form-control" id="password" placeholder="Password" required>
</div>
</div>
<div class="alert alert-danger text-center" style="display:none;" id="error">
<p>Invalid username or password !!</p>
</div>
<button type="submit" class="btn btn-lg btn-success btn-block" id="login"><span class="glyphicon glyphicon-lock frm-general"></span>Login</button>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="<?=base_url('assets/js/jQuery-2.1.4.min.js');?>"></script>
<script src="<?=base_url('assets/js/bootstrap.min.js');?>"></script>
<script src="<?=base_url('assets/js/validator.min.js');?>"></script>
<script src="<?=base_url('assets/js/view/login.js')?>"></script>
</body>
</html>
Ajax
$(function(){
$('#login').submit(function(e){
var username = $('#username').val();
var password = $('#password').val();
URL_GET_ACCESS = BASE_URL+"Login_controller/login";
$.ajax({
url: URL_GET_ACCESS,
type: 'POST',
data: 'username='+username+'&password='+password;
}).done(function(ans){
console.log(resp);
if(ans === '0'){
$('#error').show().delay(2000).fadeOut();
}else if(ans === '1'){
window.location.href='<?php echo base_url() ?>home/';
}else{
window.location.href='<?php echo base_url() ?>home/';
}
});
});
return false;
});
I assume the problem is that the submission is being triggered and is taking you to the URL defined by your form action (in this case to itself). To prevent this try using jQuery's e.preventDefault(); as soon as you start your submit function.
Another solution I often use is not using a submit button but instead just a span (<span id='iWillSubmit' class='iLookLikeAButton'>) styled as a button and then attach the submit function to a .on('click') on that span element.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a booking form and I successfully connected my database to my website. When I go to my database in MYSQL to see the data I inserted, all fields are in zeros. I tried changing my type of my data fields in the database but it didn't work.
My website connection with the MYSQL database:
<?php
$conexao=mysqli_connect("localhost", "root", "", "sitepap2");
?>
Code to sends the data inserted in the form to the database and to check if there's already a similar record in the database:
<?php
include("conecta.php");
$pnome=$_POST['pnome'];
$numerotmv=$_POST['numerotmv'];
$localsessao=$_POST['localsessao'];
$data=$_POST['data'];
$hora=$_POST['hora'];
$pesquisaUsuario = mysqli_num_rows(mysqli_query($conexao,"
SELECT nome FROM agendamento
WHERE numerotmv = '$numerotmv'
"));
if($pesquisaUsuario >0){
echo 1;
}else{
mysqli_query($conexao, "
insert into agendamento
(pnome, numerotmv, localsessao, data, hora)
values
('$pnome','$numerotmv', '$localsessao','$data','$hora')
");
echo 0;
}
?>
My index file where the form is displayed:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PHP form</title>
</head>
<body>
<div class="modal fade" id="calendario" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-body">
<!-- Registro -->
<form name="calendario" id="calendario" method="post" class="form-horizontal">
<div>
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="text-uppercase align-self-end text-center">Agendamento</h2>
<hr class="divider">
</div>
<div class="form-group">
<label class="control-label col-xs-4">Primeiro Nome</label>
<div class="col-xs-8">
<input type="text" class="form-control" name="pnome" required="required">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-4">Número de telemóvel</label>
<div class="col-xs-8">
<input type="text" class="form-control" name="numerotmv" required="required">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-4">Local da Sessão</label>
<div class="col-xs-8">
<input type="text" class="form-control" name="localsessao" required="required">
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input class="form-control" name="data" type="date" required>
<span class="form-label">Data</span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input class="form-control" name="hora" type="time" required>
<span class="form-label">Hora</span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-8 col-xs-offset-4">
<button type="submit" onClick="verificarAgendamento()" class="btn btn-primary btn-lg">Agendar</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
function verificarAgendamento(){
event.preventDefault();
$.ajax({
type: "POST",
url: "agendamento.php",
data: $("#calendario").serialize(),
success: function(resultado){
if(resultado==0){
alert("Booking made with success");
}else{
alert("error");
}
return false;
}
});
$('#calendario')[0].reset();
return false;
}
</script>
</body>
</html>
My database structure:
database
What happens when I try to insert data through my PHP form in the database:
problem
Thank to all the people that spent time reading this post to help me. I'm grateful.
You have two id's called calendario. The form and the div. So your ajax request is serializing the div, not the form.
Change one of the ids to a unique value and it will work e.g.:
NOTE: If you change the id of your form you need to change it in your ajax call as well
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PHP form</title>
</head>
<body>
<div class="modal fade" id="calendario" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-body">
<!-- Registro -->
<form name="calendario" id="calendario-form" method="post" class="form-horizontal">
<div>
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="text-uppercase align-self-end text-center">Agendamento</h2>
<hr class="divider">
</div>
<div class="form-group">
<label class="control-label col-xs-4">Primeiro Nome</label>
<div class="col-xs-8">
<input type="text" class="form-control" name="pnome" required="required">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-4">Número de telemóvel</label>
<div class="col-xs-8">
<input type="text" class="form-control" name="numerotmv" required="required">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-4">Local da Sessão</label>
<div class="col-xs-8">
<input type="text" class="form-control" name="localsessao" required="required">
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input class="form-control" name="data" type="date" required>
<span class="form-label">Data</span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input class="form-control" name="hora" type="time" required>
<span class="form-label">Hora</span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-8 col-xs-offset-4">
<button type="submit" onClick="verificarAgendamento()" class="btn btn-primary btn-lg">Agendar</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
function verificarAgendamento(){
event.preventDefault();
$.ajax({
type: "POST",
url: "agendamento.php",
data: $("#calendario-form").serialize(),
success: function(resultado){
if(resultado==0){
alert("Booking made with success");
}else{
alert("error");
}
return false;
}
});
$('#calendario')[0].reset();
return false;
}
</script>
</body>
</html>
When im doing a ajax call to the update.php from profiles.php it go a blank page update.php but it does make the changes if i go back to the profile.php
idk what im doing wrong what im missing??
profile.php
<?php include_once("includes/config.php");
if (isset($_GET['id']))
{
$Nome = $_GET['id'];
$sql = "SELECT * FROM utilizadores WHERE id='$Nome'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
if($row = $result->fetch_assoc()) {
echo'
<br>
<form action="update.php" method="post" id="go" class="go" accept-charset="utf-8">
<div class="content" >
<div class="container-fluid">
div class="row">
<div class="col-md-8">
<div class="card">
<div class="header">
<h4 class="title">Perfil do paciente</h4>
</div>
<div class="content">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Nome</label>
<input type="text" class="form-control" disabled placeholder="Nome" value="'.$row["Nome"].'">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Apelido</label>
input type="text" class="form-control" disabled placeholder="Apelido" value="'.$row["Apelido"].'">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input type="email" class="form-control" name="Email "disabled placeholder="Email" value="'.$row["Email"].'">
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Idade</label>
<input type="text" class="form-control" disabled placeholder="Idade" value="'.$row["Idade"].'">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Sexo</label>
<input type="text" class="form-control" disabled placeholder="Sexo" value="'.$row["Sexo"].'">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Telefone</label>
<input type="text" class="form-control" disabled placeholder="Telefone" value="'.$row["Telefone"].'">
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label>Peso</label>
<input type="text" class="form-control" disabled placeholder="Peso" value="'.$row["Peso"].'Kg">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Altura</label>
<input type="text" class="form-control" disabled placeholder="Altura" value="'.$row["Altura"].'Cm">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Perimetro Abdominal</label>
<input type="text" class="form-control" disabled placeholder="Perimetro abdominal" value="'.$row["Perimetro_abdominal"].'Cm">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Perimetro Anca </label>
<input type="text" class="form-control" disabled placeholder="Perimetro Anca" value="'.$row["Perimetro_anca"].'Cm">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Medicação:</label>
<textarea rows="3" class="form-control" name="Medicacao" placeholder="Medicação" id="Medicacao">'.$row["Medicacao"].'</textarea>
</div>
<input type=hidden name=hidden value="'.$row["id"].' ">
<input type="submit" name="med" class="btn btn-info btn-fill pull-right" value="Atualizar" id="med"></div>
<div class="col-md-6">
<div class="form-group">
<label>Observações:</label>
<textarea rows="3" name="Obs" class="form-control" placeholder="Anotar observações" id="Obs">'.$row["Obs"].' </textarea>
</div>
<input type="submit" name="obs" class="btn btn-info btn-fill pull-right" value="Atualizar">
</div>
</div></form>';
}
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($conn);
?>
<script type="text/javascript">
$( "#med" ).click(function() {
$.ajax({
type: "POST",
url: "update.php",
success: function(){
alertify.success('campo atualizado com sucesso');
}
});
});
</script>
update.php
include_once("includes/config.php");
if(isset($_POST['med'])) {
$UpdateQuery = "UPDATE utilizadores SET Medicacao='$_POST[Medicacao]' WHERE id='$_POST[hidden]' ";
$res = mysqli_query($conn,$UpdateQuery);
if($res == 1)
{
//header('Location: ' . $_SERVER['HTTP_REFERER'],true, 301 );
}
?>
You are not cancelling the default submit event of your submit button when you handle the click event. That causes the form to be submitted in the normal way as well by going to the url that is set in the action attribute of the form.
Apart from that, you also need to add the data to the ajax request.
This:
$( "#med" ).click(function() {
$.ajax({
type: "POST",
url: "update.php",
success: function(){
alertify.success('campo atualizado com sucesso');
}
});
});
should be:
$( "#med" ).click(function(event) {
// cancel default submit event
event.preventDefault();
$.ajax({
type: "POST",
// add data
data: $('form#go').serialize(),
url: "update.php",
success: function(){
// Do whatever you need to here
console.log('campo atualizado com sucesso');
}
});
});
Good afternoon, I have a web project, ready, and the form validated with ajax and jquery, have also a PHP function where sending all data on my form, and I have to rest a modal window boostratp, activated by clicking on the submit, the problem is that jquery is blocking the passage of the form to php and is not sending only shows the modal. I guess I activate the jquery from php, but not exactly how to do it
this my form:
// What to do on submit - example of success message
// -------------------------------------------------
submitHandler: function(form) {
$('#successForm').modal('show');
return false;
}
});
// Reset the contact form when success message shown as bootstrap modal is dismissed
// ---------------------------------------------------------------------------------
$('#successForm').on('hidden.bs.modal', function() {
$('#contactForm').trigger("reset");
$('#contactForm .form-group').find('.glyphicon').removeClass('glyphicon-ok');
});
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="js/js-theme/jquery-1.11.3.js"></script>
<!-- Include all plugins (below), or include individual files as needed -->
<script src="js/js-bootstrap/affix.js"></script>
<script src="js/js-bootstrap/alert.js"></script>
<script src="js/js-bootstrap/button.js"></script>
<script src="js/js-bootstrap/carousel.js"></script>
<script src="js/js-bootstrap/collapse.js"></script>
<script src="js/js-bootstrap/dropdown.js"></script>
<script src="js/js-bootstrap/modal.js"></script>
<form id="contactForm" name="contactForm" action="enviar.php" method="post" enctype="multipart/form-data" target="_top">
<div class="col-lg-6">
<div class="form-group has-feedback wow flipInX" data-wow-duration="600ms">
<label for="nombre">Nombre*</label>
<input id="nombre" class="form-control input-lg" type="text" name="nombre" value="" placeholder="" aria-label="nombre" />
<span id="nombre1" class="glyphicon form-control-feedback"></span>
</div>
<!-- end .form-group -->
<div class="form-group wow flipInX" data-wow-duration="900ms">
<label for="celular">Celular</label>
<input id="celular" class="form-control input-lg" type="text" name="celular" value="" placeholder="" aria-label="celular" />
</div>
<!-- end .form-group -->
<div class="form-group has-feedback wow flipInX" data-wow-duration="800ms">
<label for="email">Email*</label>
<input id="email" class="form-control input-lg" type="email" name="email" value="" placeholder="" aria-label="email" />
<span id="email1" class="glyphicon form-control-feedback"></span>
</div>
<!-- end .form-group -->
</div>
<div class="col-lg-6">
<div class="form-group has-feedback wow flipInX" data-wow-duration="1000ms">
<label for="mensaje">Mensaje*</label>
<textarea id="mensaje" class="form-control" name="mensaje" rows="10" ></textarea>
<span id="mensaje1" class="glyphicon form-control-feedback"></span>
</div>
<!-- end .form-group -->
</div>
<div class="clearfix"></div>
<div class="text-center">
<div class="form-group wow zoomInDown" data-wow-duration="800ms">
<button id="submitContact" type="submit" class="btn btn-default btn-lg">Enviar</button>
<button class="btn btn-danger btn-lg" type="reset">Borrar</button>
</div>
<!-- end .form-group -->
</div>
<!-- end .text-center -->
</form>
<!-- Modal success on submit -->
<div class="theme-submit-success-modal">
<div class="modal fade" id="successForm" tabindex="-1" role="dialog" aria-labelledby="successFormModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="text-center">
<span class="fa fa-comments-o"></span>
</div>
<h4 class="text-center" name="modal_contact" id="successFormModalLabel">Enviado Con Éxito</h4>
<p class="text-center">Gracias por contactarnos, en breve contestaremos a su mensaje. </p>
</div>
<div class="modal-footer">
<div class="text-center">
<button type="button" class="btn btn-default" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
</div>
</div>
You should start learning how to make websites. So much code for a simple form?!
You better show the modal after the form is sent not just submitted, I think.
Is there a reason for returning false here:
submitHandler: function(form) {
$('#successForm').modal('show');
return false;
}
This maybe preventing execution of other necessary code.
In the database I have a table called articles. On one page of my website there is a list of titles of all articles - and each title is actually a link to edit the article. It looks like this:
<a onclick="launch_edit_modal(<?php echo $article->getId(); ?>)" data-toggle="modal" data-target="#edit_modal" href="#">Edit</a>
When you click on the link - function launch_edit_modal(id_of_article) is triggered:
<script type="text/javascript">
$('#edit_modal').modal({
show: false
});
function launch_edit_modal(id) {
$.ajax({
type: "POST",
url: "return_article_data.php",
data: {
id:id
},
dataType: "json",
success: function(data) {
$("#category").val(data.category_id);
$("#title").val(data.title);
$("#content").val(data.content);
$('#edit_modal').show();
}
});
}
</script>
This script is at the bottom.
So, using AJAX I find the other data (category, title, content) about that article and then I update the form which is modal's content:
<div class="modal fade" id="edit_modal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span>×</span></button>
<h3 class="modal-title">Edit article</h3>
</div>
<div class="modal-body">
<div class="row">
<form id="edit_forma" class="form-horizontal" method="post" action="edit_article.php">
<fieldset>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="selectbasic">Category:</label>
<div class="col-md-4">
<select id="category" name="category" class="form-control">
<?php foreach($categories as $c): ?>
<option value="<?php echo $c->getId(); ?>"><?php echo $c->getName(); ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="title">Title:</label>
<div class="col-md-4">
<input id="title" name="title" placeholder="" class="form-control input-md" type="text">
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-4 control-label" for="content">Content:</label>
<div class="col-md-4">
<textarea class="form-control" id="content" name="content" rows="10"></textarea>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit"></label>
<div class="col-md-4">
<button type="submit" id="submit" name="submit" class="btn btn-success">Izmeni</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-default">
Close
</button>
</div>
</div>
</div>
</div>
All of this works - but there is a problem - when I click on edit link - Modal is shown, and then after 2 or 3 seconds the form is filled (updated) with data.
Is there a way to fix this - to show Modal after the form is filled (updated)?
Thanks in advance.
As Ghazanfar Mir wrote in the comments below my question, I need just to set:
async: false
for ajax call, and the problem is solved.
Thank you Ghazanfar Mir.
I am using Tinymce for a text editor to edit some text before submitting the form. I then use jQuery to submit the form without loading the page, but when I submit the form it takes two clicks to submit the value of the textarea..
Here is my code for my form:
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Write News Release</h1>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<span id="result"></span>
<div class="panel panel-default">
<div class="panel-heading">News release form</div>
<div class="panel-body">
<form id="myForm" action="dataentry/save_data.php" method="post">
<div class="col-lg-6">
<div class="form-group">
<label>Story date</label>
<div class="controls">
<div class="input-group">
<input type="text" name="date_story" id="date_story" class="datepicker form-control" placeholder="choose date">
<label for="date-picker-2" class="input-group-addon btn"><span class="glyphicon glyphicon-calendar"></span></label>
</div>
</div>
</div>
<div class="form-group">
<label>Writer/Author</label>
<input type="text" name="writer" id="writer" class="form-control" placeholder="Enter Name">
</div>
<div class="form-group">
<label>Headline</label>
<input type="text" name="headline" id="headline" class="form-control" placeholder="Enter headline">
</div>
<div class="form-group">
<label>Source</label>
<input type="text" name="source" id="source" class="form-control" placeholder="Enter source">
</div>
</div>
<div class="col-lg-10">
<div class="form-group">
<label>Story</label>
<textarea name="story" id="story" class="form-control" rows="10"></textarea>
</div>
<div class="form-group">
<label>Keywords</label>
<input type="text" name="keywords" id="keywords" class="form-control" placeholder="Enter keywords separated by comma(,)">
</div>
<input type="hidden" name="save" value="nr">
<button id="submit" name="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script src="../js/save_data_admin.js"></script>
<script src="../js/jquery-1.11.2.js"></script>
<script src="//tinymce.cachefly.net/4.1/tinymce.min.js"></script>
<script>tinymce.init({selector:'textarea'});</script>
and this is inside of save_data_admin.js:
I alredy use tinyMCE.triggerSave() and other getContent but when I try the button isn't submit the form.
$("#submit").click(function() {
//tinyMCE.triggerSave();
$.post( $("#myForm").attr("action"), $("#myForm :input").serializeArray(), function(save){ $("#result").html(save); } );
clearInput();
});
$("#myForm").submit(function(){
return false;
});
function clearInput(){
$('input[type="text"], input[type="date"], textarea').val('');
}
and save_data.php:
<?php
session_start();
include_once '../../include/CsppoAdmin.php';
$csppoAdmin = new CsppoAdmin();
//echo $_POST['date_story']." ".$_POST['writer']." ".$_POST['headline']." ".$_POST['source']." ".$_POST['story']." ".$_POST['keywords'];
if ($_REQUEST['save']=='nr')
{
if (!empty($_REQUEST['date_story']) && !empty($_REQUEST['writer']) && !empty($_REQUEST['headline']) && !empty($_REQUEST['source']) &&!empty($_REQUEST['story']) && !empty($_REQUEST['keywords'])) {
extract($_REQUEST);
$register = $csppoAdmin->add_news_release($date_story,$writer,$headline,$source,$story,$keywords);
if ($register)
echo '<p style="color:green">News release was successful saved!</p>';
else
echo '<p style="color:red">Failed. Inputted already exits please try again.</p>';
}else
echo '<p style="color:red">Fill up all fields</p>';
}
?>
Maby something like this:
$("#myForm").submit(function(){
tinyMCE.triggerSave(); //must called. fills the hidden textarea
//format some data maby?
//post the data
$.post( $("#myForm").attr("action"), $("#myForm :input").serializeArray(), function(save){ $("#result").html(save); } );
return false;
});