Creating a loading image while ajax function loads [duplicate] - php

This is the code I have. I'm trying to insert a image to show that ajax is loading but I just can't get this right; I tried a lot of possible ways but it just isn't working. Any suggestions on what to do?
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('main_result');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
$("#main_result").empty().html('<img src="loading.gif" />');
var category = document.getElementById('category').value;
var brand = document.getElementById('brand').value;
var item = document.getElementById('item').value;
var queryString = "&category=" + category + "&brand="+ brand +"&item="+ item;
ajaxRequest.open("GET", "main_search_special.php?section=special" + queryString, true);
ajaxRequest.send(null);

You can approach this in a couple of different ways, you can either
Preload image and create the element when the request is sent and destroy it after it's done
Create it along with the document and then hide it until the request is sent, and then hide it again when it's done
A combination of the two: Preload and create element in javascript, and from there just hide/show the element at each request/completion.
#1 Is probably most preferred when the request is rarely sent, since it doesn't interfere with the document's load, but rather loads after everything else is done. Since creating/destroying an element takes up more processing time than simply hiding/showing the element, this is not a recommended approach.
#2 Is preferred when the request is sent frequently, since you'll be using the loader image often, there is no need to create/destroy it and just have it available from the start. I recommend this approach.
#3 Is preferred when you want to play it safe. This doesn't load the image until the page is done loading and requires very little processing time.
Example #1 | Code
HTML
<div id='content'></div>
Javascript
var PreloadIt = new Image(441,291);
PreloadIt.src="loader.gif";
var http = new XMLHttpRequest();
var url = "thepage.php";
var params = "whatever=you&want=in+here";
http.open("POST", url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
document.getElementById('content').removeChild(document.getElementById('ajaxloader'));
document.getElementById('content').innerHTML = http.responseText
}
}
function BeginLoading(){
var eLoader = document.createElement("img");
eLoader.src = "loader.gif";
eLoader.alt = "";
eLoader.id = "ajaxloader";
document.getElementById('content').appendChild(eLoader);
http.send(params);
}
BeginLoading();
Example #2 | Code
HTML
<div id='content'>
<div id='ajaxloader'><img src="loader.gif" style="display: none"/></div>
</div>
Javascript
var http = new XMLHttpRequest();
var url = "thepage.php";
var params = "whatever=you&want=in+here";
http.open("POST", url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
document.getElementById('ajaxloader').style.display = "none";
document.getElementById('content').innerHTML = http.responseText
}
}
function BeginLoading(){
document.getElementById('ajaxloader').style.display = "block";
http.send(params);
}
BeginLoading();
Example #3 | Code
HTML
<div id='content'></div>
Javascript
function CreateLoader(){
var img = document.createElement("img");
img.id = "ajaxloader";
img.src = "loader.gif";
img.alt = "";
document.getElementById("content").appendChild(img);
img.show = function(){ img.style.display = "block"; }
img.hide = function(){ img.style.display = "none"; }
img.hide();
return img;
}
var eLoader = CreateLoader();
var http = new XMLHttpRequest();
var url = "thepage.php";
var params = "whatever=you&want=in+here";
http.open("POST", url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
eLoader.hide();
document.getElementById('content').innerHTML = http.responseText
}
}
function BeginLoading(){
eLoader.show();
http.send(params);
}
BeginLoading();
Misc
I would recommend keeping track of the returned status. When a request fails, your code will return an error, since you're not handling it. Make sure that the request was a success and handle your errors.
You should also consider using encodeURIComponent(), if you've got data with special characters, like spaces and such.
var category = document.getElementById('category').value;
var brand = document.getElementById('brand').value;
var item = document.getElementById('item').value;
var url = "main_search_special.php"
var parameters = "section=special&category=" + encodeURIComponent(category) + "&brand=" + encodeURIComponent(brand) + "&item=" + encodeURIComponent(item);
ajaxRequest.open("GET", url+"?"+parameters, true);
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && http.status == 200){
var ajaxDisplay = document.getElementById('main_result');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}else{
console.log("Request for \""+url+ "\" failed.");
}
}
ajaxRequest.send();

Just add the image to your display area before you send the request. The results will overwrite it when the request completes.
...
var ajaxDisplay = document.getElementById("main_result");
ajaxDisplay.innerHTML = "<img src='loading.gif' />"
ajaxRequest.send(null);

I'd recommend putting the return action into its own function to make it look a little cleaner
But all you have to do to add an image is:
Before you do your send (basically anywhere in the function), create the image element and append to whatever element in your html you like
When you get a return from your ajax call, delete the image element.

this is what you can do-
set an image at your favorite position.make it's visibility to hidden.before making a call to php make it's visibility to visible and again after response from php file you can make your image's visibility to hidden.
This is one of the way you can do this,there are also other ways.
search.onclick = function()
{
var ajaxRequest;
document.getElementById("image_loading").style.visibility = "visible";
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("image_loading").style.visibility = "hidden";
var ajaxDisplay = document.getElementById('main_result');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
$("#main_result").empty().html('<img src="loading.gif" />');
var category = document.getElementById('category').value;
var brand = document.getElementById('brand').value;
var item = document.getElementById('item').value;
var queryString = "&category=" + category + "&brand="+ brand +"&item="+ item;
ajaxRequest.open("GET", "main_search_special.php?section=special" + queryString, true);
ajaxRequest.send(null);
}

Related

Error arises when javascript code is executed

I changed the database columns to be not nullable and not it works find. But still, no values are received. here is the console error: 4abdikani.local.ask.org/json.php:1 Failed to load resource: net::ERR_NAME_NOT_RESOLVED 4graphs.html:153 GET abdikani.local.ask.org/json.php net::ERR_NAME_NOT_RESOLVED –
what will be the solution for such an error. The code answer for the question How to turn a json files into a graph? returns this error
Here is the main part of the code. I want it to return the value from the local php page and display it on a graph.
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//Push the data in array
var time = new Date().toLocaleTimeString();
var txt = this.responseText;
var obj = JSON.parse(txt); //Ref: https://www.w3schools.com/js/js_json_parse.asp
console.log(obj);
obj.forEach(function(element_data){
console.log(element_data);
ADCvalues.push(element_data.waterlevel);
Tvalues.push(element_data.temperature);
Hvalues.push(element_data.humidity);
timeStamp.push(time);
showGraph();
var table = document.getElementById("dataTable");
var row = table.insertRow(1); //Add after headings
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = time;
cell2.innerHTML = element_data.waterlevel;
cell3.innerHTML = element_data.temperature;
cell4.innerHTML = element_data.humidity;
});
}
};
xhttp.open("GET", "http://abdikani.local.ask.org/json.php", true); // Works fine with me using the same json document locally - Handle readADC server on ESP8266
xhttp.send();
}
</script>
</body>
</html>

jquery effects not loading after xmlhttprequest from the database

This is my xmlhttprequest so after i some text in the search bar. the ajax works fine. it gives back the information that i want.
function ajax_post(){
var hr = new XMLHttpRequest();
var url = "SavingsAddSearch.php";
var sb = document.getElementById("searchWord").value;
var vars = "search="+sb;
if(sb == ""){
hr.open("GET", url, true);
hr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
hr.onreadystatechange = function (){
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
document.getElementById("demo").innerHTML = return_data;
}
}
hr.send();
document.getElementById("demo").innerHTML = "processing...";
}
else{
hr.open("POST", url, true);
hr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
hr.onreadystatechange = function (){
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
document.getElementById("demo").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("demo").innerHTML = "processing...";
}
}
but after the data was fetch from the database. the problem is the jquery effects like hide and slideToggle can't load. but i know my effects works fine. can someone help me how to load the data using ajax with the jquery effects. my jquery target html is in the php side.

AJAX code doesnt reload

Been trying to follow a tutorial:
https://www.udemy.com/json-ajax-data-transfer-to-mysql-database-using-php/
There is a video in section 4: lecture 20
script.js
var output = document.getElementById('output');
output.innerHTML = "";
function submitData(fdata){
var xhttp = new XMLHttpRequest();
xhttp.onload = function(){ console.log(xhttp.responseText);
jData();}
xhttp.open(fdata.method,fdata.action,true);
xhttp.send(new FormData(fdata));
//console.log(fdata.method);
return false;
}
function jData(){
var ajaxhttp = new XMLHttpRequest();
var url ="json.php";
ajaxhttp.open("GET", url, true);
ajaxhttp.setRequestHeader("content-type","application/json");
ajaxhttp.onreadystatechange = function(){
if(ajaxhttp.readyState == 4 && ajaxhttp.status == 200){
var jcontent = JSON.parse(ajaxhttp.responseText);
for (var myObj in jcontent){
output.innerHTML += '<div>' + jcontent[myObj].firstName + ' ' + jcontent[myObj].lastName +
' ' + jcontent[myObj].age + '</div>';
}
console.log(jcontent);
}
}
ajaxhttp.send();
}
I'm not so sure how I am suppose to put the other codes here since it requires a sql command but if ever someone could look at this code. The code is suppose to display the data and every time I insert a new data. It's suppose to display the new data at the bottom however the code does it displays all the data over and over again.
Can someone explain why this is happening?

Uploading files with XMLHttpRequest

I am new to XMLHttpRequest and I have been using it as a AJAX file uploader using JavaScript's FormData().
The problem I am having is that it seems to upload fine, although I think it is not sending it to the right PHP file or my PHP is wrong because nothing is displayed in the folder where pictures should be.
At the moment, I don't know how to view the returned html data
JavaScript:
$("#form").submit(function(event) {
event.preventDefault();
event.stopPropagation();
var form = $(this);
var file = document.getElementById("file");
var data = new FormData();
var onerror = function(event) {
alert("An error occoured!");
}
var onprogressupdate = function(event) {
if(event.lengthComputable) {
var percent = event.loaded / event.total * 100;
$("#progress").html(percent+"%");
}
}
var onreadystatechange = function(event) {
if(request.status == 200 && request.readyState == 4) {
alert("Uploaded!");
$("#progress").hide();
$("#progress").html("");
}
else {
alert("Alternative state and/or status");
console.log("state: " + request.state);
console.log("readyState: " + request.readyState);
}
}
for(var i = 0; i < file.files.length; i++)
data.append('file[]', file.files[i]);
$("#progress").show();
$("#progress").html("Uploading files...");
var request = new XMLHttpRequest();
request.upload.addEventListener("error", onerror);
request.upload.addEventListener("progress", onprogressupdate);
request.upload.addEventListener("readystatechange", onreadystatechange);
request.open("post", "upload.php");
request.setRequestHeader("Content-type", "multipart/form-data");
request.send(data);
});
Upload page
<?php
if(isset($_FILES["file"])) {
$f = $_FILES["file"];
$dir = "data";
if(!file_exists($dir))
mkdir($dir);
foreach($f["name"] as $k => $name) {
$file = $dir."/".$name;
if($f["error"][$k] == 0 && move_uploaded_file($f["tmp_name"][$k], $file)) {
$uploaded[] = $file;
}
}
die(json_encode($uploaded));
}
?>
Don't set the content type, its set automatically.
Create your FormData object with form element you want to send:
var data = new FormData(this);
instead of
var data = new FormData();
The syntax of the FormData is
new FormData (optional HTMLFormElement form)
without the argument, it is empty, see the reference.

how to track the ready state for each file with html5 xmlhttprequest object

below is my code for uploading files using XMLHttpRequest send method
function send_file_to_server(file,id)
{
console.log('send_file_to_server id received = ' + id);
var filename = file.name;
var container_name = $("#gs-file-upload-container").find(':selected').text();
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e)
{
console.log(' bytes loaded = '+e.loaded + ' remaining = ' + e.total);
}
xhr.onreadystatechange = function()
{
if(xhr.status == 200 && xhr.readyState == 4){
on_upload_complete( filename,id,xhr);
}
var queryString = 'http://upload_files?filename='+filename+'&cname='+container_name;
xhr.open("POST", queryString, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", encodeURIComponent(filename));
xhr.setRequestHeader("Content-Type", "application/octet-stream");
xhr.send(file);
}
With the above function i wait for on_upload_complete to get called and then pass the second file object and one by one i am uploading. Can someone suggest how can i make it upload simultaneously i tried doing this below as
var xhr = Array();
function send_file_to_server(file,id)
{
console.log('send_file_to_server id received = ' + id);
var filename = file.name;
var container_name = $("#gs-file-upload-container").find(':selected').text();
xhr[filename] = new XMLHttpRequest();
xhr[filename].upload.onprogress = function(e)
{
console.log(' bytes loaded = '+e.loaded + ' remaining = ' + e.total);
}
xhr[filename].onreadystatechange = function()
{
if(xhr[filename].status == 200 && xhr[filename].readyState == 4){
on_upload_complete( filename,id,xhr);
}
var queryString = 'http://upload_files?filename='+filename+'&cname='+container_name;
xhr[filename].open("POST", queryString, true);
xhr[filename].setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr[filename].setRequestHeader("X-File-Name", encodeURIComponent(filename));
xhr[filename].setRequestHeader("Content-Type", "application/octet-stream");
xhr[filename].send(file);
}
by doing this i xhr[filename] inside onreadystatechange is undefined because of loop and i want to keep track of every file upload progress and finish it . But as you can see the problem is only keeping track of onreadystatechange with a unique id and i am stuck here. Please can anyone throw light , suggestions and recommendations help is appreciated. thanks
You have deal with Javascript Closure. onreadystatechange see filename,id,xhr of the lastest invoke of send_file_to_server function. To change this rewrite your function like this:
var xhr = Array();
function send_file_to_server(file,id)
{
console.log('send_file_to_server id received = ' + id);
var filename = file.name;
var container_name = $("#gs-file-upload-container").find(':selected').text();
xhr[filename] = new XMLHttpRequest();
xhr[filename].upload.onprogress = function(e)
{
console.log(' bytes loaded = '+e.loaded + ' remaining = ' + e.total);
}
(function(localFilename, localId, localXhr){
localXhr[localFilename].onreadystatechange = function(){
if(localXhr[localFilename].status == 200 && localXhr[localFilename].readyState == 4){
on_upload_complete(localFilename, localId, localXhr);
}
}
})( filename,id,xhr)
var queryString = 'http://upload_files?filename='+filename+'&cname='+container_name;
xhr[filename].open("POST", queryString, true);
xhr[filename].setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr[filename].setRequestHeader("X-File-Name", encodeURIComponent(filename));
xhr[filename].setRequestHeader("Content-Type", "application/octet-stream");
xhr[filename].send(file);
}

Categories