WP API featured image attachment - javascript

Using WP API I am trying to get the featured image from a post but unsuccessful -
here is the line of code that is not working:
ourHTMLString += postsData[i]._links[i].wp:featuredmedia[i].href.guid.rendered;
The other lines of code is working. Here is the code:
var prodCatPostsContainer = document.getElementById("prod-Cat-Posts-Container");
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'www.example.com/wp-json/wp/v2/posts?filter[category_name]=news-and-events');
function createHTML(postsData) {
var ourHTMLString = '';
for (i = 0;i < postsData.length;i++) {
ourHTMLString += postsData[i]._links[i].wp:featuredmedia[i].href.guid.rendered;
ourHTMLString += '<h6 class="news-title">' + postsData[i].title.rendered + '</h6>' ;
ourHTMLString += postsData[i].content.rendered;
}
prodCatPostsContainer.innerHTML = ourHTMLString;
}
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
console.log(data);
createHTML(data);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
UPDATE
I have added another XMLHttpRequest to get the media featured image of the news item as per #RYAN AW recommendation, but still not working. I am unsure if I am doing this right, but I am pushing all the featured media ID's into an array, then I use the ID's in the array to make a get request, grabbing the "guid" -> "rendered" image url that I can see in JSON. Do I have to loop through this related news item mediaRequest somehow? i.e mediaRequest.open('GET', 'http://www.example.com/wp-json/wp/v2/media/' + featuredMedia[i]); Any help would be great.
var prodCatPostsContainer = document.getElementById("prod-Cat-Posts-Container");
var mediaContainer = document.getElementById("media-Container");
var featuredMedia = [];
//----------------- News Content ------------------//
var newsRequest = new XMLHttpRequest();
newsRequest.open('GET', 'http://www.example.com/wp-json/wp/v2/posts?filter[category_name]=news-and-events');
newsRequest.onload = function() {
if (newsRequest.status >= 200 && newsRequest.status < 400) {
var data = JSON.parse(newsRequest.responseText);
createNEWS(data);
} else {
console.log("News Request - We connected to the server, but it returned an error.");
}
};
function createNEWS(postsData){
var ourHTMLString = '';
for (i = 0;i < postsData.length;i++){
featuredMedia.push(postsData[i].featured_media);
ourHTMLString += '<h6 class='"news-title"'>' + postsData[i].title.rendered + '</h6>' ;
ourHTMLString += postsData[i].content.rendered + '<br><br>';
}
prodCatPostsContainer.innerHTML = ourHTMLString;
}
newsRequest.onerror = function() {
console.log("Connection error");
};
newsRequest.send();
//----------------- Media Featured Image ------------------//
var mediaRequest = new XMLHttpRequest();
mediaRequest.open('GET', 'http://www.example.com/wp-json/wp/v2/media/' + featuredMedia);
/*for (i = 0;i < featuredMedia.length;i++){
mediaRequest.open('GET', 'http://www.example.com/wp-json/wp/v2/media/' + featuredMedia[i]);
}*/
mediaRequest.onload = function() {
if (mediaRequest.status >= 200 && mediaRequest.status < 400) {
var mediaDat = JSON.parse(mediaRequest.responseText);
createMEDIA(mediaDat);
} else {
console.log("Media Request - We connected to the server, but it returned an error.");
}
};
function createMEDIA(mediaData){
var mediaHTMLString = '';
for (i = 0;i < mediaData.length;i++){
mediaHTMLString += '<img src="' + mediaData[i].guid.rendered + '"/><br>';
}
mediaContainer.innerHTML = mediaHTMLString;
}
mediaRequest.onerror = function() {
console.log("Connection error");
};
mediaRequest.send();

Hi #roshambo Try to write it as answer, with that plugin you don't need to make 2nd request just to get img src of featured image, I can get easily this featured image with php, I am not familiar in javascript. but I think your code should be like this.
var prodCatPostsContainer = document.getElementById("prod-Cat-Posts-Container");
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'www.example.com/wp-json/wp/v2/posts?filter[category_name]=news-and-events');
function createHTML(postsData) {
var ourHTMLString = '';
for (i = 0;i < postsData.length;i++) {
//ourHTMLString += postsData[i].better_featured_image.source_url; //full size
ourHTMLString += postsData[i].better_featured_image.media_details.sizes.post-thumbnail.source_url; //thumbnail
ourHTMLString += '<h6 class="news-title">' + postsData[i].title.rendered + '</h6>' ;
ourHTMLString += postsData[i].content.rendered;
}
prodCatPostsContainer.innerHTML = ourHTMLString;
}
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
console.log(data);
createHTML(data);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
If you still activating that plugin, you can share your JSON response for a single post. If that post has a featured image there will be better_featured_image fields in that response.

I have found an answer https://wordpress.stackexchange.com/questions/241271/wp-rest-api-details-of-latest-post-including-featured-media-url-in-one-request I added this code to my functions file in the GET request location
add_action( 'rest_api_init', 'add_thumbnail_to_JSON' );
function add_thumbnail_to_JSON() {
//Add featured image
register_rest_field('post',
'featured_image_src', //NAME OF THE NEW FIELD TO BE ADDED - you can call this anything
array(
'get_callback' => 'get_image_src',
'update_callback' => null,
'schema' => null,
)
);
}
function get_image_src( $object, $field_name, $request ) {
$feat_img_array = wp_get_attachment_image_src($object['featured_media'], 'thumbnail', true);
return $feat_img_array[0];
}
then called ourHTMLString += '<img src=' + postsData[i].featured_image_src + '>';

Related

Having trouble dynamically writing HTML in Chrome

Okay, so I am working on code to display all the images in a folder as a gallery. I've got a PHP script to find all the files in the folder (someone else had written it, and it works just fine):
<?php
$directory = $_REQUEST['folder'];
if (!is_dir($directory)) {
exit('Invalid diretory path');
}
$files = array();
foreach (scandir($directory) as $file) {
if ('.' === $file) continue;
if ('..' === $file) continue;
$files[] = $file;
}
echo json_encode($files);
?>
Now I had a javascript get the json from the php and display it in a grid:
const urlParams = (new URL(document.location)).searchParams;
const folder = urlParams.get('folder');
const gallery = document.getElementById("web_gallery");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
for(var i = 0; i < myObj.length; i++)
{
var write = "<img src='" + folder + "/" + myObj[i] + "' id='gallery_img'>";
console.log(write);
gallery.innerHTML += write;
}
}
};
xmlhttp.open("GET", "toJson.php?folder=" + folder, true);
xmlhttp.send();
This works just fine on Firefox, but it doesn't display anything on Chrome. I looked through several threads here and the one with the most traction seamed to suggest that I should try to use JQuery, so I set that up and wrote this:
$(document).ready(function(){
const urlParams = (new URL(document.location)).searchParams;
const folder = urlParams.get('folder');
var url = "toJson.php?folder=" + folder;
var toWrite = [];
$.get(url, function( data ) {
var images = JSON.parse(data);
for(var i = 0; i < images.length; i++)
{
toWrite.push("<img src='" + folder + "/" + images[i] + "' id='gallery_img'>");
//$( "#web_gallery" ).append( write ); // Had this here before, but tried to move it down to after it's done.
}
}).done(function()
{
for(var i = 0; i < toWrite.length; i++)
{
$("#web_gallery").append(toWrite[i]);
}
});
});
Someone else suggested that you shouldn't do so many append requests so I changed it to:
$(document).ready(function(){
const urlParams = (new URL(document.location)).searchParams;
const folder = urlParams.get('folder');
var url = "toJson.php?folder=" + folder;
var write = "";
$.get(url, function( data ) {
var images = JSON.parse(data);
for(var i = 0; i < images.length; i++)
{
write += "<img src='" + folder + "/" + images[i] + "' id='gallery_img'>\n";
}
}).done(function()
{
setTimeout(function () {
$("#web_gallery").append(write);
}, 1500);
});
});
All of these work fine in Firefox, but not a single one of them work in Chrome, and I'm not sure why. It seems to have to do with the time and speed of writing to the page, I think.
Append the image element with the createElement method.
var image = document.createElement('img');
image.src = imageFilePath;
$(image).appendTo("#web_gallery");

JavaScript - Self-invoking function can't see functions from external script

I have a conceptual issue about scopes on the following code.
The code is a simple client-side validation script for two forms.
I used a self-invoking function to try a something different approach by avoiding to set all global variables but its behavior seems a bit weird to me.
I am still learning to code with JavaScript and I'm not an expert, but these advanced features are a bit complicated.
I don't want to use jQuery but only pure JavaScript in order to learn the basis.
<!-- Forms handling -->
<script src="validate_functions.js"></script>
<script>
(function main() {
var frmPrev = document.getElementById('frmPrev');
var frmCont = document.getElementById('frmCont');
var btnPrev = frmPrev['btnPrev'];
var btnCont = frmCont['btnCont'];
var caller = '';
var forename = '';
var surname = '';
var phone = '';
var email = '';
var privacy = '';
var message = '';
var infoBox = document.getElementById('info-box');
var infoBoxClose = infoBox.getElementsByTagName('div')['btnClose'];
btnPrev.onclick = function(e) {
submit(e);
};
btnCont.onclick = function(e) {
submit(e);
};
function submit(which) {
caller = which.target.name;
var errors = '';
if(caller == 'btnPrev') {
forename = frmPrev['name'].value.trim();
surname = frmPrev['surname'].value.trim();
phone = frmPrev['phone'].value.trim();
email = frmPrev['email'].value.trim();
message = frmPrev['message'].value.trim();
privacy = frmPrev['privacy'].checked;
}
if(caller == 'btnCont') {
phone = frmCont['phone'].value.trim();
email = frmCont['email'].value.trim();
message = frmCont['message'].value.trim();
}
errors = validateFields(caller, forename, surname, phone, email, privacy, message);
if(errors == '') {
var params = 'which=' + caller;
params += '&fname=' + forename;
params += '&sname=' + surname;
params += '&tel=' + phone;
params += '&email=' + email;
params += '&priv=' + privacy;
params += '&mess=' + message;
var request = asyncRequest();
request.open('POST', "send-mail.php", true);
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
request.setRequestHeader('Content-length', params.length);
request.setRequestHeader('Connection', 'close');
request.onreadystatechange = function() {
if(this.readyState == 4) {
if(this.status == 200) {
if(this.responseText != null) {
infoBox.innerHTML = this.responseText;
} else {
infoBox.innerHTML = '<p>No data from server!</p>';
}
} else {
infoBox.innerHTML = '<p>Could not connect to server! (error: ' + this.statusText + ' )</p>';
}
}
}
request.send(params);
} else {
infoBox.innerHTML = errors;
}
infoBox.style.display = 'block';
}
infoBoxClose.onclick = function() {
infoBox.style.display = 'none';
infoBox.innerHTML = '';
};
function validateFields(_caller, _forename, _surname, _phone, _email, _privacy, _message) {
var errs = '';
if(_caller == 'btnPrev') {
errs += validateForename(_forename);
errs += validateSurname(_surname);
errs += validatePhone(_phone);
errs += validateEmail(_email);
errs += validateMessage(_message);
errs += validatePrivacy(_privacy);
}
if(_caller == "btnCont") {
errs += validatePhone(_phone);
errs += validateEmail(_email);
errs += validateMessage(_message);
}
return errs;
}
function asyncRequest() {
var request;
try {
request = new XMLHttpRequest();
}
catch(e1) {
try {
request = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(e2) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e3) {
request = null;
}
}
}
return request;
}
})();
Web console keeps telling me that single validate functions are not defined.
Why?
They should be loaded from the external script.. furthermore they should have a global scope.
Thank you in advance :)
Problem solved!
The path to the external script was incorrect.
Sorry for this rubbish! ^^"

JavaScript - Calling an 'onClick' function from a For loop loading multiple links

I am in the process of creating a listview from JSON data however, after calling an 'onclick' function from a For loop, the link, which opens up in a new window, loads three URLs into the URL input of the browser. Any idea how I could re-work the below code to just load one link rather that the three based on the below code?
<h3>Links</h3> <br>
<ul class="list">
<div id="timetables"></div>
</ul>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "https://api.myjson.com/bins/qg69t";
var URL_1 = "";
var URL_2 = "";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
URL_1 += arr[i].timetable_1_link;
URL_2 += arr[i].timetable_2_link;
console.log(arr[i].timetable_1_link);
out += '<div>' + arr[i].course + '</div><p>' + arr[i].timetable_1_name + '</p><p>' + arr[i].timetable_2_name + '</p>';
}
document.getElementById("timetables").innerHTML = out;
}
function openLinkInNewWindow_1() {
window.open(URL_1, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
function openLinkInNewWindow_2() {
window.open(URL_2, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
</script>
You can start by refactoring the function that opens the URL to accept a parameter like this:
function openLinkInNewWindow_1(URL) {
window.open(URL, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
Then in the for loop pass the URL along with each link.
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
URL_1 = arr[i].timetable_1_link;
URL_2 = arr[i].timetable_2_link;
console.log(arr[i].timetable_1_link);
out += '<div>' + arr[i].course + '</div><p>' + arr[i].timetable_1_name + '</p><p>' + arr[i].timetable_2_name + '</p>';
}
document.getElementById("timetables").innerHTML = out;
}
This way you only need the one function. Notice also that I removed the + from the URL_1 += line.
Using URL_1+= is culprit here. Every time loops run it appends new string to existing url(s).
So remove += from URL_ variables in your function 'myFunction' and assign values directly by using '=' only.
Updated code is written below
<h3>Links</h3> <br>
<ul class="list">
<div id="timetables"></div>
</ul>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "https://api.myjson.com/bins/qg69t";
var URL_1 = "";
var URL_2 = "";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
URL_1 = arr[i].timetable_1_link;
URL_2 = arr[i].timetable_2_link;
out += '<div>' + arr[i].course + '</div><p>' + arr[i].timetable_1_name + '</p><p>' + arr[i].timetable_2_name + '</p>';
}
document.getElementById("timetables").innerHTML = out;
}
function openLinkInNewWindow_1() {
window.open(URL_1, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
function openLinkInNewWindow_2() {
window.open(URL_2, "_blank", "toolbar=yes,scrollbars=yes,resizable=yes");
}
</script>
You can take a look for updated and running code here

Why phonegap click event fires twice?

I am developing android app using phonegap 1.5.0
App stores data in local database and synchronizes using web services.
I am using one button click to call synchronize data JavaScript function.
What I have found is:
This synch button's on click event fires twice.
Single record is getting uploaded twice and the uploaded time is same in the server database.
How to avoid this?
Thanks
EDIT:
Hey everyone, sorry for the delay in reply; was bit busy with some priority work.
Calling SyncData() function on click of button.
Here is the code:
document.addEventListener("DOMContentLoaded", onDeviceReady, false);
var db;
var maxrecords = 0;
var recordsprocessed = 0;
var urlstart = "http://www.mywebsite.com/";
function onDeviceReady() {
db = window.openDatabase("LocalDB", "1.0", "PhoneGap Demo", 50 * 1024 * 1024);
}
function SyncData() {
maxrecords = 0;
recordsprocessed = 0;
db.transaction(queryDB, errorCB, successCB);
}
function queryDB(tx) {
var entriestoupload = 0;
var profimagetoupload = 0;
//check how many entries are to be synchronized
tx.executeSql('SELECT count(*) as cnt FROM tblEntries WHERE IsUploaded=0', [], function(tx, results) {
entriestoupload = parseInt(results.rows.item(0)['cnt']);
//check how many profile images are to be uploaded
tx.executeSql('SELECT count(*) as cnt FROM tblEntries WHERE IsProfileImageUploaded=0', [], function(tx, results) {
profimagetoupload = parseInt(results.rows.item(0)['cnt']);
//synch proceeds if there is any record which is not sychronised
if (entriestoupload > 0 || profimagetoupload > 0) {
var dataMsg = '';
var porofimgMsg = '';
if (entriestoupload > 0) dataMsg = entriestoupload + ' entry, ';
if (profimagetoupload > 0) porofimgMsg = profimagetoupload + ' profile image ';
// give user exact info about what will be synchronized
if (confirm(dataMsg + porofimgMsg + ' are not synchronized.\n Do you want to start synchronisation? \n Please wait till synch successfull message appears.')) {
//start synchronisation
tx.executeSql('SELECT * FROM tblEntries ORDER BY DateOfRegistration DESC', [], uploadData, errorCB);
}
} else {
alert('All records are already Synchronized.');
}
}, errorCB);
}, errorCB);
}
function uploadData(tx, results) {
var len = results.rows.length;
maxrecords = len;
var Synched = 0;
if (len > 0) {
for (var i = 0; i < len; i++) {
var row = results.rows.item(i);
var LocalId = row['LocalId'];
var DateOfRegistration = getDateTimeformatMySql(String(row['DateOfRegistration']));
var DateOption = getDateTimeformatMySql(String(row['DateOption']));
var VolunteerId = row['VolunteerId'];
var IsUploaded = row['IsUploaded'];
var LiveId = row['LiveId'];
var ProfileImagePath = row['ProfileImagePath'];
var IsProfileImageUploaded = parseInt(row['IsProfileImageUploaded']);
var params = null;
var weburl = null;
if (IsUploaded == 0) {
//set parameters for web service
params = "LocalId=" + LocalId + "&OrganizationName=" + row['OrganizationName'] + "&FirstName=" + row['FirstName'] + "&LastName=" + row['LastName'] + "&EmailAddress=" + row['EmailAddress'] + "&MobileNumber=" + row['MobileNumber'] + "&Country=" + row['Country'] + "&State=" + row['State'] + "&City=" + row['City'] + "&Lattitude=" + row['Lattitude'] + "&Longitude=" + row['Longitude'] + "&Website=" + row['Website'] + "&DateOption=" + DateOption + "&TimeOption=" + row['TimeOption'] + "&NumberOption=" + row['NumberOption'] + +"&RadioOption=" + row['RadioOption'] + "&Details=" + row['Details'] + "&CheckBoxoption=" + row['CheckBoxoption'] + "&DropDownOption=" + row['DropDownOption'] + "&DateOfRegistration=" + DateOfRegistration + "&VolunteerId=" + VolunteerId;
//web service url
weburl = urlstart + "mywebserviceurl";
try {
$.ajax({
async: false,
type: "POST",
url: weburl,
data: params,
dataType: "json",
success: function(data, textStatus, jqXHR) {
if (data.Success == "0") {
alert('web services error:\n' + data.Message);
}
if (data.Success == "1") {
try {
LiveId = parseInt(String(data.LiveId));
IsUploaded = 1;
//Update local database to set IsUploaded and LiveId
tx.executeSql("UPDATE tblEntries SET LiveId= " + LiveId + " ,IsUploaded=1 WHERE LocalId= " + LocalId, [], function(tx, results) {
Synched = Synched + 1; /*alert(LiveId);*/
}, errorCB);
//check if profile image exists or not
if (ProfileImagePath != undefined) {
uploadImage(LiveId, LocalId, ProfileImagePath, '1', '');
}
} catch (e) {
}
}
},
error: function() {
alert("There was an error loading the feed");
}
});
} catch (e) {
}
} else {
//check if data is uploaded and image is not uploaded
if (IsProfileImageUploaded == 0 && ProfileImagePath != undefined) {
uploadImage(LiveId, ShopId, ProfileImagePath, '1', '');
}
}
}
}
} // end of querySucess function
//function to upload image
function uploadImage(LiveId, LocalId, ImagePath, UploadType, CreationDate) {
try {
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = ImagePath;
options.mimeType = "image/jpg";
var params = new Object();
params.LiveId = LiveId;
params.LocalId = LocalId;
params.UploadType = UploadType;
params.CreationDate = CreationDate;
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
var url = urlstart + "mywebservice_url_to_uploadimage";
ft.upload(ImagePath, url, win, fail, options, false);
} catch (e) {
console.error("Survey App Err :" + e.message);
}
}
function win(r) {
var jsonresponse = r.response.substring(r.response.indexOf('{'), r.response.indexOf('}') + 1);
var obj = $.parseJSON(jsonresponse);
if (obj.Success == "1") {
var LocalId = parseInt(obj.LocalId);
var UploadType = parseInt(obj.UploadType);
if (UploadType == 1) {
db.transaction(function(tx) {
tx.executeSql("UPDATE tblEntries SET IsProfileImageUploaded=1 WHERE LocalId=?", [LocalId], function(tx, results) {
}, errorCB);
}, errorCB, successCB);
}
}
}
function fail(error) {
alert("There was an error uploading image");
}
Only solution i found for this is to use tap instead of click and it will solve the problem.

Content Insensitive Autosave via XMLHttpRequest

I am trying to make an autosave that can be dropped into any of my forms and be "self aware" of the content in order to simulate an actual save. In addition, I want it to be able to notify the user in the event of multiple failures of the autosave. The following is the come I have come up with, but I keep getting readyState = 4 and status = 500 as a result of my XMLHttpRequest.send(). When I "normally" click save with the form, the save works perfectly fine, but this code just doesn't seem to pass the data over correctly. Every page that has this code has a setTimeout(autosave,5000) to initialize the code. Can someone point me in the right direction of what I'm doing wrong? I'm new to XMLHttpRequest objects.
For what I can tell, last_params gets "sent" with the correct data, but when I get it via the request() (using classic ASP on the other end), the value is "" (blank). I'm thinking I have an order of execution problem, I just don't know what or where.
Quick footnote: I know that there are 'similar' functions with jQuery and other frameworks, but I do not feel comfortable enough with them yet. I want to start with something "simple".
var last_params = "";
var autosave_time = 61000;
var autosave_fail_check = 5;
var max_autosave_fail_check = 5;
var response_text = "";
function autosave() {
var autosave_button_name = "save_button";
var form_action = document.getElementById("formS").action;
var form_data = document.getElementById("formS");
var all_inputs = form_data.getElementsByTagName("input");
var all_textareas = form_data.getElementsByTagName("textarea");
var params = "";
// Check all inputs for data
for (var i = 0; i < all_inputs.length; i++) {
var current_item = all_inputs[i];
if (current_item.type != "button" && current_item.type != "submit") {
if (current_item.type != "checkbox") {
params += current_item.name + "=" + current_item.value + "&";
} else {
params += current_item.name + "=" + current_item.checked + "&";
}
}
}
// check all textareas for data
for (var i = 0; i < all_textareas.length; i++) {
var current_item = all_textareas[i];
params += current_item.name + "=" + current_item.value + "&";
}
params += "autosave=1";
if (params == last_params) {
setTimeout(autosave, autosave_time);
return;
} else {
last_params = params;
}
// Setup time
var time = "";
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
if (minutes < 10) {
minutes = "0" + minutes;
}
time = hours + ":" + minutes + ":" + seconds;
if(hours > 11){
time = time + "PM";
} else {
time = time + "AM";
}
var status = "[]";
// **************************************************
var http;
try {
// Gecko-based browsers, Safari, and Opera.
http = new XMLHttpRequest();
} catch(e) {
try {
// For Internet Explorer.
http = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
// Browser supports Javascript but not XMLHttpRequest.
document.getElementById(autosave_button_name).value = "Autosave NOT Available";
http = false;
}
}
http.onreadystatechange = function()
{
if (http.readyState == 4 && http.status == 200) {
autosave_fail_check = max_autosave_fail_check; // reset the fail check
}
status = " [" + http.readyState + " / " + http.status + "] ";
}
if (autosave_fail_check <= 0) {
if (autosave_fail_check == 0) {
document.getElementById(autosave_button_name).value = "Autosave FAILURE; Check Connection!";
//alert("Autosave has FAILED! Please check your connection!");
}
autosave_fail_check = -1;
} else {
autosave_fail_check--;
}
var url = form_action;
http.open("POST", url, true); // async set to false to prevent moving on without saving
http.setRequestHeader("Content-type", "multipart/form-data");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.send(last_params);
response_text = http.responseText;
if (autosave_fail_check >= 0) {
document.getElementById(autosave_button_name).value = "Last Saved: " + time + " [" + autosave_fail_check + "] " + status;
} else {
autosave_fail_check = -1;
}
setTimeout(autosave, autosave_time);
} // end function autosave()

Categories