Ajax loading after form submit - javascript

I want to display a loading image after I submit a form. Here is my current code (I am using Bootstrap):
<form method="GET" action="/search/results" id="searchform">
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Search" style="min-width: 300px;" required autofocus>
</div>
<button type="submit" class="btn btn-dark btn-md">Search</button>
</div>
<br>
<div class="form-group">
<h4 class="text-muted">Scoring Type</h4>
<label class="radio-inline">
<input type="radio" name="scoring" id="standard" value="standard" checked> Standard
</label>
<!-- other radio options -->
</div>
</form>
<br>
<div class="modal">
</div>
<style>
.modal {
display: none;
position: fixed;
z-index: 1000;
top: 0;
left: 0;
height: 100%;
width: 100%;
background: rgba( 255, 255, 255, .8 )
url("{% static 'img/loading.gif' %}")
50% 50%
no-repeat;
}
body.loading {
overflow: hidden;
}
body.loading .modal {
display: block;
}
</style>
The form submits to a page called /search/results, but I want this page to be loaded with ajax. Once it is done loading, I want to fully replace the search webpage with the webpage that contains the results. While it is loading, I want $('body').addClass('loading'); to be applied, which will display the loading icon in the way I want (I do not want any changes in css, it works how I want it to). I have looked all over the place but I cannot seem to find a solution that works for me. Thanks.

To make sure the form wont submit as normal ones:
remove method="GET";
<form action="/search/results" id="searchform">
Js:
$("#searchform").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this );
var url = $form.attr( "action" );
//before send
$("body").addClass("loading");
/* Send the data using post */
var posting = $.post(url , $( "#searchform" ).serialize() );
/* Alerts the results */
posting.done(function( data ) {
//use data
$("body").removeClass("loading");
});
});

use the below procedure:
var data = $("#searchform").serialize();
$('#searchform').on('submit',function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "/search/results",
data: data,
dataType: "json",
success: function(data) {
//on success remove the image
},
error: function(){
alert('error handing here');
}
});
})

Related

Using jquery validate errorPlacement to get error message in a specific div

I am attempting to use jQuery Validate's errorPlacement function to place an error message, but I cannot figure it out. Whenever I hit submit, the input slides down, instead of the error placing in the newsletterValidate div.
Does anyone see what I am doing wrong in my errorPlacement code?
$('#newsletterForm').validate({
//errorClass: 'invalid',
errorPlacement: function(error, element) {
//element.val(error[0].outerText);
//error.appendTo(element.next('div'));
error.appendTo(element.parent('div').next('div').find('#newsletterValidate'));
},
rules: {
email: {
required: true,
email: true
}
},
messages: {
email: {
required: "Please enter your email address",
email: "Please enter a valid email address"
}
},
submitHandler: function(form) {
event.preventDefault();
var datastring = $('#newsletterForm').serialize();
$.ajax({
url: 'http://localhost:8080/php/newsletterSend.php',
type: 'POST',
data: datastring
,
success: function(data) {
console.log(data);
if (data == 'Error!') {
alert('Unable to submit form!');
alert(data);
} else {
$('#newsletterInput')[0].reset();
$('#newsletterSuccess').show();
}
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
console.log('error');
}
});
}
});
#newsletterInput {
width: 70%;
border: none;
padding: 15px 10px;
outline: none;
font-size: 1.1rem;
font-family: 'Nunito', sans-serif;
display: inline-block;
background: pink;
}
#newsletterSubmit {
width: 25%;
display: inline-block;
border: none;
font-size: 1.1rem;
font-family: 'Nunito', sans-serif;
padding: 15px 10px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
<div>
<form id="newsletterForm">
<input type="email" id="newsletterInput" name="email" placeholder="Email Address *"><input type="submit" id="newsletterSubmit">
</form>
</div>
<div id="newsletterValidate"></div>
error.appendTo(element.parent('div').next('div').find('#newsletterValidate'));
I'm not sure why you are using jQuery to traverse around inside the DOM when you already know the unique id. So just skip right to your target...
error.appendTo($('#newsletterValidate'));
Demo 1: jsfiddle.net/b2enbs0s/
However, now that it's working, you can see there's a different problem. The message is being repeated.
That's because you're trying to place the message outside of the form container...
<div>
<form id="newsletterForm">
<input type="email" id="newsletterInput" name="email" placeholder="Email Address *"><input type="submit" id="newsletterSubmit">
</form>
</div>
<!--// outside of the form //-->
<div id="newsletterValidate"></div>
In this case, the plugin creates the validation message but cannot find it again in order to properly toggle it.
The fix is to place the message element inside of the form container where the plugin can automatically find & toggle after it's created. The following structure visually renders identical to your original layout...
<form id="newsletterForm">
<div>
<input type="email" id="newsletterInput" name="email" placeholder="Email Address *"><input type="submit" id="newsletterSubmit">
</div>
<!--// inside of the form //-->
<div id="newsletterValidate"></div>
</form>
Final Working Demo: jsfiddle.net/b2enbs0s/1/

how to render ajax return in cakephp 3.1

I have a table that have checkboxes inside. after select it how to return a sum of values from table in modal before confirm the form? and how to render the ajax response from controller?
in my view
$("#envia-vendas").ajaxForm({
url: '../vendas/confirmar',
type: 'post',
success: function (data) {
$('#myModal').modal('show');
console.log(data);
},
in my controller
//dostuf
if($this->request->is('ajax')){
$sum = $sum;
$this->render('ajax/confirmado', 'ajax');
echo 'bal';
$this->set('text', 'test');
$this->set('_serialize', ['text']);
}
how to print the result in the view without reloading page?
What this fiddle does is grabs all of your inputs, then pops up a modal after the values and names have been injected for confirmation.
It should give you a good starting point. What this is setup to do is give you the confirmation screen without the need for additional server calls.
Just set your action to the route that you want to pass the information to for server interactions.
HTML
<form id="test-form" method="post" action="your/action/here">
<input type="text" name="test" value="" />
<input type="submit" name="submit-form" value="submit" />
</form>
<div class="modal">
<div class="form-info-wrapper">
</div>
<a class="confirm">Confirm Information</a>
</div>
CSS
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
background: #FFF;
}
JS
jQuery(document).ready(function ($){
$('body').on('click', 'input[type=submit]', function (e) {
e.preventDefault();
var data = $(this).parent('form').serializeArray();
$('.form-info-wrapper').empty();
for(_data in data)
{
$('.form-info-wrapper').append(data[_data].name + ': ' + data[_data].value);
}
$('.modal').fadeIn();
});
$('.confirm').click(function (e){
e.preventDefault();
$('#test-form').submit();
});
});
https://jsfiddle.net/ojaeacps/2/

Adding Overlay to a popup and adding input type field to exit the form

I have been working on creating a popup with some different functionality. It is being used as a pop for users to subscribe to my website. I have added in a form connected my DB, which is all working great. I am now trying to add some custom features.
I am trying to add some overlay (faded) to my background of the popup so my homepage is faded out in the background of the popup
I need to add in a input type field (if possible) to close my form. * I have added in a image with a X, if there is not input type option I will use this to exit the form
Here is my code:
JavaScript:
<script>
function PopUp(hideOrshow) {
if (hideOrshow == 'hide') {
document.getElementById('ac-wrapper').style.display = "none";
}
else if(localStorage.getItem("popupWasShown") == null) {
localStorage.setItem("popupWasShown",1);
document.getElementById('ac-wrapper').removeAttribute('style');
}
}
window.onload = function () {
setTimeout(function () {
PopUp('show');
}, 0);
}
function hideNow(e) {
if (e.target.id == 'ac-wrapper') document.getElementById('ac-wrapper').style.display = 'none';
}
HTML:
<div id="ac-wrapper" style='display:none' onClick="hideNow(event)">
<div id="popup">
<img alt="#" class="close-image" src="Assets/images/Deep_Close.png" />
<form name="Mail_list" action="save.php" method="post">
<br/>
<h4>Subscription</h4>
<br/>
<div class="form-group">
<label for="first_name">First Name: </label>
<input type="text" name="first_name" id="first_name" size="25" placeholder="First Name" autofocus required />
</div>
<div class="form-group">
<label for="last_name">Last Name: </label>
<input type="text" name="last_name" id="last_name" size="25" placeholder="Last Name" required />
</div>
<div class="form-group">
<label for="email">User Email: </label>
<input type="text" name="email" id="email" size="25" placeholder="Email" required />
</div>
<br/><br/>
<input type="submit" value="Submit Form">
<input type="reset" value="Reset Form">
</form>
CSS:
#ac-wrapper {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1001;
}
#popup{
position:absolute;
display:hidden;
top:300px;
left:50%;
width:500px;
height:auto;
margin-left:-250px;
background-color:white;
z-index:6;
padding:20px;
border:solid 5px #333333;
border-radius:5px;
}
#overlay-back {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: #000;
opacity: 0.6;
filter: alpha(opacity=60);
z-index: 5;
display: none
}
.close-image{
display: block;
float:right;
position:relative;
top:-15px;
right: -15px;
height: 20px;
}
As you can see I have added in the 'Overlay' CSS already, I just am not sure how to implement this in my popup to make the functionality work.
Also, the 'close-image' CSS will be used to close the form if their is no input type available to close the form (which I haven't been able to find), How do I implement this is my JavaScript?
For the overlay, give it position: fixed and place it outside of your other elements. You want it to be 'fixed' to the body, so with 100% height and width it'll cover the full page, effectively.
Just build your overlay/ form to look how you want - with all elements visible, then handle the show/ hide afterwards in your JavaScript.
To close the form, just have a click handler to hide both the form and the overlay when the given element is clicked. See a brief example:
var closeImage = document.getElementById('close-image');
var overlay = document.getElementById('overlay-back');
var formWrapper = document.getElementById('ac-form-wrapper');
// Hide the elements & do other stuff you may want..
function hide() {
overlay.style.display = "none";
formWrapper.style.display = "none";
}
// Call this whenever you want to show stuff.
// In this case, it would go inside the setTimeout
// function also.
function show() {
overlay.style.display = "block";
formWrapper.style.display = "block";
}
// Click handler for the image element.
closeImage.addEventListener("click", function() {
hide();
}, false);
It may be better to change the close-image element to be an ID instead, it's easier to target in native JavaScript, and the element probably doesn't need to be a class anyway.

javascript search function not working

I have a search form which which takes an input and pass the data to a django view.
the form has a search button which on click opens a input box like shown in images given below:
Now when i enter something into the input and press enter, it just collapses the input box and no action occurs. It happens every time. I want it to call the function associated with form. I figured out that the problem is in the javascript but don't know how to fix it.
html:
<form class="navbar-form" role="search" method="POST" action="{% url 'search' %}">
{% csrf_token %}
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="search_box">
<span class="input-group-btn">
<button name="search" type="submit" class="search-btn"> <span class="glyphicon glyphicon-search"> <span class="sr-only">Search</span> </span> </button>
</span>
</div>
</form>
javascript:
e(function() {
function t() {
var t = e('.navbar-collapse form[role="search"].active');
t.find("input").val(""), t.removeClass("active")
}
e('header, .navbar-collapse form[role="search"] button[type="reset"]').on("click keyup", function(n) {
console.log(n.currentTarget), (27 == n.which && e('.navbar-collapse form[role="search"]').hasClass("active") || "reset" == e(n.currentTarget).attr("type")) && t()
}), e(document).on("click", '.navbar-collapse form[role="search"]:not(.active) button[type="submit"]', function(t) {
t.preventDefault();
var n = e(this).closest("form"),
i = n.find("input");
n.addClass("active"), i.focus()
}), e(document).on("click", '.navbar-collapse form[role="search"].active button[type="submit"]', function(n) {
n.preventDefault();
var i = e(this).closest("form"),
s = i.find("input");
e("#showSearchTerm").text(s.val()), t()
})
}
css:
.navbar-collapse form[role="search"] input {
font-size: 18pt;
opacity: 0;
display: none;
height: 48px;
position: relative;
z-index: 2;
float: left;
}
.navbar-collapse form[role="search"].active input {
display: table-cell;
opacity: 1;
z-index: 100;
border-radius: 0;
border: none;
line-height: 45px;
height: 75px;
font-size: 14px;
padding: 0px 25px;
width: 315px;
}
.navbar-collapse {float:right; padding:0px}
its because you didn't submit form
Try this to submit form..
Without AJAX
$('form#myForm').submit();
with performing AJAX
$('input#submitButton').click( function() {
$.post( 'some-url', $('form#myForm').serialize(), function(data) {
... do something with response from server
},
'json' // I expect a JSON response
);
});
$('input#submitButton').click( function() {
$.ajax({
url: 'some-url',
type: 'post',
dataType: 'json',
data: $('form#myForm').serialize(),
success: function(data) {
... do something with the data...
}
});
});
Hope this helps..
Letting you know the step by step procedure.
Set a .keyup event on the search input. $("[name='search_box']").keyup(function(e){ .... });
Check if the keycode of the pressed key is equal to 13 (enter key) if(e.keyCode==13){ ... }
If it is 13 then call the function associated with the form.

How to generalize the code of a file upload web form for multiple forms with different id attributes?

I have the following web form to upload a single file using jquery, showing a progress bar and displaying a message when the file has been uploaded:
<form id="uploadFileForm" method="post" action="upload.php" enctype="multipart/form-data">
<input type="file" size="60" name="fileToUpload" />
<input type="submit" value="Upload">
</form>
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div >
</div>
<br />
<div id="message"></div>
In the head section of the webpage I have the related javascript code that detects the upload form through its id, along with the css that formats the progress bar and message divs:
<script>
$(document).ready(function()
{
var options = {
beforeSend: function()
{
$("#progress").show();
//clear everything
$("#bar").width(\'0%\');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#bar").width(percentComplete+\'%\');
$("#percent").html(percentComplete+\'%\');
},
success: function()
{
$("#bar").width(\'100%\');
$("#percent").html(\'100%\');
},
complete: function(response)
{
$("#message").html("<font color=\'#85a129\'>"+response.responseText+"</font>");
},
error: function()
{
$("#message").html("<font color=\'#CC3300\'> ERROR: unable to upload files</font>");
}
};
$("#uploadFileForm").ajaxForm(options);
});
</script>
<style>
#progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
#bar { background-color: #85a129; width:0%; height:20px; border-radius: 3px; }
#percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
Everything works perfectly and I'm happy with it. However I would like to have multiple forms in separate areas of the same page that allow the upload of other files (one form per file). I achieved this by adding new forms and by duplicating the javascript code for each one of the forms changing the ids (e.g. uploadFileForm2, uploadFileForm3,...) along with the ids of the divs associated to the progress bars (progress2,bar2,percent2,...) and messages (message2,...).
This is obviosly very redundant.
How can I generalize my javascript code so that it detects all the ids of the upload forms along with their respective progress bars and messages?
Is there also a way to have a single css specification for all the progress bars even if they have different ids?
Try
//Add data-progress and data-message with the id of those as values
<form id="uploadFileForm" method="post" action="upload.php" enctype="multipart/form-data" data-progress="#progress" data-message="#message">
<input type="file" size="60" name="fileToUpload" />
<input type="submit" value="Upload" />
</form>
<div id="progress" class="progress">
<div id="bar" class="bar"></div>
<div id="percent" class="percent">0%</div>
</div>
<br />
<div id="message" class="message"></div>
then
$(document).ready(function () {
function ajaxSubmit(form) {
var $form = $(form),
$progress = $($form.data('progress')),
$message = $($form.data('message')),
$bar = $progress.find(".bar"),
$percent = $progress.find(".percent");
var options = {
beforeSend: function () {
$progress.show();
//clear everything
$bar.width('0%');
$percent.html("");
$message.html("0%");
},
uploadProgress: function (event, position, total, percentComplete) {
$bar.width(percentComplete + '%');
$percent.html(percentComplete + '%');
},
success: function () {
$bar.width('100%');
$progress.find(".percent").html('100%');
},
complete: function (response) {
$message.html("<font color=\'#85a129\'>" + response.responseText + "</font>");
},
error: function () {
$message.html("<font color=\'#CC3300\'> ERROR: unable to upload files</font>");
}
};
}
ajaxSubmit($("#uploadFileForm"));
ajaxSubmit($("#uploadFileForm1"));
ajaxSubmit($("#uploadFileForm2"));
});

Categories