AJAX Auto Refresh / Page without refresh after submitting Button - HTML / PHP - javascript

My only problem is the page does not load auto refresh, tho it is loading when i refresh the page..
here is my html and ajax code with its database.
My Trigger Button
<?php
$data = mysqli_query($con,"SELECT * FROM announcement");
$count = mysqli_num_rows($data);
if ($count != 0) {
while($row = mysqli_fetch_array($data)) {
echo '
<button class="btn btn-danger nav-link delannouncement" id="delannouncement">Resume System</button>';
$dataid = $row['id'];
}
}else{
echo '<button class="btn btn-primary nav-link announcement" id="announcement">Passenger Announcement</button>';
}
?>
Fetching the Data in Database
Here is where I call the data in mysql from ajax to here.
$data = mysqli_query($con,"SELECT * FROM announcement");
$count = mysqli_num_rows($data);
if ($count != 0) {
while($row = mysqli_fetch_array($data)) {
echo '<div id="myModal" class="modal" style="position:fixed; display: none; padding-top: 100px;
left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgb(0,0,0); background-color: rgba(0,0,0,0.9); ">
<div class="container" style="width: 100%">
<div class="card col-12" style="background-color: red; color: white;">
<div class="card-header">
<p><h3 class="text-center">Announcement</h3></p>
</div>
<div class="card-body text-center">
<h5>'.$row['additional_info'].'</h5>
<p>Please click refresh button to resume after the announcement</p>
</div>
</div>
</div>
<img class="modal-content" id="img01">
</div>';
$dataid = $row['id'];
}
}
?>
</div>
<script>
document.getElementById('myModal').style.display='block';
My AJAX code
This is my AJAX code, here is where I got the problem the modal will not load right after I clicked the button, before it will work, I need to refresh the page how to fix this problem
$('.announcement').on("click", function () {
$.confirm({
title: 'Announcement',
content: '' +
'<form action="" class="formName">' +
'<div class="form-group">' +
'<label>Announcement Info</label>' +
'<input type="text" placeholder="Enter announcement here" class="add-info form-control" required />' +
'</div>' +
'</form>',
buttons: {
formSubmit: {
text: 'Submit',
btnClass: 'btn-blue',
action: function () {
var addInfo = this.$content.find('.add-info').val();
$.confirm({
type: 'red',
theme: 'material',
title: 'Are you sure you want to make an announcement?',
content:'<strong>Announcement Info:</strong> ' + addInfo,
buttons: {
Yes: {
btnClass: 'btn-green',
action: function () {
$.ajax({
type: "POST",
url: "announcement.php",
data: {
addInfo: addInfo
},
dataType: "text",
success: function (data) {
window.location.replace("change-password.php");
},
error: function (err) {
console.log(err);
}
});
}
},
No: {
text: 'No', // With spaces and symbols
action: function () {
$.alert('Announcement Cancelled');
}
}
}
});
}
},
cancel: function () {
//close
},
},
onContentReady: function () {
// bind to events
var jc = this;
this.$content.find('form').on('submit', function (e) {
// if the user submits the form by pressing enter in the field.
e.preventDefault();
jc.$$formSubmit.trigger('click'); // reference the button and click it
});
}
});
});
I am new to ajax coding and syntax help me to finish this project please.

$('.announcement').on("click", function () {
$.confirm({
///YOUR LONG CODE
});
//ALL YOU NEED
return false;
});
just return false as firing an event when you submit a button inside a form.. :)

Related

How to submit HTML form data in Modal Box using PHP ajax?

I want to add state name in my state mysql table in database using PHP and Ajax but the modal box is not submitting the information. I posted all my code for single button submission in model box and are as follows:
My directory structure is:
test.html
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<link rel="stylesheet" type="text/css" href="./model.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js">
</script>
</head>
<body>
<button id="add_state">Add State</button>
<div>
<?php
include('server/connection.php');
$sqlSelect="SELECT * FROM tbl_state_info ORDER By StateName ASC";
$result = $conn -> query ($sqlSelect);
$result = $conn -> query ($sqlSelect);
echo "<select name='StateName'>";
echo "<option>select</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value=$row[StateName]> $row[StateName] </option>";
}
echo "</select>";
?>
</div>
<div id="add_state_model" class="add_state_model">
<div class="add_state_model_content">
<span class="state_model_close">×</span>
<form id="state_submit_form" method="post" action="">
<label>Enter State:</label>
<input type="text" name="state">
<input type="submit" name="state_submit">
</form>
<div class="message_box" style="margin-left: 60px;"></div>
</div>
</div>
<script src="./model.js"></script>
</body>
</html>
and for backend i am using javascript and PHP
model.js
var add_state_model = document.getElementById('add_state_model');
var add_state_button = document.getElementById('add_state');
var add_state_span = document.getElementsByClassName('state_model_close')[0];
add_state_button.onclick = function(){
add_state_model.style.display = "block";
}
add_state_span.onclick = function(){
add_state_model.style.display = "none";
}
window.onclick = function(event) {
if (event.target == add_state_model) {
add_state_model.style.display = "none";
}
}
$(document).ready(function(){
var delay = 1000;
$('[name="state_submit"]').click(function(e){
e.preventDefault();
var state = $('#state_submit_form').find('[name="state"]').val();
if(state === ''){
$('.message_box').html(
'<p><span style="color:red;">Please enter state name!</span></p>'
);
$('[name="state"]').focus();
return false;
}
console.log(state);
$.ajax({
type: "POST",
url: "server/addstate.php",
data: {"state":state},
beforeSend: function() {
$('.message_box').html(
'<img src="./tenor.gif" width="40" height="40"/>'
);
},
success: function(data)
{
setTimeout(function() {
$('.message_box').html(data);
}, 1000);
}
});
});
});
And also there is server page addstate.php
<?php
if ( ($_POST['state']!="") ){
$state = $_POST['state'];
include('connection.php');
/* check connection */
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
//insert query for registration
$insertSql = "INSERT INTO `tbl_state_info`(`StateName`) VALUES ('$state')";
if ($conn->query($insertSql) === TRUE) {
echo "<span style='color:green;'>
<p>State added to dropdown</p>
</span>";
}else{
printf("Error: %s\n", $conn->error);
}
}
?>
and connection.php file
<?php
// set the timezone first
if(function_exists('date_default_timezone_set')) {
date_default_timezone_set("Asia/Kolkata");
}
$conn = new mysqli('localhost', 'root', '');
//check connection
if($conn->connect_error){
die("Connection Failed".$conn->connect_error);
}
//connect database
mysqli_select_db($conn, 'crm');
?>
and the css file model.css, it is used for Model Box pop up
.add_state_model {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content/Box */
.add_state_model_content {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 30%; /* Could be more or less, depending on screen size */
}
/* The Close Button */
.state_model_close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.state_model_close:hover,
.state_model_close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
I am getting this below error:
Make me correct if I am not wrong
You can visit this URL this will help you to solve your problem How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?
Or try to change URL path
I have tried on my end it's working for me
url: "http://localhost/CRM/server/addstate.php",
to
url: "server/addstate.php"
If any help feel free to ask me
in your ajax request
data object accept only json object and you have passed query string
try this code
$.ajax({
type: "POST",
url: "http://localhost/CRM/server/addstate.php",
data: {"state":state},
beforeSend: function() {
$('.message_box').html(
'<img src="tenor.gif" width="40" height="40"/>'
);
},
success: function(data)
{
setTimeout(function() {
$('.message_box').html(data);
}, 1000);
}
});
and second thing settimeout accept delay in miliseconds which i have specified 1 second

AJAX - No Refresh , loading auto refresh to another page

My only problem is the page does not load auto refresh, tho it is loading when i refresh the page.. P.S Im loading the page to another page
here is my html and ajax code with its database.
My Trigger Button
<?php
$data = mysqli_query($con,"SELECT * FROM announcement");
$count = mysqli_num_rows($data);
if ($count != 0) {
while($row = mysqli_fetch_array($data)) {
echo '
<button class="btn btn-danger nav-link delannouncement" id="delannouncement">Resume System</button>';
$dataid = $row['id'];
}
}else{
echo '<button class="btn btn-primary nav-link announcement" id="announcement">Passenger Announcement</button>';
}
?>
Fetching the Data in Database
Here is where I call the data in mysql from ajax to here.
$data = mysqli_query($con,"SELECT * FROM announcement");
$count = mysqli_num_rows($data);
if ($count != 0) {
while($row = mysqli_fetch_array($data)) {
echo '<div id="myModal" class="modal" style="position:fixed; display: none; padding-top: 100px;
left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgb(0,0,0); background-color: rgba(0,0,0,0.9); ">
<div class="container" style="width: 100%">
<div class="card col-12" style="background-color: red; color: white;">
<div class="card-header">
<p><h3 class="text-center">Announcement</h3></p>
</div>
<div class="card-body text-center">
<h5>'.$row['additional_info'].'</h5>
<p>Please click refresh button to resume after the announcement</p>
</div>
</div>
</div>
<img class="modal-content" id="img01">
</div>';
$dataid = $row['id'];
}
}
?>
</div>
<script>
document.getElementById('myModal').style.display='block';
My AJAX code
This is my AJAX code, here is where I got the problem the modal will not load right after I clicked the button, before it will work, I need to refresh the page how to fix this problem
$('.announcement').on("click", function () {
$.confirm({
title: 'Announcement',
content: '' +
'<form action="" class="formName">' +
'<div class="form-group">' +
'<label>Announcement Info</label>' +
'<input type="text" placeholder="Enter announcement here" class="add-info form-control" required />' +
'</div>' +
'</form>',
buttons: {
formSubmit: {
text: 'Submit',
btnClass: 'btn-blue',
action: function () {
var addInfo = this.$content.find('.add-info').val();
$.confirm({
type: 'red',
theme: 'material',
title: 'Are you sure you want to make an announcement?',
content:'<strong>Announcement Info:</strong> ' + addInfo,
buttons: {
Yes: {
btnClass: 'btn-green',
action: function () {
$.ajax({
type: "POST",
url: "announcement.php",
data: {
addInfo: addInfo
},
dataType: "text",
success: function (data) {
window.location.replace("change-password.php");
},
error: function (err) {
console.log(err);
}
});
}
},
No: {
text: 'No', // With spaces and symbols
action: function () {
$.alert('Announcement Cancelled');
}
}
}
});
}
},
cancel: function () {
//close
},
},
onContentReady: function () {
// bind to events
var jc = this;
this.$content.find('form').on('submit', function (e) {
// if the user submits the form by pressing enter in the field.
e.preventDefault();
jc.$$formSubmit.trigger('click'); // reference the button and click it
});
}
});
});
I am new to ajax coding and syntax help me to finish this project please.
Do not get into this much complex solution, just return data in json(or xml) format form your API, and then render whatever html you want on frontend(i.e. do not return html form Backend)

How to show loader image with message at center & prevent bootstrap modal dialog box from closing while AJAX response is coming from PHP file?

I'm using Bootstrap v 3.0.0. I've following HTML code of Bootstrap Modal:
<div class="modal fade" id="newModal" 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">Submit Form</h4>
</div>
<div class="modal-body" style="max-height: 300px; overflow-y: auto;">
<br/>
<!-- The form is placed inside the body of modal -->
<form id="request_form" method="post" class="form-horizontal" enctype="multipart/form-data" action="">
<div class="form-group">
<label class="col-sm-4 col-sm-offset-1 control-label">Reg ID <span style="color:#FF0000">*</span> :</label>
<div class="col-sm-5">
<input type="text" class="form-control" name="reg_id" id="reg_id"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 col-sm-offset-1 control-label">Reg Date<span style="color:#FF0000">*</span> :</label>
<div class="col-sm-5">
<input type="text" class="form-control date_control" id="reg_date" name="reg_date" value="" placeholder="yyyy-mm-dd">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 col-sm-offset-1 control-label">Upload Image<span style="color:#FF0000">*</span> :</label>
<div class="col-sm-5">
<input type="file" name="reg_image" id="reg_image" accept="image/*" capture="camera" />
</div>
</div>
<div class="form-group">
<div class="col-sm-5 col-sm-offset-5">
<button type="submit" class="btn btn-success" id="btn_receipt_submit">Submit</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
For above bootstrap modal I've written following AJAX-jQuery code :
$('#request_form').submit(function(e) {
var form = $(this);
var formdata = false;
var reg_id = $('#reg_id').val();
var reg_date = $('#reg_date').val();
if(window.FormData) {
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
url : 'xyz.php',
type : 'POST',
cache : false,
data : formdata ? formdata : form.serialize(),
contentType : false,
processData : false,
beforeSend: function() {
$(".btn").prop('disabled', true); // disable both the buttons on modal
},
success: function(response) {
$(".btn").prop('disabled', false); // enable both the buttons on modal
var responseObject = $.parseJSON(response);
if(responseObject.error_message) {
if ($(".alert-dismissible")[0]) {
$('.alert-dismissible').remove();
}
var htmlString = "<div class='alert alert-danger alert-dismissible' role='alert'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>"+responseObject.error_message+"</div>";
$(htmlString).insertBefore('div.modal-body #request_form');
} else {
$('#newModal').modal('hide');
$('#Modal2').modal('show');
}
}
});
e.preventDefault();
});
I want to show some appropriate loader image exactly at the the center of the screen along with the message "Your request is processing...please wait" when the AJAX request goes to PHP file and it should be displayed exactly at the center of the screen until the response from PHP file comes.
Also during this time user should not be able to close the modal, nor it should get hidden if user clicks anywhere apart from the modal. In other words, until the response from PHP file comes user should not be able to do anything.
I tried many tricks but I'm only able to disable the two buttons appearing on form until the response comes. But actually I want to do much more than this.
Here is what you could do:
Use css to create a spinning icon
As for the positioning of the icon and message do the following:
create div that covers the whole page
set the z-index to a high value, higher than that of modal
use css to center content in the div
the div should initially be hidden
when the submit event fires the div is made visible which then disables any user action
Use the following JavaScript:
The JavaScript:
$(function() {
var mod1 = $('#newModal'),
mod2 = $('#modal2'),
btn = $('.open-form'),
ldg = $('#loading');
mod1.add(mod2).modal({show: false});
btn.on('click', function() {
mod1.modal( 'show' );
});
$('#request_form').submit(function(e) {
e.preventDefault();
ldg.find('> div > span').text('Please wait as your file is uploaded')
.end().show();
var form = $(this);
var formdata = false;
var reg_id = $('#reg_id').val();
var reg_date = $('#reg_date').val();
if(window.FormData) {
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
url : formAction,
type : 'POST',
cache : false,
data : formdata ? formdata : form.serialize(),
contentType : false,
processData : false,
success: function(response) {
ldg.hide();
var responseObject = $.parseJSON(response);
if(responseObject.error_message) {
if ($(".alert-dismissible")[0]) {
$('.alert-dismissible').remove();
}
var htmlString = "<div class='alert alert-danger alert-dismissible' role='alert'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>"+responseObject.error_message+"</div>";
$(htmlString).insertBefore('div.modal-body #request_form');
} else {
$('#newModal').modal('hide');
$('#Modal2').modal('show');
}
}
});
});
});
The Demo:
DEMO
http://jsfiddle.net/cnvusn04/2/
CSS:
.modal {
text-align: center;
}
.modal:before {
display: inline-block;
vertical-align: middle;
content: " ";
height: 100%;
}
.modal-dialog {
display: inline-block;
text-align: left;
vertical-align: middle;
}
JQ:
$('#myModal').modal({
show:false,
})
// prevents closure while the ajax call is in progress
$('#myModal').on('hide.bs.modal', function (e) {
if(inProgess == true)
return false;
})
var inProgess = false;
ajaxCall();
function ajaxCall()
{
inProgess = true;
$('#myModal').modal('show');
//simulates the ajax call
setTimeout(function(){
inProgess = false;
$('#myModal').modal('hide');
}, 5000);
}
Notice that i expect that your question should be close cause it is "too broad".
You can try to disable the mouse event on the modal:
$(".modal").css('pointer-events','none');
See also: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
The above does not disable the button (used to open the modal), but you can keep your first solution. Also notice that you will have to set the modal's keyboard option false to pevent closing with the escape key.
Alternatively you code set a overlay with a higher z-index than the modal
CSS:
html, body{
height:100%;
}
#disableall{
position: absolute;
width: 100%;
height:100%;
z-index:1050;
background-color: rgba(255,0,0,0.5);
display:none;
}
html directly after the <body> tag:
<div id="disableall"></div>
javascript:
beforeSend: function() {
$("disableall").show();
},
it worked for me try like this
css
#pageloaddiv {
position: fixed;
margin: 0px;
width: 100%;
height: 100%;
z-index: 100000;
background: url('../img/ajax-loader.gif') no-repeat center center rgba(0, 0, 0, 0.38);
}
html
<div id="pageloaddiv" style="display: none;"></div>
javascript
$.ajax({
url: 'your url',
beforeSend:function(){
$('#pageloaddiv').show();
},
success: function() {
$('#pageloaddiv').hide();
$('#newModal').hide();
},
});
is there anything wrong with using something like font awesome icons that are animated
<i class="fa fa-spin fa-3x"></i>
the above then might do the trick for you

Unable to get the ID of the button

Please have a look at the following code
<?php
//echo $this->Html->css(array('bootstrap', 'mark', 'style'));
echo $this->Html->script(array('timer','swfobject','bootstrap.min.js'));
?>
<style>
#hideall {
display: none;
opacity: 0.7;
position: fixed;
height: 100%;
width: 100%;
top: 0;
left: 0;
background: #000;
border: 1px solid #cecece;
z-index: 1;
vertical-align:middle;
text-align:center;
}
.removeCardflip{
transition: rotateY(0deg);
-webkit-transition: rotateY(0deg);
transition-duration: 0s;
}
/* SECTIONS */
.section {
clear: both;
padding: 0 10px 0 10px;
margin: 0px;
}
</style>
<div id="hideall">
<?php //echo $this->Html->image('progress.gif', array('alt' => 'Wait', 'style' => 'text-align:center; padding-top:200px;'));?>
</div>
<!--<div class="wrapper" style="border: 1px solid red; width: 100%;">-->
<div class="section group" style="margin-top: 50px;">
<div class="col span_3_of_3">
<h3 style="margin:0px; font-size:22px;">Play word game: </h3>
</div>
</div>
<div class="">
<div>
<div>
<span class="remainWords"><?php //echo count($words);?></span> oxxxxxxxxxxxxxxxf <?php //echo $totalWords;?>
</div>
<div>
<?php
echo $this->Html->image("comic_edit.png",
array(
"alt" => "Pareto List",
"id" => "paretoList",
'url' => "javascript:;"
)
);
?>
</div>
</div>
</div>
<div class="container"><div class="row">
<?php
$word="";
foreach($worddeck as $worcard)
{
?>
<div class="xy col-lg-3 col-md-4 col-sm-6 img-rounded" id="card1" style="width:250px; height:200px; background-color:grey; heiht:170px; margin: 10px 10px;">
<div id="enside1" >
<h1 data-pos="<?php //echo ; ?>" ><?php echo $worcard['unique_wordsforcards']['en_word']; $enSpell = $worcard['unique_wordsforcards']['en_word']; ?></h1>
</div>
<div id="ptside1" style="display:none;">
<?php echo $phonemer[$enSpell]; ?>
<p><?php echo $worcard['unique_wordsforcards']['hint']; ?></p>
</div>
<div id="cntrol1">
<button type="button" id="<?php $enSpell ?>" class="a btn btn-success mr5 btn-lg">Acertei</button>
<button type="button" id="2" class="e btn btn-danger mr5 btn-lg">Errei</button>
</div>
</div>
<?php
}
?>
</div></div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script type="text/javascript">
$(document).ready(function(){
$( ".btn-danger" ).click(function(){
console.log("Red Button");
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
console.log( "The act has been done");
toclose.toggle();
});
});
$( ".btn-success" ).click(function(){
console.log("Red Button");
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
xxx($(this).attr('id'));
console.log( "The act has been done");
toclose.toggle();
});
});
$( ".xy" ).click(function(){
$(this).find("#enside1").toggle();
$(this).find("#ptside1").toggle();
console.log(this);
});
function xxx(id)
{
alert(id);
}
function increment()
{
$.ajax({
url: "http://localhost/cake2/flip2/correct",
}).done(function() {
console.log( "The act has been done");
toclose.toggle();
});
}
});
</script>
Please consider how those buttons are being generated inside the PHP loop.
I am trying to print the ID of a button using the below code.
$( ".btn-success" ).click(function(){
console.log("Red Button");
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
xxx($(this).attr('id'));
console.log( "The act has been done");
toclose.toggle();
});
});
But the alert dialog is empty. What has gone wrong here?
You are using $(this) in the wrong place. Save id of button before ajax call and use in ajax call done() function.
$( ".btn-success" ).click(function(){
console.log("Red Button");
idOfButton = $(this).attr('id');
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
alert(idOfButton);
console.log( "The act has been done");
toclose.toggle();
});
});
You can also save the event source before ajax call and later use it to get the id of event source element.
$( ".btn-success" ).click(function(){
console.log("Red Button");
eventSourceButton = $(this);
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
alert(eventSourceButton.attr('id'));
console.log( "The act has been done");
toclose.toggle();
});
});
You need to specify a context parameter in your $.ajax call. The this keyword does not refer to your .btn.sucess but to the window object or to whatever it has been assigned to if a call function was used.
See this example from jQuery ajax docs :
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$( this ).addClass( "done" ); // this refers to document.body
});
I hope that helps !

Using a Modal popup contact form, Is it possible to show a confirmation in same popup, upon submit?

I have a very basic php email contact page that is activated when the user submits from a modal popup window. Instead of redirecting to a "thank you.html" page, is it possible to populate the popup window with the 'thank you' message?
Here is the html:
<!DOCTYPE html>
<head>
<title></title>
<!--Subscribe Popup Function, JQuery -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script type="text/javascript" src="jquery.reveal.js"></script>
<style>
.reveal-modal-bg {position: fixed; height: 100%; width: 100%; background: #000; background: rgba(0,0,0,.8); z-index: 100; display: none; top: 0; left: 0; padding: 0px; border: 0px; margin: 0px;}
.reveal-modal {visibility: hidden;top: 100px; width: 80%;background: #fff;position: absolute;z-index: 101;padding: 0px;border: 0px;margin: 0px 10%;}
</style>
</head>
<body>
Subscribe</div>
<!-- Subscribe Pop-Up Content -->
<div id="myModal" class="reveal-modal">
<form action="receiving.php" method="POST">
<input type="text" name="email" value="EMAIL" /><br>
<input type="submit" name="submit" value="Submit" />
</form>
</div>
</body>
</html>
Here is "receiving.php":
<?php
$email = $_POST['email'];
if(isset($_POST['submit']))
{
$from_add = "$email";
$to_add = "myname#mysite.com";
$subject = "New Subscriber";
$message = "Email: $email";
$headers = "From: $from_add \r\n";
$headers .= "Reply-To: $from_add \r\n";
$headers .= "Return-Path: $from_add\r\n";
$headers .= "X-Mailer: PHP \r\n";
if(mail($to_add,$subject,$message,$headers))
{
$msg = "Mail sent";
}
}
header("location: http://www.mysite.com/thankyou.html"); exit;
?>
And if it helps to see here is the javascript being used "jquery.reveal.js" Please note that I am very inexperienced with js and php. This code was my starting point and it is from here Reveal JQuery Modal:
(function($) {
$('a[data-reveal-id]').live('click', function(e) {
e.preventDefault();
var modalLocation = $(this).attr('data-reveal-id');
$('#'+modalLocation).reveal($(this).data());
});
$.fn.reveal = function(options) {
var defaults = {
animation: 'fadeAndPop', //fade, fadeAndPop, none
animationspeed: 300, //how fast animtions are
closeonbackgroundclick: true, //if you click background will modal close?
dismissmodalclass: 'close-reveal-modal' //the class of a button or element that will close an open modal
};
//Extend dem' options
var options = $.extend({}, defaults, options);
return this.each(function() {
var modal = $(this),
topMeasure = parseInt(modal.css('top')),
topOffset = modal.height() + topMeasure,
locked = false,
modalBG = $('.reveal-modal-bg');
if(modalBG.length == 0) {
modalBG = $('<div class="reveal-modal-bg" />').insertAfter(modal);
}
//Entrance Animations
modal.bind('reveal:open', function () {
modalBG.unbind('click.modalEvent');
$('.' + options.dismissmodalclass).unbind('click.modalEvent');
if(!locked) {
lockModal();
if(options.animation == "fadeAndPop") {
modal.css({'top': $(document).scrollTop()-topOffset, 'opacity' : 0, 'visibility' : 'visible'});
modalBG.fadeIn(options.animationspeed/2);
modal.delay(options.animationspeed/2).animate({
"top": $(document).scrollTop()+topMeasure + 'px',
"opacity" : 1
}, options.animationspeed,unlockModal());
}
if(options.animation == "fade") {
modal.css({'opacity' : 0, 'visibility' : 'visible', 'top': $(document).scrollTop()+topMeasure});
modalBG.fadeIn(options.animationspeed/2);
modal.delay(options.animationspeed/2).animate({
"opacity" : 1
}, options.animationspeed,unlockModal());
}
if(options.animation == "none") {
modal.css({'visibility' : 'visible', 'top':$(document).scrollTop()+topMeasure});
modalBG.css({"display":"block"});
unlockModal()
}
}
modal.unbind('reveal:open');
});
//Closing Animation
modal.bind('reveal:close', function () {
if(!locked) {
lockModal();
if(options.animation == "fadeAndPop") {
modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
modal.animate({
"top": $(document).scrollTop()-topOffset + 'px',
"opacity" : 0
}, options.animationspeed/2, function() {
modal.css({'top':topMeasure, 'opacity' : 1, 'visibility' : 'hidden'});
unlockModal();
});
}
if(options.animation == "fade") {
modalBG.delay(options.animationspeed).fadeOut(options.animationspeed);
modal.animate({
"opacity" : 0
}, options.animationspeed, function() {
modal.css({'opacity' : 1, 'visibility' : 'hidden', 'top' : topMeasure});
unlockModal();
});
}
if(options.animation == "none") {
modal.css({'visibility' : 'hidden', 'top' : topMeasure});
modalBG.css({'display' : 'none'});
}
}
modal.unbind('reveal:close');
});
//Open Modal Immediately
modal.trigger('reveal:open')
//Close Modal Listeners
var closeButton = $('.' + options.dismissmodalclass).bind('click.modalEvent', function () {
modal.trigger('reveal:close')
});
if(options.closeonbackgroundclick) {
modalBG.css({"cursor":"pointer"})
modalBG.bind('click.modalEvent', function () {
modal.trigger('reveal:close')
});
}
$('body').keyup(function(e) {
if(e.which===27){ modal.trigger('reveal:close'); } // 27 is the keycode for the Escape key
});
function unlockModal() {
locked = false;
}
function lockModal() {
locked = true;
}
});//each call
}//orbit plugin call
})(jQuery);
You can do it this way . After mailing the user redirect the user to current page(where your pop up was)
header("location: http://www.mysite.com/#mailsuccess"); //with hash at the last
Now in Jquery get this hash match it and fire the pop up
Jquery
$(document).ready(function(){
var hash=window.location.hash;
if(hash==="#mailsuccess")
{
$('#successModal').reveal({ /* options */ }); //You can use same modal or different modal to show success message
}
});
USING SIMPLE AJAX
<!DOCTYPE html>
<head>
<title></title>
<!--Subscribe Popup Function, JQuery -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script type="text/javascript" src="jquery.reveal.js"></script>
<style>
.reveal-modal-bg {position: fixed; height: 100%; width: 100%; background: #000; background: rgba(0,0,0,.8); z-index: 100; display: none; top: 0; left: 0; padding: 0px; border: 0px; margin: 0px;}
.reveal-modal {visibility: hidden;top: 100px; width: 80%;background: #fff;position: absolute;z-index: 101;padding: 0px;border: 0px;margin: 0px 10%;}
</style>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit','#mailform',function(e){
e.preventDefault(); //stop default form submit
var email=$('#mailform input[name="email"]').val(); //get email from form
$.ajax({
type: "POST",
url: "receiving.php",
data: "email="+email,
cache: false,
success: function(html){
if($.trim(html)==='success')
{
$('#myModal').trigger('reveal:close'); //close current modal
$('#successModal').reveal(); //open success modal
}
}
});
});
});
</script>
</head>
<body>
Subscribe</div>
<!-- Subscribe Pop-Up Content -->
<div id="myModal" class="reveal-modal">
<form action="receiving.php" method="POST" id="mailform"> //give a id to form
<input type="text" name="email" value="EMAIL" /><br>
<input type="submit" name="submit" value="Submit" />
</form>
</div>
<div id="successModal" class="reveal-modal">
Mailed successfully
</div>
</body>
</html>
in your PHP remove header location
if(mail($to_add,$subject,$message,$headers))
{
echo 'success';
exit();
}
Here is a resource you can edit and use Download Source Code or see live demo here http://purpledesign.in/blog/pop-out-a-form-using-jquery-and-javascript/
Add a Button or link to your page like this
<p>click to open</p>
“#inline” here should be the “id” of the that will contain the form.
<div id="inline">
<h2>Send us a Message</h2>
<form id="contact" name="contact" action="#" method="post">
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<button id="send">Send E-mail</button>
</form>
</div>
Include these script to listen of the event of click. If you have an action defined in your form you can use “preventDefault()” method
<script type="text/javascript">
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(mailvalid == true && msglen >= 4) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
//This will post it to the php page
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
//Display a message on successful posting for 1 sec
$(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
}
});
}
});
});
</script>
You can add anything you want to do in your PHP file.
Ya sure this is just add id to your form
like:
<form action="receiving.php" method="POST" id="yourformId">
user javascript function
don't use submit button user normal button like
<input type="button" name="submit" value="Submit" onclick="beforesubmit()" />
function beforesubmit()
{
/**open popup**/
return false;
}
onconfirm of popup execute code
$("#yourformId").submit();

Categories

Resources