submitting form then showing loading image by javascript - javascript

I am submitting a form and loading loading gif in the same div by replacing html of form by html of loading image.
I am first submitting the form then loading gif, because I have to replace the content of div(in which form exist) with loading image.
Logs 1,2,3 are printing, loading image is showing but form is not submitting
Please help.
<script>
/* javascriptfunction */
Submit_and_loadimage() {
console.log("1");
document.getElementById("form_in_div").submit();
or
document.forms['form_name'].submit();
console.log("2");
document.getElementById("form_in_div").innerHTML ='LOADING_IMAGE-DIV';
console.log("3");
}

You won't be able to do this easily with plain javascript. When you post a form, the form inputs are sent to the server and your page is refreshed - the data is handled on the server side. That is, the submit() function doesn't actually return anything, it just sends the form data to the server.
If you really wanted to show this kind of working image Javascript (without the page refreshing), then you'll need to use AJAX, and when you start talking about using AJAX, you'll need to use a library. jQuery is by far the most popular, and my personal favourite. There's a great plugin for jQuery called Form which will do exactly what it sounds like you want.
Here's how you'd use jQuery and that plugin:
Show your image on form submit
$('#myForm')
.ajaxForm({
url : 'myscript.php', // or whatever
dataType : 'json',
success : function (response) {
// hide your image
}
})
;

Let suppose on button click you are calling ajax method
<button onclick="LoadData();"/>
before ajax call show image and onComplete ajax method hide
this image
function LoadData(){
$("#loading-image").show();
$.ajax({
url: yourURL,
cache: false,
success: function(html){
$("Your div id").append(html);
},
complete: function(){
$("#loading-image").hide();
}
});
}

you can submit your form using ajax so that page won't redirect.
put your loading '.gif' image somewhere in a hidden block
<div style="display:none" class="loading">
<img src="path/to/loading.gif" />
</div>
set the display of this div to inline-block when you click the submit button. Then make an ajax call. and hide this div again when yo get response from the server.
with jquery you can do it like
jQuery('#submitbtn').click(function(){
jQuery('.loading').show();
jQuery.post( "test.php", { name: "John", time: "2pm" })
.done(function( data ) {
alert( "Data Loaded: " + data );
jQuery('.loading').hide();
});
});

then try this Add div and make it hide by Default.
<div id="loading">
<img id="loading-image" src="images/ajax-loader.gif" alt="Loading..." /> </div>
And in java script on page load show that div containg loading image
<script language="javascript" type="text/javascript">
$(window).load(function() {
$('#loading').hide();
});
</script>~

Related

Javascript to Post Inside a Div

I have this code bellow and I need it to make a post inside a div.
<script type="text/javascript">
$(function() {
$(".loader").click(function(event) {
event.preventDefault(); // stop the link loading the URL in href
$('#content').load($(this).attr('href'));
});
});
</script>
<form method="post">
some random inputs and checkbox's goes here
<input type="submit" href="/consulta/consulta_produto.php" class="loader" value="Consultar">
</form>
When submiting, the javascript is sucessfully loading the consulta_produto.php inside a div called "content", however, I need to adapt the script to make it possible to POST too
Someone at other topic said to Use $(".loader").parent("form").submit instead of $(".loader").click, however i didnt understood what he meant, I tried changing it in a lot of different ways, but none of them worked
I researched a few topics about how to post with javascript, but I could adapt none of them to keep the function to load consulta_produto.php inside the div "content"
So I wonder, how can I adapt my javascript to keep loading consulta_produto.php inside content div while posting the data from some inputs and check boxs?
First of all, you need to either:
Place all of your <script> code after the relevant HTML has been loaded, OR
Wrap it all in a $(document).ready(function() {...}); to achieve the same effect
Then, instead of executing code at your inputs click() event, you can do it upon your forms submit() event. (This is basically what you mentioned someone told you in another topic). I changed your submit input to a submit button, doesn't really matter.
So, instead of loading the href attribute, you load the action attribute of the form itself into the div.
Of course you want to submit actual data along with the form - no problem. You just use an AJAX method. This is in order to stop the page from reloading.
First you do the preventDefault() to stop the usual page reload. Then you initialize the $.ajax() method.
Data: The first parameter 'data' contains all the form data to pass
along.
Type: Represents the type of request (POST)
URL: This is the form action (/consulta/consulta_produto.php).
Success: Finally, the 'success' parameter contains a function
which loads it all into the specified <div>.
AJAX is essential when avoiding page reloads in PHP, play around with it!
<script type="text/javascript">
$(document).ready(function() {
$("#form").submit(function(event) {
event.preventDefault();
$.ajax({ //AJAX Method
data: $(this).serialize(), //Gets data from form
type: $(this).attr('method'), //Gets the method, in your case POST
url: $(this).attr('action'), //Gets the form action
success: function(r) {
$('#content').html(r); //Loads data into div
}
}); //End of AJAX Method
}); //End of form submit event
});
</script>
And here is your HTML:
<div id="content" style="width:100%; height:500px; ">
</div>
<form id="form" action="/consulta/consulta_produto.php" method="post">
some random inputs and checkbox's goes here
<button type="submit">Consultar<button>
</form>

Can I submit a form using jquery/ajax to a php script that returns a file?

I have a PHP script that is using PHPExcel. It generates an xlsx file for download. However, this takes quite a bit of time depending on the paramters that the users selects. I am wondering if I can submit the paramaters to via ajax, show a "loader" image after submitting it, but once the file is complete, return the file for download.
Here is what I tried, but it didn't work:
$(document).ready(function(e) {
$("#reporting-export-form").submit(function(e) {
$("#loadingImage").show();
var url = "reporting-export-download.php";
$.ajax({
type: "POST",
url: url,
data: $("#reporting-export-form").serialize(),
success: function(data)
{
return data;
$("#loadingImage").hide();
}
});
e.preventDefault();
});
});
UPDATE
So I think the consenhsious is that it cant' be done. So I have another idea that is working 99% and fakes an ajax experience, but with 1 glitch. I put an iframe on the page. I then set the target of my form to be that iframe. When it submits, the page stays on it's current page and when the PHPExcel file finishes it presents the file for download. So then I added this jQuery code to my page:
$("#reporting-export-form").submit(function(e) {
$("#loadingImage").show();
});
And that works great as well. Now I want to hide the loading image once the file is either downloaded or cancelled. So I added this code to the page that outputs the file:
$(document).ready(function(e){
$('#loadingImage', window.parent.document).hide();
});
That doesn't work. If I remove the PHP code that outputs the file, then it does remove the loading image after the iframe loads, but as long as I try to output the php file in the iframe, the javascript doesn't seem to work. Any ideas?

Sending dynamic POST data with Javascript

So basically, I'm trying to send some data to a remote PHP page, via POST, with 4 static parameters and one random parameter, a number.
So far what I have done is created an HTML page with a form with 4 hidden fields and 1 empty field, in which a random number is inserted as the value via Javascript (using Math.random). Now whenever I submit this form, it takes me to the remote PHP page, and so I have to click back again (in the browser) and then submit.
So, I decided to load this form in an iFrame in another HTML Page, so after clicking submit, I can just hit refresh, and then submit again.
I want to know, is there a way I can use Javascript in the parent HTML to automatically submit the form in the iFrame, then create a new random value and submit it again?
Here is my code so far
a.html
<html>
<body>
<form method="post" action="http://awebsite.com/remotefile.php">
*some hidden fields with the static values*
<input type="text" id="mytext" name="mobile_no">
<input type="submit">
</form>
<script>//don't remember the exact code, use javascript to generate a random number which is put in the value for mytext via getElementById</script>
</body>
</html>
now this was the form which was to manually send data to the server
this is to load an iframe:
b.html
<html>
<body>
<iframe src="a.html">
</body>
</html>
Can I use javascript in b.html to resend the form multiple times, but with the value of mobile_no different each time?
Or can I simply send POST data with the parameters to the server via simple Javascript (or PHP)
You question isn't 100% clear, but it sounds like you want to asynchronously post form data. You could easily do this with a JavaScript library like jQuery without the need for an iframe. First you should add an ID attribute to your form to make it easier to reference in your jQuery code. Then you can attach an event listener to the form's submit event where you can customize the form before submission and handle the response
$('#myForm').submit(function(e) {
// prevent default form submit action from occuring
e.preventDefault();
// load values need to make AJAX request
var method = $(this).attr('method');
var action = $(this).attr('action');
// Process Ajax request
$.ajax({
type: method,
url: action,
dataType: 'html',
data: $(this).serialize(),
beforeSend: function() {
// generate and assign per form submit random number
// show loading gif
},
success: function(response) {
// AJAX POST success, insert the HTML response into the DOM
},
error: function(jqXHR, textStatus, errorThrown) {
// console.log any errors for debugging here
},
complete: function() {
// Post completion tasks, such as hide loading gif
}
});
});

jQuery fadeIn div after page reload

i have a form that stores user data via an ajax call.
On success i normally have a div fade in with a success message. However i want to reload the page so that the page is updated, and then fade in the success message.
I was using a .load() to update the div, and then toggle the form to hide itself etc. But the .load was causing some other js scripts to not work after it was called etc so for now im going to just reload the page.
However, i want to show the success message div after the page has been reloaded.
This is an example:
if (check) {
$.ajax({
type: "POST",
url: "process/updateuserpref.php",
data: $('.updatepref').serialize(),
dataType: "json",
success: function(response){
if (response.updatePrefSuccess) {
location.reload();
$('#successdisplay').fadeIn(1000);
$('#successdisplay').delay(2500).fadeOut(400);
}
}
});
}
I know obviously the
$('#successdisplay').fadeIn(1000);
$('#successdisplay').delay(2500).fadeOut(400);
Doesnt currently work, but any help on how i can do what i want?
Thanks, Craig.
Instead of simple reloading you could sent a GET variable with the reload, then check if the GET variable exist show the success message if not, do nothing
I do the same thing, so this is how I do it:
intead of reload() I do:
window.location.href = document.location.protocol +"//"+ document.location.hostname + document.location.pathname + '?success=1';
Then in my PHP script I do a conditional output:
<?php if( $isset( $_GET['success'] ) && $_GET[ 'success' ] == 1 ) { ?>
<div id="successdisplay">
Changes performed Successfully
</div>
<?php }?>

any way to stay in the same location when refreshed

i am working on jquery and javascript. and is there any way to make the page refresh and to restore the same link which is clicked. for example. in gmail.com when we open sent items which is in the lefthand side of the window and refresh the page. it get reloaded with the same sent items tab's contents, same things work for inbox and drafts when refreshed. is there anyother method or example to acheive this. if yes. please help. it would be appreciated.
here is my code to make the page refresh on refresh:
<script>
$(window).load(function(){
$(function()
{
$('#submit').click(function()
{
$('.container').show();
$('#login').hide();
$.cookie('shown', true);
});
if ($.cookie('shown')) {
$('#submit').click()
}
});
});
</script>
Here is a sample ajax form submit script.
// this is the id of the submit button
$("#submit").click(function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
Presuming that you're using Ajax to change your page states, why not look at something like History.js?

Categories