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.
Related
So I am trying to send message to LINE Notify from Google Spreadsheets via google form responses, I already testing the API with Postman and it works, I got the Notification, however it doesn't works on the Apps Script Code. here's the error log:
function autoFillPendataanKontak(e) {
var nama = e.values[1];
var nim = e.values[2];
var bidang = e.values[3];
var file = DriveApp.getFileById('------');
var doc = DocumentApp.openById(file.getId());
var body = doc.getBody();
function sendLineNotify(messageNama, messageBidang) {
var token = ["------"];
var options = {
"method": "post",
"payload": messageNama + " telah mendaftar di Bidang " + messageBidang,
"headers": {
"Authorization": "Bearer " + token
}
};
UrlFetchApp.fetch("https://notify-api.line.me/api/notify", options);
}
function appendTable(variabel1, variabel2){
var rangePSDI = null;
var searchElement = body.findElement(DocumentApp.ElementType.TABLE, rangePSDI);
element = searchElement.getElement();
table = element.asTable();
if (bidang == 'PSDI') {
body.replaceText('{{a}}', variabel1);
body.replaceText('{{b}}', variabel2);
var tr = table.appendTableRow();
var ukur = table.getNumRows();
ukur -= 3;
tr.appendTableCell(ukur+1);
tr.appendTableCell("{{a}}");
tr.appendTableCell("{{b}}");
} else if (bidang == 'PSDM') {
body.replaceText('{{c}}', variabel1);
body.replaceText('{{d}}', variabel2);
var tr = table.appendTableRow();
var ukur = table.getNumRows();
ukur -= 3;
tr.appendTableCell(ukur + 1);
tr.appendTableCell("{{c}}");
tr.appendTableCell("{{d}}");
}
}
appendTable(nama, nim);
sendLineNotify(nama, bidang);
doc.saveAndClose();
}
Solved the problem, I just forgot the "message=" on payload
"payload": "message=" + messageNama + " telah mendaftar di Bidang " + messageBidang,
I'm new to Dropzone Js and i want to upload a file, process data to json then upload to my Flask server.
i appreciate any kind of help, thanks.
var id = '#kt_dropzone_4';
// set the preview element template
var previewNode = $(id + " .dropzone-item");
previewNode.id = "";
var previewTemplate = previewNode.parent('.dropzone-items').html();
previewNode.remove();
var myDropzone4 = new Dropzone(id, { // Make the whole body a dropzone
url: "/Upload", // Set the url for your upload script location
headers: {
'x-csrftoken': $('#csrf_Upload').val()
},
method: "post",
parallelUploads: 5,
acceptedFiles: ".xls, .xlsx, .csv",
previewTemplate: previewTemplate,
maxFilesize: 2, // Max filesize in MB
autoQueue: false, // Make sure the files aren't queued until manually added
previewsContainer: id + " .dropzone-items", // Define the container to display the previews
clickable: id +
" .dropzone-select" // Define the element that should be used as click trigger to select files.
});
myDropzone4.on("addedfile", function (file) {
// Hookup the start button
file.previewElement.querySelector(id + " .dropzone-start").onclick = function () {
myDropzone4.enqueueFile(file);
};
$(document).find(id + ' .dropzone-item').css('display', '');
$(id + " .dropzone-upload, " + id + " .dropzone-remove-all").css('display', 'inline-block');
//remove duplicates
if (this.files.length) {
var i, len;
for (i = 0, len = this.files.length; i < len - 1; i++) // -1 to exclude current file
{
if (this.files[i].name === file.name && this.files[i].size === file.size && this.files[i]
.lastModifiedDate.toString() === file.lastModifiedDate.toString()) {
this.removeFile(file);
$('#muted-span').text('Duplicates are not allowed').attr('class', 'kt-font-danger kt-font-bold').hide()
.fadeIn(1000)
setTimeout(function () {
$('#muted-span').hide().text('Only Excel and csv files are allowed for upload')
.removeClass('kt-font-danger kt-font-bold').fadeIn(500);
}, 2500);
}
}
}
});
// Update the total progress bar
myDropzone4.on("totaluploadprogress", function (progress) {
$(this).find(id + " .progress-bar").css('width', progress + "%");
});
myDropzone4.on("sending", function (file, response) {
console.log(file)
console.log(response)
// Show the total progress bar when upload starts
$(id + " .progress-bar").css('opacity', '1');
// And disable the start button
file.previewElement.querySelector(id + " .dropzone-start").setAttribute("disabled", "disabled");
});
// Hide the total progress bar when nothing's uploading anymore
myDropzone4.on("complete", function (progress) {
var thisProgressBar = id + " .dz-complete";
setTimeout(function () {
$(thisProgressBar + " .progress-bar, " + thisProgressBar + " .progress, " + thisProgressBar +
" .dropzone-start").css('opacity', '0');
}, 300)
});
// Setup the buttons for all transfers
document.querySelector(id + " .dropzone-upload").onclick = function () {
myDropzone4.enqueueFiles(myDropzone4.getFilesWithStatus(Dropzone.ADDED));
};
// Setup the button for remove all files
document.querySelector(id + " .dropzone-remove-all").onclick = function () {
$(id + " .dropzone-upload, " + id + " .dropzone-remove-all").css('display', 'none');
myDropzone4.removeAllFiles(true);
};
// On all files completed upload
myDropzone4.on("queuecomplete", function (progress) {
$(id + " .dropzone-upload").css('display', 'none');
});
// On all files removed
myDropzone4.on("removedfile", function (file) {
if (myDropzone4.files.length < 1) {
$(id + " .dropzone-upload, " + id + " .dropzone-remove-all").css('display', 'none');
}
});
I have not found yet a way to get the uploaded data from dropzonejs. I tried to read the file with FileReader but it's not a binary data (correct me if i'm wrong).
I need to process data on myDropzone4.on("addedfile", function (file){})
and return it as a json format if possible.
I found an answer for it, I just needed to find the input type file.when using dropzone.js either you find the input type file in the html page or in their javascript file, where i found that the input type file was being created with a class to hide this element :
var setupHiddenFileInput = function setupHiddenFileInput() {
if (_this3.hiddenFileInput) {
_this3.hiddenFileInput.parentNode.removeChild(_this3.hiddenFileInput);
}
_this3.hiddenFileInput = document.createElement("input");
_this3.hiddenFileInput.setAttribute("type", "file");
_this3.hiddenFileInput.setAttribute("id", "123");
if (_this3.options.maxFiles === null || _this3.options.maxFiles > 1) {
_this3.hiddenFileInput.setAttribute("multiple", "multiple");
}
// _this3.hiddenFileInput.className = "dz-hidden-input";
}
so i gave it an id and bind an event to the input then i read the file with two functions depends on the format of the file uploaded, for csv files to json :
function getText(fileToRead) {
var reader = new FileReader();
reader.readAsText(fileToRead);
reader.onload = loadHandler;
reader.onerror = errorHandler;
}
function loadHandler(event) {
var csv = event.target.result;
process(csv);
}
function process(csv) {
// Newline split
var lines = csv.split("\n");
result = [];
var headers = lines[0].split(",");
for (var i = 1; i < lines.length - 1; i++) {
var obj = {};
//Comma split
var currentline = lines[i].split(",");
for (var j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
console.log(result);
}
function errorHandler(evt) {
if (evt.target.error.name == "NotReadableError") {
alert("Canno't read file !");
}
}
Read excel files (xls,xlsx) format to json format:
var ExcelToJSON = function () {
this.parseExcel = function (file) {
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
var workbook = XLSX.read(data, {
type: 'binary'
});
workbook.SheetNames.forEach(function (sheetName) {
// Here is your object
var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[
sheetName]);
var json_object = JSON.stringify(XL_row_object);
console.log(JSON.parse(json_object));
jQuery('#xlx_json').val(json_object);
})
};
reader.onerror = function (ex) {
console.log(ex);
};
reader.readAsBinaryString(file);
};
};
the event that will detect change on the input, detect file format then use one of those to get the result in a JSON format:
$(document).ready(function () {
$('input[type="file"]').on('change', function (e) {
// EXCEL TO JSON
var files = e.target.files;
console.log(files)
var xl2json = new ExcelToJSON();
xl2json.parseExcel(files[0]);
var fileName = e.target.files[0].name;
console.log('The file "' + fileName + '" has been selected.');
// CSV TO JSON
var files = e.target.files;
if (window.FileReader) {
getText(files[0]);
} else {
alert('FileReader are not supported in this browser.');
}
});
});
I hope this helps i'm using dropzonejs with keenthemes implementation.
I have a function :
var postBet = function(enemyID, ip_1, ip_2, playerID) {
$.post("save.php", {
enemyID: enemyID,
ip_1: ip_1,
ip_2: ip_2,
playerID: playerID
},
function(data, status) {
document.getElementById("saveWarningText").innerHTML = data;
$("#saveWarningText").fadeIn(100);
setTimeout(function() {
$("#saveWarningText").fadeOut(100);
}, 3000);
}
);
};
Unlike all of my other functions when I attempt to call it I get: Uncaught ReferenceError: postBet is not defined
Update
Full code:
var cors_api_url = 'https://cors-anywhere.herokuapp.com/';
var doCORSRequest = function(options, printResult) {
var x = new XMLHttpRequest();
x.open(options.method, cors_api_url + options.url);
x.onload = x.onerror = function() {
printResult(
(x.responseText || '')
);
};
if (/^POST/i.test(options.method)) {
x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
x.send(options.data);
};
var playerIDs = [""];
var playerNames = [""];
var playerScores = [""];
var enemyIDs = [""];
var enemyNames = [""];
var enemyScores = [""];
var parser2 = new DOMParser();
var xmlDoc2;
var done1 = false;
var done2 = false;
var step1 = function() {
for (var i = 0; i < playerIDs.length; i++) {
var url2 = "http://www" + document.getElementById('extension').value + ".myfantasyleague.com/" + (new Date()).getFullYear() + "/export?TYPE=playerScores&L=" + document.getElementById('code').value + "&RULES&PLAYERS=";
url2 = url2 + playerIDs[i] + ",";
var out2 = "";
callback1(i, url2);
if (i >= playerIDs.length - 1) {
done1 = true;
}
}
for (var i = 0; i < enemyIDs.length; i++) {
var url2 = "http://www" + document.getElementById('extension').value + ".myfantasyleague.com/" + (new Date()).getFullYear() + "/export?TYPE=playerScores&L=" + document.getElementById('code').value + "&RULES&PLAYERS=";
url2 = url2 + enemyIDs[i] + ",";
var out2 = "";
callback2(i, url2);
if (i >= playerIDs.length - 1) {
done2 = true;
}
}
if (done1 && done2) {
step2();
}
};
var callback1 = function(i, url2) {
doCORSRequest({
method: this.id === 'post' ? 'POST' : 'GET',
url: url2,
}, function printResult(result) {
out2 = result;
xmlDoc2 = parser2.parseFromString(out2, "text/xml");
var temp = 0;
for (var j = 0; j < parseInt(xmlDoc2.getElementsByTagName('playerScore').length) - 1; j++) {
if (xmlDoc2.getElementsByTagName('playerScore')[j].getAttribute('score') !== "") {
temp = temp + parseInt(xmlDoc2.getElementsByTagName('playerScore')[j].getAttribute('score'));
}
playerScores[i] = temp;
}
});
};
var callback2 = function(i, url2) {
doCORSRequest({
method: this.id === 'post' ? 'POST' : 'GET',
url: url2,
}, function printResult(result) {
out2 = result;
xmlDoc2 = parser2.parseFromString(out2, "text/xml");
var temp = 0;
for (var j = 0; j < parseInt(xmlDoc2.getElementsByTagName('playerScore').length) - 1; j++) {
if (xmlDoc2.getElementsByTagName('playerScore')[j].getAttribute('score') !== "") {
temp = temp + parseInt(xmlDoc2.getElementsByTagName('playerScore')[j].getAttribute('score'));
}
enemyScores[i] = temp;
}
});
};
var step2 = function() {
for (var i = 0; i < playerIDs.length; i++) {
var url2 = "http://www" + document.getElementById('extension').value + ".myfantasyleague.com/" + (new Date()).getFullYear() + "/export?TYPE=players&PLAYERS=";
url2 = url2 + playerIDs[i];
callback3(i, url2);
}
for (var i = 0; i < enemyIDs.length; i++) {
var url2 = "http://www" + document.getElementById('extension').value + ".myfantasyleague.com/" + (new Date()).getFullYear() + "/export?TYPE=players&PLAYERS=";
url2 = url2 + enemyIDs[i];
callback4(i, url2);
}
};
var callback3 = function(i, url2) {
doCORSRequest({
method: this.id === 'post' ? 'POST' : 'GET',
url: url2
}, function printResult(result) {
xmlDoc2 = parser2.parseFromString(result, "text/xml");
playerNames[i] = xmlDoc2.getElementsByTagName('player')[0].getAttribute('name');
var option = document.createElement("option");
var node = document.createTextNode(playerNames[i] + " : " + playerScores[i]);
option.appendChild(node);
var element = document.getElementById("you");
element.appendChild(option);
});
};
var callback4 = function(i, url2) {
doCORSRequest({
method: this.id === 'post' ? 'POST' : 'GET',
url: url2
}, function printResult(result) {
xmlDoc2 = parser2.parseFromString(result, "text/xml");
enemyNames[i] = xmlDoc2.getElementsByTagName('player')[0].getAttribute('name');
var option = document.createElement("option");
var node = document.createTextNode(enemyNames[i] + " : " + enemyScores[i]);
option.appendChild(node);
var element = document.getElementById("enemy");
element.appendChild(option);
});
};
var postBet = function(enemyID, ip_1, ip_2, playerID) {
$.post("save.php", {
enemyID: enemyID,
ip_1: ip_1,
ip_2: ip_2,
playerID: playerID
},
function(data, status) {
document.getElementById("saveWarningText").innerHTML = data;
$("#saveWarningText").fadeIn(100);
setTimeout(function() {
$("#saveWarningText").fadeOut(100);
}, 3000);
}
);
};
(function() {
postBet('1', '1', '1', '1');
document.getElementById('start').onclick = function(e) {
var url = "http://www" + document.getElementById('extension').value + ".myfantasyleague.com/" + (new Date()).getFullYear() + "/export?TYPE=rosters&L=" + document.getElementById('code').value;
var data = "";
var output = "";
var parser = new DOMParser();
var xmlDoc;
var n1 = document.getElementById("you");
while (n1.firstChild) {
n1.removeChild(n1.firstChild);
}
var n2 = document.getElementById("enemy");
while (n2.firstChild) {
n2.removeChild(n2.firstChild);
}
e.preventDefault();
doCORSRequest({
method: this.id === 'post' ? 'POST' : 'GET',
url: url,
data: data
}, function printResult(result) {
output = result;
xmlDoc = parser.parseFromString(output, "text/xml");
for (var i = 1; i < xmlDoc.getElementsByTagName("franchise")[parseInt(document.getElementById('team').value) - 1].childNodes.length; i += 2) {
playerIDs.length = Math.round((xmlDoc.getElementsByTagName("franchise")[parseInt(document.getElementById('team').value) - 1].childNodes.length / 2) - 1);
playerScores.length = Math.round((xmlDoc.getElementsByTagName("franchise")[parseInt(document.getElementById('team').value) - 1].childNodes.length / 2) - 1);
playerIDs[Math.round(i / 2) - 1] = xmlDoc.getElementsByTagName("franchise")[parseInt(document.getElementById('team').value) - 1].childNodes[i].getAttribute('id');
}
for (var i = 1; i < xmlDoc.getElementsByTagName("franchise")[parseInt(document.getElementById('other').value) - 1].childNodes.length; i += 2) {
enemyIDs.length = Math.round((xmlDoc.getElementsByTagName("franchise")[parseInt(document.getElementById('other').value) - 1].childNodes.length / 2) - 1);
enemyIDs[Math.round(i / 2) - 1] = xmlDoc.getElementsByTagName("franchise")[parseInt(document.getElementById('other').value) - 1].childNodes[i].getAttribute('id');
}
step1();
});
};
})();
Turns out 000webhost was using a cached version of the website. It was using an older version of my code without that function. Fixed the problem by deleting and re-uploading my code to 000webhost.
I'm using the Phonegap file transfer plugin to upload a picture to the server. However I am getting error code: 1 (FileTransferError.FILE_NOT_FOUND_ERR). I've tested my server code with POSTMAN and I can upload and image successfully. However I get that error with the plugin. This is my code. The file is declared from "camera_image.src" and I can see the image when I append this to the src of an image on the fly. Any contributions? How is this code not perfect?
var fileURL = camera_image.src;
alert(fileURL);
var win = function (r) {
temp.push(r.response);
statusDom.innerHTML = "Upload Succesful!";
}
var fail = function (error) {
alert("An error has occurred: Code = " + error.code + " | Source:" + error.source + " | Target:" + error.target );
statusDom.innerHTML = "Upload failed!";
}
var options = new FileUploadOptions();
options.fileKey = "properties_photo";
options.fileName=fileURL.substr(fileURL.lastIndexOf('/') + 1);
options.headers = {
Connection: "close"
};
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
statusDom = document.querySelector('#status');
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100);
statusDom.innerHTML = perc + "% uploaded...";
console.log(perc);
} else {
if(statusDom.innerHTML == "") {
statusDom.innerHTML = "Loading";
} else {
statusDom.innerHTML += ".";
}
}
};
ft.upload(fileURL, encodeURI("http://cloud10.me/clients/itsonshow/app/image_upload_process.php"), win, fail, options);
I had this problem because of spaces in the path or filename of the file to be uploaded.
You need to ensure the plugin isn't being passed a fileURL with %20 in the URL.
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 + '>';