I'm using modal to display form. I want to validate form and show possible errors after clicking submit button. I don't want to close my modal after validation so I decided to use Ajax. Here is my code:
Modal:
<div class="modal fade" id="form-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<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" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<form name="offer-form" id="offer-form" action="offers.php" method="post">
<label for="name-input">Name</label><br>
<?php
if (isset($_SESSION["name-error"])) {
echo "<p>".$_SESSION["name-error"]."</p>";
unset($_SESSION['name-error']);
}
?>
<input type="text" id="name-input" name="name"><br>
<input type="submit" id="submit-input" name="submit" value="Submit">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
Script:
<script type="text/javascript">
$(document).ready(function(){
$("#offer-form").submit(function(e){
e.preventDefault();
$.ajax({
type : 'POST',
data: $("#offer-form").serialize(),
url : 'validate.php',
success : function(data){
}
});
return false;
});
})
PHP:
<?php
session_start();
$_SESSION["name-error"] = "Error";
?>
The problem is that I have to refresh website to see error being displayed. How can I fix this?
Display the error with JQUERY... If you want PHP to process your $_SESSION you will need to reload the page (because PHP in on the server side).
Do an echo in your PHP file and catch the data in your success function
<?php
session_start();
$_SESSION["name-error"] = "Error";
echo "ERROR";
success : function(data){
if(data = "Error")
{
}
}
Your validation.php file
session_start();
$_SESSION["name-error"] = "Error";
$error = array('error' => $_SESSION["name-error"]);
echo json_encode($error);
Your Html
<label for="name-input">Name</label><br>
<p class='sessionError'></p>
Your ajax success funcion
success : function(data){
$('.sessionError').text(data.error);
}
return the value of the session to your ajax and using jquery append the error to the page:
Add the following to your success function
success : function(data){
$('label[for="name-input"]').html('</br>'+data.message)
}
in your php
<?php
session_start();
header('Content-Type: application/json');
$_SESSION["name-error"] = "Error";
echo json_encode(["message"=>$_SESSION["name-error"]]);
?
Related
I am trying to get it where if there is an error when the user registers it will pop up with a modal like this. (I have it right now with a button to test it out)
So my question is how do I get it to pop up with out a button? Like if someone happened to forget their username, the modal would pop up with the error, But How do I get it where If there is an error the modal will pop up with it.?
<div class="buttonWrapper">
<button type="button" class="btn btn-success btn-df float-button-dark waves-effect waves-effect waves-button waves-float waves-dark" data-toggle="modal" data-target="#myModal2">Primary</button>
<div class="modal modal-default fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<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" id="myModalLabel1">Whoops! Something Happened.</h4>
</div>
<div class="modal-body">
<?php
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<p> - '.$error.'</p>';
}
}
//if action is joined show sucess
if(isset($_GET['action']) && $_GET['action'] == 'joined'){
echo "<h2 class='alert alert-success'>Registration successful, please check your email to activate your account.</h2>";
}
?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
Maybe this could be useful:
<html>
<body>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function () {
$('#idForm').on('submit', function (e) {
e.preventDefault();
var inputs = {
user : {
field : $('#fieldUser'),
error : 'field user required !'
},
password : {
field : $('#fieldPassword'),
error : 'field password required !'
},
email : {
field : $('#fieldEmail'),
error : 'field email required !'
}
};
var errors = new Array();
for(input in inputs) {
//console.log(inputs[input].field.empty())
if(inputs[input].field.val() === "") {
//alert(inputs[input].error)
errors.push(inputs[input].error);
}
}
// errors var contain all errors
if(errors.length > 0) {
// here show your modal with errors.
//$('#idModal').show();
//alert(errors);
var errorsJoin = errors.join('\n');
alert('please review this errors : \n' + errorsJoin);
} else {
alert('sign up successfully');
}
})
})
</script>
<form method="POST" id="idForm">
user : <input type="text" id="fieldUser"> <br>
pass :<input type="text" id="fieldPassword"> <br>
email :<input type="text" id="fieldEmail"> <br>
<input type="submit" value="Sign Up">
</form>
</body>
</html>
I want to update data using modal with ajax in PHP. I am beginer, plz tell me where is my mistake .
HTML Code
<button type="submit" class="btn btn-success" data-toggle="modal" data-cphone='.$row['country_phon'].' data-cname='.$row['country_name'].' >Update</button>';
<div id="myModal" class="modal fade" tabindex="-1" 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">Update Country</h4>
</div>
<form action="" method="post">
<div class="modal-body">
<input type="text" id="cn" name="pcountry">
</div>
<div class="modal-body">
<input type="text" id="cph" name="pphone">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary updt" name="updatecountry" >Save</button>
JS Code: Here when I click on Button, modal appears with the values fetched from database with the help of jquery.
<script>
$(document).ready(function(){
$(".btn").click(function(){
var cphone =$(this).data('cphone');
var cname = $(this).data('cname');
$("#cph").val(cphone);
$("#cn").val(cname);
$("#myModal").modal('show');
});
});</script>
JS code : This is ajax code . I want to update the text of textbox.
<script>
$(".updt").click(function(e){
e.preventDefault();
var cnt = $("#myModal").find("input[name='pcountry']").val();
var cp = $("#myModal").find("input[name='pphone']").val();
$.ajax({
dataType: 'json',
type:'POST',
url: 'test.php',
data:{pcountry:cnt, pphone:cp},
})
)};
</script></div>
PHP Code :
<?php
if(isset($_POST['updatecountry']))
{$country1 = $_POST['pcountry'];
$phone1 = $_POST['pphone'];
echo $country1;
echo $phone1;
echo "Updated Successfully";
mysqli_query($conn,"update country set country_name='$country1' , country_phon='$phone1' where country_id=18");
mysqli_close($conn);
}?>
On view btn class use for update and save. I suggest you please use different class name or id.
<button type="submit" class="form_update btn btn-success" data-toggle="modal" data-cphone='.$row['country_phon'].' data-cname='.$row['country_name'].' >Update</button>';
JS changes
<script>
$(document).ready(function(){
$(".form_update").click(function(){
var cphone = $(this).attr("data-phone");
var cname = $(this).attr("data-cname");
$("#cph").val(cphone);
$("#cn").val(cname);
$("#myModal").modal('show');
});
});
</script>
Hope this code is workinf fine.
please i need someone to help me check if i'm missing something. The form in the Bootstrap modal wont submit.
my HTML codes for the modal (sidebar.php)
<!-- start Joel's modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">E-Logbook Entry</h4>
</div>
<div class="modal-body">
<form id="modal-form" method="post" action="notes_functions.php">
<fieldset>
<label>Log Entry</label>
<textarea rows="4" cols="50" class="form-control" name="note_content" placeholder="What have you learnt today?..."></textarea>
</form>
</div>
<div class = "modal-footer">
<button type = "button" class = "btn btn-default" data-dismiss = "modal">
Close
</button>
<input type="submit" name="submit" class="btn btn-default" id="submitnote" value="Submit" />
</div>
</div>
</div>
</div>
<!-- end Joel's modal -->
codes for the PHP file (notes_functions.php)
<?php
include_once 'database-config.php';
if (isset($_POST['submitnote'])) {
$noteContent = strip_tags($_POST['note_content']);
$sql = "INSERT INTO account_notes (note_contents) VALUES ('$noteContent')";
$dbh->exec($sql);
echo "New record created successfully";
echo "Log details = ".$note_contents;
}
?>
my AJAX codes for submitting the form
<script type="text/javascript">
var frm = $('#modal-form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
dataType: "JSON",
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
</script>
I can't seem to spot the error :-(
your submit button is not in the form. place it in the form or add this to the button
form="modal-form"
like so:
<input type="submit" name="submit" class="btn btn-default" id="submitnote" value="Submit" form="modal-form" />
Two things:-
1.Instead of if (isset($_POST['submitnote'])) { use if (isset($_POST['submit'])) {
2.Put ev.preventDefault(); before $.ajax({
Am trying to submit data using modal bootstrap but i can't get it to work. The page will contain more than one modal to enable user to easily update their details.Here the code.
<div class="modal fade" id="overview-modal" 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">Overview</h4>
</div>
<form id="overview_form" action="neuro/update_profile.php" class="form-horizontal" >
<div class="modal-body">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Overview</label>
<div class="col-sm-10">
<textarea class="form-control" id="overview_input" cols="20" rows="10" name="overview_textarea">
</textarea>
<input type="hidden" name="url"/>
</div>
</div>
<div class="form-group">
</div>
</div>
<div class="modal-footer">
<div class="btn-group">
<input type="submit" id="save" class="btn btn-success" value="Save"/>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
</div>
This is the javascript that will handle the form submission to the php file
<script>
$(document).ready(function () {
$("#save").submit(function () {
var formData = $("form#overview_form").serialize();
var my_url = "neuro/update_profile.php";
$.ajax({
type: "POST",
url: my_url,
data: formData ,
success: function (msg) {
$("#overview-modal").modal('hide');
},
error: function () {
alert("Error encounted");
}
});
return false;
});
});
</script>
The php is in a folder called neoro/update_profile ,since i will be using more than one modal in the profile page i have decided to append a url on the form attributes so that it can be easily processed in the php
$profile = new Profile();
$url = $_POST['url'];
if (isset($url)) {
if ($id == "overview") {
$overview = $_POST['overview'];
$profile->save_overview($user_id, $overview);
return TRUE;
}
} else {
header("Location: ./profile.php");
}
This is full of errors
You are sending the form via GET method and accessing it via POST method
Your URL field is empty
you are using action field and also submit simultaneously
your jquery code is not correct
you are using $id variable in your php code which is undefined
Corrected code:
<form id="overview_form" class="form-horizontal" method="post">
<input type="hidden" name="url" value='yoururl'/>
Do this:
$('#overview_form').submit(// your code here);
Instead of on #save, since you are submitting form not button 😉
Or
Even you can achieve same thing on #save but with click function as below
$('#save').click( // here your code );
I have been trying for 2 days but still no luck!
I want to
Submit Form from index.php to result.php
Show result.php inside Modal while index.php is open! (without
closing index.php)
here is example code!
index.php
<form id="myform" method="post" action="result.php" target="_blank">
<input type="text" name="userId" id="userId"/>
<input id="button" type="submit"/>
</form>
result.php
<div id="resultModal" class="modal fade" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
<i class="fa fa-times-circle"></i>ESC</button>
<h4 class="modal-title">Show Result </h4>
</div>
<div class="modal-body">
</div>
</div>
</div>
</div>
In Modal body
<?php $selectedId = $_POST['userId'];
echo $selectedId;
?>
And JQuery
<script type="text/javascript">
$('#myForm').on('submit', function(ev) {
var userId = $('#userId').find("input").val();
$.ajax({
type: 'POST',
url : $(this).attr('action'),
data: userId,
success: function () {
// alert('form was submitted');
}
});
});
</script>
Well it has taken me some time but I think I found an answer to your question, or at least this solution can give you a good clue on how to continue with what you are doing.
First index.php: Here you need to have your form with an input field and one button, which we will call modal, and submit form (using Ajax for post)
<form id="form" method="post">
<div id="userDiv"><label>UserId</label>
<input type="text" name="userId" id="userId" placeholder="UserId"/> <br></div>
<button type="button" id="btn" class="btn btn-info" data-toggle="modal" data-target="#myModal">Send Data</button>
</form>
Then you need a modal where you will put content from remote page. In modal-body you add one more div tag with id="bingo" to locate him easy :) like this:
<div class="modal fade" id="myModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<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" id="myModalLabel">MyModal</h4>
</div>
<div class="modal-body">
<div id="bingo"></div>
</div>
</div>
</div>
</div>
This page also needs to have a script tag which will do the job. Important it must be placed after the script tag where you load the jquery file.
<script>
$(document).ready(function(){
$("#btn").click(function(){
var vUserId = $("#userId").val();
if(vUserId=='')
{
alert("Please enter UserId");
}
else{
$.post("result.php", //Required URL of the page on server
{ // Data Sending With Request To Server
user:vUserId,
},
function(response,status){ // Required Callback Function
$("#bingo").html(response);//"response" receives - whatever written in echo of above PHP script.
$("#form")[0].reset();
});
}
});
});
</script>
And last but not the least result.php:
<?php
if($_POST["user"])
{
$user = $_POST["user"];
// Here, you can also perform some database query operations with above values.
echo "Your user id is: ". $user;
}
?>
P.S. I hope I didn't mess somewhere with ids, variables or similar because I tried to adjust the solution to your example. I hope this is what you need, or at least this will be a clue to accomplish your task. Still think that this could be done on one page but it was interesting for me to try to find a way to make this work... GL!