Unwanted Empty Modal on Page Load - javascript

Am working in PHP using a jquery dialogue as a modal to display my form errors.
Everything works fine and displays corrrectly except on page load... an empty modal is displayed.
If you close it then proceed to fill-in the form the modal works as it is intended, displaying errors (if any) when the submit button it clicked.
For the sake of brevity I've included only the relavent code.
Am seeking help on how to prevent the empty modal from displaying on page load. I've reviewed dozens of related submissions and attempted to try implementing them, with dismal results. In most cases they either have no effect, or end-up disabling the modal all together.
Thanks in advance for any suggestions.
<?php
/// php error checking and form processing here ///
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" media="screen" />
</head>
<body>
<form action="<?=$_SERVER['PHP_SELF']?>" name="inquiry" method="post">
/// form fields here ///
<ul class="actions">
<li><input type="submit" class="button small" name="submit" id="submit" value="Send Inquiry" /></li>
</ul>
</form>
<div id="error" title="Form Errors:">
<?php
if (!empty($errors))
{
echo "<div style=\"padding:15px 15px 0 15px\">";
echo "<ul style=\"margin-bottom:20px\">";
foreach ($errors as $error)
echo "<li style=\"font-size:15px; padding:5px\">$error</li>";
echo "</ul></div>";
}
?>
</div>
<!-- JS at the end -->
<script src="/assets/js/jquery.min.js"></script><!-- ver: 1.11.3 -->
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$('#error').dialog({
height: 380,
width: 260,
modal: true,
resizable: false,
dialogClass: 'no-close error-dialog'
});
</script>
</body>
</html>

You could prevent this by calling the dialog init just when the form is submitted using $_POST["submit"] like :
<script>
<?php if( isset( $_POST["submit"] ) ){ ?>
$('#error').dialog({
height: 380,
width: 260,
modal: true,
resizable: false,
dialogClass: 'no-close error-dialog'
});
<?php } ?>
</script>

Related

jQuery Confirmation Dialog Modal - Unable to Submit Form Sucessfully

I have a sample code block below which consists of a simple bootstrap form whereby I am using a jqueryUI Modal Dialog as a replacement for the basic javascript confirmation window.
When i submit the form by clicking the submit button, the jqueryUI modal window does popup without any issues.
If;
I click "No" - I get all 3 console.log messages i.e.
1-Confirmation_In_Progress
4-Confirmation_Cancelled
5-Confirmation_Cancelled
If;
I click "Yes" - I get all 3 console.log messages i.e.
1-Confirmation_In_Progress
2-Confirmation_AboutTo
3-Confirmation_Done
Therefore I conclude the jquery code must be working to some extent BUT the form values dont seem to be posted.
I have tried various methods to submit the form as seen below.
Any idea what is wrong with my jquery form submission ?
The form code is below;
<!DOCTYPE html>
<html>
<head>
<title> Simple BootStrap Form - jQuery UI Modal Dialog as Confirmation Box </title>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" media="all" rel="stylesheet" type="text/css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css">
<!-- CSS -->
<style>
.customColor { background: darkturquoise; }
.jqDialogAdjust { float: left; margin: 2px 2px 0 0; }
.no-close .ui-dialog-titlebar-close { display: none }
</style>
</head>
<!-- HTML -->
<body>
<div class="container">
<br><br>
HOME
<br><br>
<?php
if ( isset($_POST['submit_btn']) ) {
echo "<br>"."<br>";
echo "Name :".$_POST['name']."<br>";
echo "Email :".$_POST['email']."<br>";
} else {
?>
<form id="simpleform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
<div class="form-group">
<label for="name">Your Name:</label>
<input type="text" class="form-control" name="name" id="name">
</div>
<div class="form-group">
<label for="email">Your Email:</label>
<input type="email" class="form-control" name="email" id="email">
</div>
<button type="submit" class="btn btn-default" name="submit_btn" id="submit_btn" value="submit_btn" >Submit</button>
</form>
<div id="confirmdialog" title="Confirmation Required"></div>
<?php } ?>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" type="text/javascript"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript"> </script>
<script type="text/javascript" >
$(document).ready(function(){
$("#submit_btn").click(function(event){
console.log('1-Confirmation_In_Progress');
event.preventDefault();
var $target = $( event.target );
var message = 'Proceed With Action?';
var icon = '<span class="ui-icon ui-icon-alert jqDialogAdjust" ></span>';
$('#confirmdialog').html('<p>' + icon + message + '</p>');
$("#confirmdialog").dialog({
autoOpen : false,
modal : true,
height: 170,
width: 340,
resizable: false,
draggable:false,
closeOnEscape: true,
title : " :: Confirmation Required :: ",
classes: {
"ui-dialog-titlebar": "ui-corner-all customColor"
},
dialogClass: "no-close",
buttons: [{
text : "Yes",
click : function() {
console.log('2-Confirmation_AboutTo');
//die;
$target.closest("form").submit();
//$('form#simpleform').submit();
console.log('3-Confirmation_Done');
$(this).dialog("close");
}
},
{
text : "No",
click : function() {
console.log('4-Confirmation_Cancelled');
$(this).dialog("close");
console.log('5-Confirmation_Cancelled');
}
}]
}); // end of confirmdialog.dialog
$('#confirmdialog').dialog('open');
}); // end of submit_btn.click(function(event)
}); // end jQuery Document Ready
</script>
</body>
</html>
The above code block was put together by refering to various snippets here on StackOverFlow but somehow I just cant get the form to submit. If i remove the jquery lines and use a basic javascript confirm window - the form submits properly.
I created a test fiddle and tried to replicate the issue. I could not. It might be best to define your Dialog first and then the events.
For Example: https://jsfiddle.net/Twisty/f0sa5nmL/
JavaScript
$(function() {
$("#confirmdialog").dialog({
autoOpen: false,
modal: true,
height: 170,
width: 340,
resizable: false,
draggable: false,
closeOnEscape: true,
classes: {
"ui-dialog-titlebar": "ui-corner-all customColor"
},
dialogClass: "no-close",
buttons: [{
text: "Yes",
click: function() {
console.log('2-Confirmation_AboutTo');
$("#simpleform").submit();
console.log('3-Confirmation_Done');
$(this).dialog("close");
}
}, {
text: "No",
click: function() {
console.log("4-Confirmation_Cancelled");
$(this).dialog("close");
console.log("5-Confirmation_Cancelled");
}
}]
});
$("#submit_btn").click(function(event) {
console.log("1-Confirmation_In_Progress");
event.preventDefault();
$("#confirmdialog").dialog("open");
});
});
If I choose No, I get:
1-Confirmation_In_Progress
4-Confirmation_Cancelled
5-Confirmation_Cancelled
The form does not submit and the dialog closes. If I choose Yes, I get:
1-Confirmation_In_Progress
2-Confirmation_AboutTo
3-Confirmation_Done
The form then attempts to submit (and fails since it can't submit itself to itself in the fiddle.).
Hope that helps.
As mentioned in my comment above to user Twisty, looks like my problem was this line;
if ( isset($_POST['submit_btn']) ) {
echo "<br>"."<br>";
echo "Name :".$_POST['name']."<br>";
echo "Email :".$_POST['email']."<br>";
}
Jquery form submission does not include the button names and values into the post superglobal. Changing the if to either 'name' or 'email' allowed the post values to appear.
All these form submissions work as long as the if condition is NOT based on the button name/value.
$target.closest("form").submit();
$('form[name="simpleform"]').submit();
$('form#simpleform').submit();
document.forms["simpleform"].submit();
document.getElementById("simpleform").submit()
$('#simpleform').submit();
Thanks.

How can I show a DIV element without creating a new row?

I crated a small login form where I check the username in a external php file. After that I give back an error message or redirect to another site.
My problem is to show the error message. I want a short message above the login form if the username != „test“. In my script, the errormessage appears above the login form, but the login form jumps one row deeper.
Question 1:
How can a create a placeholder above the login form? So that the login form is fix?
Question 2:
Is it the right way to fill a JavaScrpt Variable in PHP as in my Code?
Thanks for your help!
< script >
var error_login;
if (error_login == 1) {
$('#errorText').show();
} else {
$('#errorText').hide();
} <
/script>
<?php
//debug
error_reporting(-1);
ini_set('display_errors', true);
session_start();
session_unset();
session_destroy();
?>
<!doctype html>
<html lang="de">
<head>
<title>Hello World</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
</head>
<body>
<?php include ("login.php"); ?>
<div class="container">
<div id="errorText" class="row justify-content-center">
Login failed!
<!-- This should be a placeholder -->
</div>
<!-- Formular Beginn -->
<div class="row justify-content-center">
<div class="col-md-6">
<form class="form" role="form" method="post" action="?login=1" accept-charset="UTF-8" id="login">
<div class="input-group" id="frmGrpBenutzer">
<input type="password" class="form-control input-lg" id="user" name="user" placeholder="Username" required autofocus>
<span class="input-group-btn">
<button type="submit" class="btn btn-primary btn-custom btn-lg" title="login" id="loginbtn"><span>Go</span></button>
</span>
</div>
</form>
</div>
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>
</html>
Here the login.php file:
<?php
session_start();
if(isset($_GET['login'])) {
$user = $_POST['user'];
if ($user == "test") {
$_SESSION['username'] = $user;
header('Location: site2.php');
} else {
echo "<script>
var error_login = 1;
</script>";
}
}
There are a few possibilities. The easiest would be to set your div with an opacity:0 or visibility:hidden this will make it still take space in the document flow.
Another option, could be to set it's position:absolute this will prevent it to take space inside your login form. Doing this will make it overlap tough, so there would need to be a padding or margin to offset the content of the form.
As for setting your javascript variable with PHP, that's one way to do it yes, but your script already defines error_login... Another way to do it, is use a holder HTML element, give it an id, and a data-* attribute. This will make it very easy to read the information from code:
$('button').click(function() {
console.log($('#login_status').data('login-error'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="login_status" data-login-error="1"></div>
<button>Click me to get result</button>
You could also add all the data you want into a JSON string as the div's content, and parse it once the page loaded.

JQuery validation on inner form (dialog)

I've a jsp with a form that include another jsp with a div (that's a JQuery dialog) and in the dialog I've a form that I've to validate.
My issue is: I cannot create an inner form opened in a dialog. So when I try to validate it, I get following error: Uncaught TypeError: Cannot read property 'form' of undefined.
See following snippet, please:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
</head>
<body>
<form id="extForm">
<div id="myDialog">
<form id="intForm">
<label for="field1">Don't write anything in textbox, just click the button</label>
<input type="text" id="field1" required>
</form>
</div>
</form>
</body>
<script>
$("#myDialog").dialog({
autoOpen: false,
modal: true,
title: "myDialog",
buttons: {
"Click me": function(){
$("#myDialog form").valid();
}
}
});
$("#myDialog").dialog("open");
</script>
</html>
If I remove the external form, it works fine. I can I solve this? Thanks.
Note: I can't remove the external form and I have to validate only the fields inside my dialog.
You are getting that error because when you call $("#myDialog").dialog() function of jQuery, myDialog div loses the form from it's inner html.
Please put html back after dialog and before open dialog functions
e.x.
<script>
$("#myDialog").dialog({
autoOpen: false,
modal: true,
title: "myDialog",
buttons: {
"Click me": function(){
$("#myDialog form").valid();
}
}
});
$("#myDialog").html("<form id='intForm'><label for='field1'>Don\'t write anything in textbox, just click the button</label><input type='text' id='field1' required></form>");
$("#myDialog").dialog("open");
</script>
This code should run fine!
Thank you
I solved wrapping dialog inside a form, using option create:
create: function(){
formDialog = $(this).wrap($('')).parent();
}
This is the result:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
</head>
<body>
<form id="extForm">
<div id="myDialog">
<label for="field1">Don't write anything in textbox, just click the button</label>
<input type="text" id="field1" required>
</div>
</form>
</body>
<script>
var formDialog;
$("#myDialog").dialog({
autoOpen: false,
modal: true,
title: "myDialog",
create: function(){
formDialog = $(this).wrap($('<form>')).parent();
},
buttons: {
"Click me": function(){
formDialog.valid();
}
}
});
$("#myDialog").dialog("open");
</script>
</html>
Thanks to all.

PHP/Javascript/Python not reloading div

I am using a raspberry pi to pulse a relay (on the below form submit) to another piece of equipment which if successfully pulsed will toggle a relay on/off. The toggled relay comes back to the pi as an input which is being monitored on the status.php page inside of the loading div. If I load the below page, it correctly displays the status.php, but after pressing the form submit button, it does not reload the status.php page. I have tried everything I can think of, please help!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Alarm Panel</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#loading').load('/status.php');
}, 2000);
});
// ]]>
</script>
<?php
if (isset($_POST['PULSE'])) {
shell_exec('python /usr/lib/cgi-bin/pulse.py');
}
?>
</head>
<body>
<div id="currentstatus" data-role="collapsible" data-theme="b" data-content-theme="b" data-collapsed="false">
<h1>Current status</h1>
<div id="loading" align="center">
<H3>Loading Status...</H3>
</div>
</div>
<div data-role="collapsible" data-theme="b" data-content-theme="b">
<h4>Change Status</h4>
<form method="post">
<input type="submit" name="PULSE" value="PULSE" />
</form>
</div>
</body>
</html>
status.php
<?php
$status = shell_exec('python /usr/lib/cgi-bin/status.py');
?>
<h3><? echo $status; ?></h3>
<br />
<img src="/img/<? print $status; ?>.jpg" height="250"; width="250";>
have you tried manipulating submit behavior? that may fix it.
$(document).on('click', '[name="pulse"]', function(e) {
e.preventDefault();
$('#loading').load('/status.php');
});
you may also try changing your timeout function... That's a bit tricky because load is an asynchronous function.
var loadStatusTimeout;
function loadStatus() {
$('#loading').load('/status.php', function() {
loadStatusTimeout = setTimeout(loadStatus, 2000);
});
}
loadStatusTimeout = setTimeout(loadStatus, 2000);
also, you're accidentally adding semicolons into your img element:
change:
<img src="/img/<? print $status; ?>.jpg" height="250"; width="250";>
to:
<img src="/img/<? print $status; ?>.jpg" height="250" width="250">

How to use ACE editor to edit and save a file

I'm a dummy in HTML.
In my project, I want to use ACE editor to allow the user editing and saving a file.
I succeed to load the file, and to open it with ACE editor.
The problem is how to save it.
For this part, I need your help.
Here is the code I wrote to use ACE.
<?php
if(isset($_POST["save_modification"])){
$file = "./".$_POST["file_name"];
$file_ptr=fopen($file,"w");
fwrite($file_ptr,$_POST["content"]);
fclose($file_ptr);
}?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" media="all" type="text/css" href="./css/style.css" />
<title>Test</title>
</head>
<body>
<div class="site">
<div class="header">
<span>Test</span>
</div>
</div>
<div class="clean"></div>
<div class="corp">
<div class="corp_ctn">
<h1>Edit a file</h1>
<div id="content" class="paragraphe">
<?php
$dir=opendir("./");
while($file=readdir($dir)){
if(!in_array($file, array(".",".."))) {
echo '<div style="float:left; margin:0 10px; text-align:center;"><a href="?f='.$file.'">';
echo $file;
echo '</a></div>';
echo '<br/>';
}
}
?>
<br clear="all"/>
<?php
if(isset($_GET["f"])) {
echo "<h1>{$_GET["f"]}</h1>";
$file = "./".$_GET["f"];
$content = file_get_contents($file);
?>
<form method="POST" action="index_select_lua_script.php">
<div id="editor" name="content" style="width:100%;height:200px;">
<?php echo $content ?>
</div>
<script src="js/ace/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
var editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/lua");
editor.getSession().setTabSize(4);
editor.setHighlightActiveLine(true);
editor.resize();
</script>
<input type="hidden" name="file_name" value="<?php echo $_GET["f"] ?>" />
<input type="submit" name="save_modification" value="Save modification" />
</form>
<br/><br/>
<?php
}
?>
</div>
</div>
</div>
</div>
When I save my modification, using the save button, the content is empty.
Please, do you have an idea of how I can do it?
Thank you
The HTML5 Filesystem API handles tasks like this quite well now. There are a few ways of capturing the contents of the editor area, and once you've done that you can save it.
Look at something like:
http://www.codeproject.com/Articles/668351/HTML-File-API-Capability-and-Compatibility
http://blog.teamtreehouse.com/building-an-html5-text-editor-with-the-filesystem-apis
http://www.html5rocks.com/en/tutorials/file/filesystem/
Can't remember where, but you can ZIP files together using JS now as well, if you so wish.

Categories

Resources