Display AJAX Loader on submitting a from - php

I would like to display an ajax loader icon when user try to submit a form, and block the content of the page (Fade in).
I have this code, but it works wrongly, it display the loader icon before submitting the form and hide it after submitting the form.
<script type="text/javascript">
function ajaxFunction() {
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
document.getElementById("content").innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open("GET", "?action=sms&pageaction=Send SMS", true);
xmlHttp.send(null);
}​
</Script>
And I have DIV :
<!---progress-->
<div id="content" >
<br/>
<br/>
<br/>
<h1>Loading ... Please wait </h1>
<br/>
<br/>
<img src="image//loading.gif" />
</div>
<!---progress-->
And the submit button is calling the ajaxFunction()
<input type="submit" name="pageaction" class="send_sms" value="Send SMS" onclick="ajaxFunction()" />
Anybody please help me in correcting my code to make it work as follow:
display a transparent background to block the page while submitting the form.
display a loading icon.
Hide the transparent background and hide the loading icon.
Thanks for all

Set your content to hide. You can do that simply:
<div id="content" style="display:none;">
...
</div>
Put it visible before sending the AJAX request.
document.getElementById("content").style.display = "block";​​​​​​
xmlHttp.send(null);

Related

How to submit a form on SUBMIT or ENTER button

I am trying to follow a tutorial and demo. But when I press SUBMIT or ENTER button, it is not submitting, it is just refreshing the page :( and showing an error.
It shows an alert
There was a problem with the request.
And the page refreshes.
My form
<form class="well-home span6 form-horizontal" name="ajax-demo" id="ajax-demo"> <div class="control-group">
<label class="control-label" for="book">Book</label>
<div class="controls">
<input type="text" id="book" onKeyUp="book_suggestion()">
<div id="suggestion"></div>
</div> </div> <div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
And my Javascript
<script>
function book_suggestion()
{
var book = document.getElementById("book").value;
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "book_name=" + book;
xhr.open("POST", "book-suggestion.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//alert(xhr.responseText);
document.getElementById("suggestion").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
</script>
book-suggestion.php
<?php
include('../includes/dbopen.php');
$book_name = $_POST['book_name'];
$sql = "select book_name from book_mast where book_name LIKE '$book_name%'";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))
{
echo "<p>".$row['book_name']."</p>";
}
?>
The submit button used there is not participating in the demo. The purpose of the demo is to show how to fetch data with ajax when user types data in the text box. It may, for sure be extended so that the submit button acts upon and adds some more functions, but for now, that has not been added to the demo.

Why my simple ajax code does not work?

Can anyone help me understand why the code does not work?
Its not change the text in the div to the text that the member write.
And sorry in advance for my English, my English teacher apparently did't do a good job... =/
the first page:
<script>
function showUser()
{
var str = document.forms["myForm"]["users"].value;
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","act2.php?q="+str,true);
xmlhttp.send();
}
</script>
<form name="myForm" onsubmit="return showUser()" method="post">
First name: <input type="text" name="users">
<input type="submit" value="Submit">
</form>
<div id="txtHint"><b>Person info will be listed here.</b></div>
the second page (act2.php): (corrected the name)
<?php
$q=$_GET["q"];
echo "$q";
?>
The file specified in this line
xmlhttp.open("GET","act2.php?q="+str,true);
is act2.php, but according to your post, you're looking for ajax2.php, could that be it?
You have simply forgotten to "return false" in the showUser method, the form will post as usual before the Ajax call is made
edit:
To clarify, in the onsubmit you have return showUser(), the the showUser method never returns a value, to stop the browser from posting the form. Also, as suggested by other posters, you imply the php file is named ajax2.php but the code actually tries to hit act2.php.
Also, using some sort of framework (jQuery is highly popular) is recommended.
Your function needs to return false to prevent the default action of the form, otherwise your form will be submitted (which is the default action).
simply add a return false at the end of your code.
function showUser(){
// ...
xmlhttp.send();
// prevents the default action (the submit from your form)
return false;
}
or:
<form name="myForm" onsubmit="showUser();return false;" method="post">
Also you can safely drop the IE5/6 compat code.
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
simply becomes:
var xmlhttp=new XMLHttpRequest();
The var in front is pretty important, otherwise xmlhttp will become a member of the global object instead of a scoped variable.
Just to show how you can do the same with less pain and jQuery.
<form name="myForm" action="/act2.php">
<input type="text" name="q">
<input type="submit">
</form>
<div id="txtHint"></div>
<script type="text/javascript">
$(document)
// Link handler for submiting form
.on('submit', 'form[name="myForm"]', function(e) {
// Preventing original form submition
e.preventDefault();
// Send all data from form, to url from form's action attribute (/act2.php) and set received data to div with id txtHint
$.get($(this).attr('action'), $(this).serialize(), function(data, status, xhr) {
$('#txtHint').html(data);
});
});
</script>

AJAX and PHP not functioning

Here is my code.
<html>
<head>
<title>Patient Information Management</title>
<!--showDate AJAX script -->
<script language="javascript" type="text/javascript">
function showDate(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.value = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var date = document.getElementByName('Date').value;
var queryString = "?date=" +date ;
ajaxRequest.open("GET", "getappointmentdate.php" +queryString, true);
ajaxRequest.send(null);
}
</script>
<!-- //Calender Script -->
<link rel="stylesheet" type="text/css" media="all" href="scripts/jsDatePick_ltr.min.css"/>
<!--JavaScript-->
<script type="text/javascript" src="scripts/jsDatePick.min.1.3.js"></script>
<!--For javascript Calendar-->
<script type="text/javascript">
window.onload = function(){
new JsDatePick({
useMode:2,
target:"Date",
cellColorScheme:"orange",
dateFormat:"%d-%m-%Y",
});
};
</script>
</head>
<body>
<div class="wrapper">
<?php include("include/header.php"); ?>
<div class="clear"></div>
<?php
<div class="clear"></div>
</div> <!-- end of sidemenu div -->
</div> <!-- end of left div -->
<div id="right" >
<h2>anything</h2>
<div class='grey_divider'></div>
<p> </p>
<div class='grey_divider'></div>
<h3>Make Appointment</h3>
<form action="">
Date : <input type="text" size="20" id="Date" name="Date"/>
<input type='button' onclick='showDate()' value='Submit'/>
</br>
</br>
</form>
</div>
</body>
</div>
</html>
When I click button 'Submit' , it should be run the php document, but unfortunately, nothing happen, someone can help me please.
I catch html date with getElementByName instead of getElementById because the 'id' has been use to catch the calender js .Would it affect?
I'm pretty sure you need to catch the button click and stop it's default behaviour with .preventDefault() and then call your function.
Added code
$('input[type="submit"]').click(function(e) {
e.preventDefault();
showDate();
});

how can i change the output of JavaScript to go to directly to another page instead of an alert window?

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Validate Zip Code</title>
<script type="text/javascript">
function IsValidZipCode(zip) {
var isValid = /20132/.test(zip);
if (isValid)
alert('Valid ZipCode');
else {
alert('yep')
}
}
</script>
</head>
<body>
<form>
<input id="txtZip" name="zip" type="text" /><br />
<input id="Button1" type="submit" value="Check My Zipcode"
onclick="IsValidZipCode(this.form.zip.value)" />
</form>
</body>
</html>
I need to use this to allow the user to go either to a page that says sorry we cannot service your area or to another page that says yes we can service your area based on wheter their zipcode is listed.
also how can i add more than one zip code in the isValid = line?
Setting window.location.href = "your url here"; answers the first part of your question.
"also how can i add more than one zip code in the isValid = line?"
If you want to stick with a regex test you can use the regex or |:
var isValid = /^(20132|20133|20200|90210|etc)$/.test(zip);
Note that I've also added ^ and $ to match the beginning and end of the entered string - the way you had it you'd also get matches if the user entered a longer string containing that code, e.g., "abc20132xyz" would match.
I'd be more inclined to do this validation server-side though.
if (isValid)
document.location.href="validzipcode.html";
else {
document.location.href="yep.html";
}
function IsValidZipCode(zip) {
var isValid = /20132/.test(zip);
if (isValid)
document.location.href="valid_zip.html";
else {
document.location.href="not_valid_zip.html";
}
}
<script type="text/javascript">
function IsValidZipCode(zip) {
var isValid = /20132/.test(zip);
if (isValid)
window.location = baseurl."/valid.php"
else {
window.location = baseurl."/invalid.php"
}
}
</script>
You can redirect it in javascript with following code , that can be put in your example instead of alert()
window.location.href = "http://stackoverflow.com";
You can try ajax for this:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Validate Zip Code</title>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function IsValidZipCode(zip){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
//alert(ajaxRequest);
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
//var ajaxDisplay = document.getElementById('ajaxDiv');
//ajaxDisplay.innerHTML = ajaxRequest.responseText;
alert(ajaxRequest.responseText);
if(ajaxRequest.responseText=="")
{
alert("sorry we cannot service your area");
}
else{
window.location = "Page.php?zip="+zip+"";
}
}
}
//var age = document.getElementById('age').value;
//var wpm = document.getElementById('wpm').value;
//var sex = document.getElementById('sex').value;
var queryString = "?zip=" + zip;
ajaxRequest.open("GET", "zip_check.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
</head>
<body>
<form name="form1" method="post">
<input id="txtZip" name="zip" type="text" /><br />
<input type="button" id="Button1" value="Check My Zipcode"
onclick="IsValidZipCode(document.form1.zip.value)" />
</form>
</body>
</html>

How to pass looping data from html page to php page via AJAX

How to send looping data from html page to php page using ajax. I am trying so hard but i don't get any way passing looping data into php page.
order.html page code are described in the below:
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var age = document.getElementById('age[]').value;
var queryString = "?age=" + age ;
ajaxRequest.open("GET", "example.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Name: <input type='text' id='age[]' Name='age[]' /> <br />
Name: <input type='text' id='age[]' Name='age[]'/>
<br />
<input type='button' onclick='ajaxFunction()' value='Query MySQL' />
</form>
<div id='ajaxDiv'>result will display here</div>
</body>
</html>
example.php page code are described in the below:
<?php
$len = count($_GET['age']);
for($x=0;$x<$len;$x++)
{
echo $service[$x]=$_GET['age'][$x];
}
?>
the [] should be append to the query string, not to the input name
var queryString = "?age[]=" + age1 + "&age[]=" + age2 + "&age[]=" + age3 ;
ajaxRequest.open("GET", "example.php" + queryString, true);

Categories