I need to receive fetch post from my wordpress to phonegap using wordpress rest api & json - wordpress

please i need help concerning phonegap and wordpress rest api.. I am a bit new to phonegap. i want to be able to receive my latest posts using GET etc and likely post from my mobile and also possibly perform other CRUD operation. thanks

I got it done already thanks much. I am posting my code here to help some out there and these community:
// Device Event Listener
document.addEventListener("deviceready", onDeviceReady, false);
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
var portfolioPostsContainer2 = document.getElementById("portfolio-posts-container2");
function onDeviceReady(){
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://mydomain/wp-json/wp/v2/posts?_embed');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
createHTML(data);
console.log(data);
// portfolioPostsBtn.remove();
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
}
function createHTML(postsData) {
var ourHTMLString = '';
var postid ='';
for (i = 0; i < postsData.length; i++) {
var posturl = postsData[i].link;
ourHTMLString +='<tr>';
ourHTMLString += '<td>' + '' + postsData[i].title.rendered + postsData[i].id+''+'</td>';
ourHTMLString += '<td>' + '<img width="100%" src ="' + postsData[i]._embedded['wp:featuredmedia']['0'].source_url + '" />' + ''+'</td>';
ourHTMLString += '<td>' + postsData[i].excerpt.rendered + '</td>';
ourHTMLString+= '</tr>';
}
portfolioPostsContainer.innerHTML = ourHTMLString;
}

Related

Marker change based on text/address input using HERE map

I'm using HERE map plugin and I need to change marker position based on address/text input. I was looking for an examples in internet, but nothing was found.
Is it even possible to do such thing, using this plugin? May be someone can point out, where do I have to look, or may be someone have working example? Any help appreciated.
Something similar is used in "Google Maps"
https://developers.google.com/maps/documentation/javascript/examples/places-searchbox
You can refer to the documentation for "Search for a Location based on an Address" can be found at https://developer.here.com/documentation/examples/maps-js/services/geocode-a-location-from-address
The working example is available at https://jsfiddle.net/4Lodwfb3/ - request a location using a free-form text input and display a marker on the map.
function geocode(platform) {
var geocoder = platform.getSearchService(),
geocodingParameters = {
q: '200 S Mathilda Sunnyvale CA'
};
geocoder.geocode(
geocodingParameters,
onSuccess,
onError
);
}
function onSuccess(result) {
var locations = result.items;
addLocationsToMap(locations);
addLocationsToPanel(locations);
}
function onError(error) {
alert('Can\'t reach the remote server');
}
var platform = new H.service.Platform({
apikey: window.apikey
});
var defaultLayers = platform.createDefaultLayers();
var map = new H.Map(document.getElementById('map'),
defaultLayers.vector.normal.map,{
center: {lat:37.376, lng:-122.034},
zoom: 15,
pixelRatio: window.devicePixelRatio || 1
});
window.addEventListener('resize', () => map.getViewPort().resize());
var locationsContainer = document.getElementById('panel');
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
var ui = H.ui.UI.createDefault(map, defaultLayers);
var bubble;
function openBubble(position, text){
if(!bubble){
bubble = new H.ui.InfoBubble(
position,
{content: text});
ui.addBubble(bubble);
} else {
bubble.setPosition(position);
bubble.setContent(text);
bubble.open();
}
}
function addLocationsToPanel(locations){
var nodeOL = document.createElement('ul'),
i;
nodeOL.style.fontSize = 'small';
nodeOL.style.marginLeft ='5%';
nodeOL.style.marginRight ='5%';
for (i = 0; i < locations.length; i += 1) {
let location = locations[i];
var li = document.createElement('li'),
divLabel = document.createElement('div'),
address = location.address,
content = '<strong style="font-size: large;">' + address.label + '</strong></br>';
position = location.position;
content += '<strong>houseNumber:</strong> ' + address.houseNumber + '<br/>';
content += '<strong>street:</strong> ' + address.street + '<br/>';
content += '<strong>district:</strong> ' + address.district + '<br/>';
content += '<strong>city:</strong> ' + address.city + '<br/>';
content += '<strong>postalCode:</strong> ' + address.postalCode + '<br/>';
content += '<strong>county:</strong> ' + address.county + '<br/>';
content += '<strong>country:</strong> ' + address.countryName + '<br/>';
content += '<strong>position:</strong> ' +
Math.abs(position.lat.toFixed(4)) + ((position.lat > 0) ? 'N' : 'S') +
' ' + Math.abs(position.lng.toFixed(4)) + ((position.lng > 0) ? 'E' : 'W') + '<br/>';
divLabel.innerHTML = content;
li.appendChild(divLabel);
nodeOL.appendChild(li);
}
locationsContainer.appendChild(nodeOL);
}
for (i = 0; i < locations.length; i += 1) {
let location = locations[i];
marker = new H.map.Marker(location.position);
marker.label = location.address.label;
group.addObject(marker);
}
group.addEventListener('tap', function (evt) {
map.setCenter(evt.target.getGeometry());
openBubble(
evt.target.getGeometry(), evt.target.label);
}, false);
map.addObject(group);
map.setCenter(group.getBoundingBox().getCenter());
}
geocode(platform);

AEM Site search query builder URL is not returning a different json

Am using AEM Site search component from core components. query builder URL is not returning a different json.
Once after searching with a text, am getting a json. Thereafter doing any search with new search text, am getting only the same json, not a new json. Only old response am getting in all search.
var request = new XMLHttpRequest();
if (self._hasMoreResults) {
var response;
var url = self._action + "?" + serialize(self._elements.form) + "&" + PARAM_RESULTS_OFFSET + "=" + self._resultsOffset;
request.open("GET", url, true);
request.onload = function() {
setTimeout(function() {
toggleShow(self._elements.loadingIndicator, false);
toggleShow(self._elements.icon, true);
}, LOADING_DISPLAY_DELAY);
if (request.status == 200 ) {
debugger;
var data = JSON.parse(request.responseText);
if (data.length > 0) {
self._generateItems(data, self._elements.results);
self._markResults();
toggleShow(self._elements.results, true);
} else {
self._hasMoreResults = false;
}
if (self._elements.results.querySelectorAll(selectors.item.self).length % self._properties.resultsSize > 0) {
self._hasMoreResults = false;
}
} else {
// error status
}
};
toggleShow(self._elements.loadingIndicator, true);
toggleShow(self._elements.icon, false);
request.send('');
}
};

needs to generate and update missing DocumentID and instanceID of the links of .indd Indesign files through extend script

I am using Mac with InDesign CC 219, and in my .indd file, some of the links are missing DocumentID and InstanceID, the below is the code I am using to get those details. If for any of the links, DocumentID and InstanceID are missing then I need to generate random DocumentID and InstanceID, and update the relevant links meta data. Is it possible through scripting, any directions please...
var doc = app.activeDocument;
for (var i = 0, len = doc.links.length; i < len; i++) {
var linkFilepath = File(doc.links[i].filePath).fsName;
var linkFileName = doc.links[i].name;
var xmpFile = new XMPFile(linkFilepath, XMPConst.FILE_INDESIGN, XMPConst.OPEN_FOR_READ);
var allXMP = xmpFile.getXMP();
// Retrieve values from external links XMP.
var documentID = allXMP.getProperty(XMPConst.NS_XMP_MM, 'DocumentID', XMPConst.STRING);
var instanceID = allXMP.getProperty(XMPConst.NS_XMP_MM, 'InstanceID', XMPConst.STRING);
}
$.level=0;
// Warn if there are no documents open.
if (!app.documents.length) {
alert('Open a document and try again.', 'Missing Document', false);
exit();
}
var doc = app.activeDocument;
// load XMP Library
function loadXMPLibrary() {
if (!ExternalObject.AdobeXMPScript) {
try {
ExternalObject.AdobeXMPScript = new ExternalObject('lib:AdobeXMPScript');
} catch (e) {
alert('Failed loading AdobeXMPScript library\n' + e.message, 'Error', true);
return false;
}
}
return true;
}
// Check all link statuses are be ok.
function linksStatusCheck(doc) {
for (var i = 0, len = doc.links.length; i < len; i++) {
if (doc.links[i].status !== LinkStatus.NORMAL) {
alert('The status of all links must be OK \nPlease update link status ' +
'via the Links panel and try again', 'Link Status', true);
exit();
}
}
return true;
}
function randomString(length, chars) {
var randomGenStr = '';
for (var i = length; i > 0; --i) {
randomGenStr += chars[Math.floor(Math.random() * chars.length)];
}
return randomGenStr;
}
function randomString(length) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var k = 0; k < length; k++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
function checkLinksXMP(doc) {
for (var i = 0, len = doc.links.length; i < len; i++) {
var linkFilepath = File(doc.links[i].filePath).fsName;
var linkFileName = doc.links[i].name;
var xmpFile = new XMPFile(linkFilepath, XMPConst.FILE_INDESIGN, XMPConst.OPEN_FOR_UPDATE);
var allXMP = xmpFile.getXMP();
// Retrieve values from external links XMP.
var documentID = allXMP.getProperty(XMPConst.NS_XMP_MM, 'DocumentID', XMPConst.STRING);
var instanceID = allXMP.getProperty(XMPConst.NS_XMP_MM, 'InstanceID', XMPConst.STRING);
// Useful for testing purposes....
// Log properties for each link to the console.
// Notify user when XMP is missing...
var docMissingCnt = 0;
var insMissingCnt = 0;
if (!documentID && !instanceID) {
alert('Link missing DocumentID and InstanceID\n' +
'Name: ' + linkFileName + '\n\n' +
'Path: ' + linkFilepath, 'Missing XMP', true);
docMissingCnt++;
insMissingCnt++;
} else if (!documentID) {
alert('Link missing DocumentID\n' +
'Name: ' + linkFileName + '\n\n' +
'Path: ' + linkFilepath, 'Missing XMP', true);
docMissingCnt++;
} else if (!instanceID) {
alert('Link missing InstanceID\n' +
'Name: ' + linkFileName + '\n\n' +
'Path: ' + linkFilepath, 'Missing XMP', true);
insMissingCnt++;
}
if(docMissingCnt > 0) {
documentID = randomString(32);
allXMP.setProperty(XMPConst.NS_XMP_MM, 'DocumentID', documentID);
var documentIDNew = allXMP.getProperty(XMPConst.NS_XMP_MM, 'DocumentID', XMPConst.STRING);
$.writeln('DocumentID - New : ' + documentIDNew);
docMissingCnt = 0;
}
if(insMissingCnt > 0) {
instanceID = randomString(32);
allXMP.setProperty(XMPConst.NS_XMP_MM, 'InstanceID', instanceID);
var instanceIDNew = allXMP.getProperty(XMPConst.NS_XMP_MM, 'InstanceID', XMPConst.STRING);
$.writeln('InstanceID - New : ' + instanceIDNew);
insMissingCnt = 0;
}
}
}
if (loadXMPLibrary() && linksStatusCheck(doc)) {
checkLinksXMP(doc);
}

Template.templatename.rendered and template instances

Whats the best way to interact with an instance of a template? I have a gallery of html5 videos I want to play when they are scrolled into view and stopped when they are outside the browser window.
the below code works perfectly for one video, but when I have multiple videos the code changes all videos at the same time, is_playing is set to the exact same value for multiple videos.
these are possible related discussion but I couldn't quite figure it out:
Let helpers access template instance #1529, Need way to reactively depend on data context / template arguments
Template.showcaseVideo.rendered = function () {
var video_id = this.data._id;
var video = document.getElementById(video_id);
var is_playing = false;
$(window).on("scroll", '', function (event) {
if(isScrolledIntoView($('#'+video_id)) && !is_playing) {
video.play();
is_playing = true;
console.log( "playing " + video_id);
} else if (is_playing) {
video.pause();
is_playing = false;
console.log( "stopped " + video_id);
}
});
}
Try to assign is_playing variable to instance of template:
Template.showcaseVideo.rendered = function () {
var self = this;
self.is_playing = false;
$(window).on("scroll", '', function (event) {
var video_id = self.data._id;
var video = document.getElementById(video_id);
var is_playing = self.is_playing;
if(isScrolledIntoView($('#'+video_id)) && !is_playing) {
video.play();
is_playing = true;
console.log( "playing " + video_id);
} else if (is_playing) {
video.pause();
is_playing = false;
console.log( "stopped " + video_id);
}
});
}

MVC 4 - 500 error on JSON call

I have started using VS2012 (Yes about time). I have a MVC 4 app.
Im making a JSON call to get data from DB to render in html.
But Im getting a 500 Internal Server error I can see in Fiddler.
Im not sure how to debug this because I cant find where to
see the C# exception if that is what the issue is.
So Im calling getRecipe in javascript.
public JsonResult GetRecipe(int rid)
{
var recipe = _rep.GetRecipe(rid);
return Json(recipe, JsonRequestBehavior.AllowGet);
}
My script is
var dataService = new function () {
var serviceBase = '/Recipes/'
getRecipesList = function (callback) {
$.getJSON(serviceBase + 'GetRecipesList', {}, function (data) {
callback(data);
});
};
getRecipe = function (rid, callback) {
$.getJSON(serviceBase + 'GetRecipe', {rid:rid}, function (data) {
callback(data);
});
};
return {
getRecipesList: getRecipesList,
getRecipe: getRecipe
};
} ();
var renderer = new function () {
renderList = function () {
dataService.getRecipesList(renderListDiv);
},
renderListDiv = function (recipes) {
var listDiv = $('#listdiv');
listDiv.html("");
$(recipes).each(function (index) {
var table = '<table>';
table += ('<tr><td><a class="recipeLink" href="#recipeList-' + this.RecipeID + '">' + this.RecipeTitle + '</a></td></tr>');
table += '</table>';
listDiv.append(table);
});
},
selectedRecipe = function (anchor) {
var href = $(this).attr("href");
var rid = href.split("-")[1];
dataService.getRecipe(rid, renderRecipe);
};
renderRecipe = function (recipe) {
var recipeDiv = $('#recipediv');
var html = '<h1>' + recipe.RecipeTitle + ' (' + recipe.RecipeID + ')</h1>';
html += '<h4>Preparation Time: ' + getTimeString(recipe.PrepTime) + '</h4>';
html += '<h4>Cooking Time: ' + getTimeString(recipe.CookTime) + '</h4>';
var count = recipe.Ings.length;
var colmax = Math.ceil(count / 2);
var colleft = 0;
var colright = colmax;
html += '</br><table id="ingredientstable">';
for (colleft = 0; colleft < colmax; colleft++) {
html += '<tr>';
html += '<td>' + recipe.Ingredients[colleft].Units + ' ' + recipe.Ingredients[colleft].Measure + ' ' + recipe.Ingredients[colleft].IngredientName + '</td>';
if(colright < count)
html += '<td>' + recipe.Ingredients[colright].Units + ' ' + recipe.Ingredients[colright].Measure + ' ' + recipe.Ingredients[colright].IngredientName + '</td>';
colright += 1;
html += '</tr>';
}
html += '</table>';
html += '<h4>Method</h4>';
html += '<p>' + recipe.Method + '</p>';
recipeDiv.html(html);
numingredients = 0;
editorForm.loadEditor(recipe);
};
clearRecipe = function () {
$('#recipediv').html("");
};
getTimeString = function (time) {
if (time < 60)
return time + ' min';
return time / 60 + ' hours'
};
changeFont = function () {
$('body').css("font-family", "Comic Sans MS");
};
return {
renderList: renderList,
selectedRecipe: selectedRecipe,
changeFont: changeFont,
clearRecipe: clearRecipe,
};
}();
The browser's developer tools might be a good place to get some additional information. In Chrome you can press F12 to bring up the dev tools window. Click on the network tab and then fire off your ajax call. You will see the failed request highlighted in red. If you click on it you will see the error that has been returned from mvc.
I have provided a screenshot in this question: Ajax call with a 'failed to load resource : the server responded with a status of 500'

Resources