I really really need your help pls. I have been battling with these for days and my project is stucked. Your help will really be appreciated.
I have 3 pages.
Page one receives my data, and html formatted version is created. it is a loop and it returns 10 posts.
===
page 2 is the html page that displays the 10 post
====
page 3. the posts at page 2 are just featured image and excerpt and title with url... to read full, click it and go to page 3 ...
Page 3 uses the unique id of each posts to display the full post:
my question: how do i pass each post id to page 3 for full content view.
i tried to store the id generated in page 1 to localstorage, but bcos its a loop ... ONLY THE LAST ONE IS STORED..
my code..
Page 1 - script page receives data
document.addEventListener("deviceready", onDeviceReady, false);
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
function onDeviceReady(){
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://myurl/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);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
}
Page 1 still: CreateHTMl create thru a loop
function createHTML(postsData) {
var ourHTMLString = '';
for (i = 0; i < 1; i++)
{
var posturl = postsData.link
ourHTMLString +='<tr>';
ourHTMLString += '<td>' + '' + postsData[i].title.rendered + ''+'</td>';
ourHTMLString += '<td>' + '<img width="100%" src ="' + postsData[i]._embedded['wp:featuredmedia']['0'].source_url + '" />' + ''+'</td>';
ourHTMLString += '<td>' + postsData[i].excerpt.rendered + localStorage.setItem("postid",postsData[i].id)+'</td>';
//i tried to store each id in a localstorage but only the last one remains
ourHTMLString+= '</tr>';
} portfolioPostsContainer.innerHTML = ourHTMLString;
}
page two uses this to display ourHTMLString
<div id="portfolio-posts-container"></div>
page 3 Need each post id.
function onDeviceReady(){
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://myurl/wp-json/wp/v2/posts/'+mypostid+'?_embed=true')
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
// createHTML(data); '+mypostid)
console.log(data);
var ourHTMLString = '';
Each post has its generated id from the api, how do i pass it to page 3 for displaying individual post
Although I'm a little confused as re the overall structure of this system, you could pass the id as a query string parameter.
View post 123
This can be parsed using location.search within JavaScript:
var postMatch = /id=(\d+)/.exec(location.search);
if(postMatch) {
var postId = postMatch[1];
// Load post postId...
} else {
// No post was passed
}
Related
I'm kinda new to php + javascript.
I have set up "cute file browser" to look at a shared folder on my computer.
it works fine displays all files & folders no problem.
Now im trying to use OMDB to search for movie posters and then display them for each movie name.
Currently it works but only with the first movie title. when inspecting the element in FF it does show all the other posters but only within the first
This is the code i made for the OMDB...
var filmName;
var realName;
filmName = finfo;
realName = filmName.split('.')[0];
var omdbUrl = "http://www.omdbapi.com/?t=" + realName;
$.ajax({
url: omdbUrl,
//force to handle it as text
dataType: "text",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//now json variable contains data in json format
//let's display a few items
document.getElementById("folders").innerHTML += "<img id='imgposter' class='imgPoster' src='" + json.Poster + "'></img>";
}
});
And this is the code for displaying my movie folders:
if(scannedFolders.length) {
scannedFolders.forEach(function(f) {
var itemsLength = f.items.length,
name = escapeHTML(f.name);
if(itemsLength) {
icon = '<span class="icon folder full"></span>';
}
if(itemsLength == 1) {
itemsLength += ' item';
}
else if(itemsLength > 1) {
itemsLength += ' items';
getPoster(name);
}
else {
itemsLength = 'Empty';
}
var folder = $('<li id="folders" class="folders"><span class="name">' + name + '</span> </li>');
folder.appendTo(fileList);
});
}
This is the error i get
As i said i am new here. if anyone could give me any tips would be great thanks
I have a mobile app.
It consists of 2 screens. The first is for capturing user
credentials and the 2nd is for displaying data.
The idea is to collect the credentials on screen 1.
Then make an ajax call with the credentials to get data and present it on
screen 2 as a series of links.
Then allow the user to touch a link on screen 2. This will return the link data to the javascript and pass it to the ajax call and get more data - THEN delete all the data on screen 2 and repopulate it with the new data.
First thing I want to find out: is showing a page with mobile.changePage(), populating it, deleting the contents and then repopulating it (without another call to mobile.changePage()) a reasonable thing to do?
I'm having a problem and I think its related to how I'm using onclick in the <a>
Each time I display the most recently received data, I want to display it in an <a>. I write each onclick to call the getData routine passing it information to determine the next ajax AND whatever is being displayed in the <a>. The only way I could figure out to access that was in onclick.
Is there a better way?
I'm able to display the results of the first ajax call just fine. But things get weird with the 2nd, 3rd etc.
Sometimes I'll touch a link and I'll progress thru the screens as I expect.
Sometimes I'll touch an <a> on the 1st result screen, the 2nd result screen will display and then (without me selecting data from the 2nd screen) the 3rd screen will display.
I've looked at the logs and the getData() routine is being executed.
What could be causing this? Am I somehow not destroying all the <a> properly? Am I using onclick in a fashion its not designed for? Should I be using buttons styled to look like links instead of <a>
Here's my code:
"use strict";
var app = {
onDeviceReady: function() {
$('#startButton').click(function(){
app.getDeptsForUser();
});
},
getDeptsForUser: function(){
var parms = new Object();
parms.userName = assignedUser;
app.getData(JSON.stringify(parms),"ENDPOINT1", "Departments");
$.mobile.changePage("#index", { transition: 'slide' });
},
getData: function(paramStr, endpoint, displayHeader){
var paramStrObj = JSON.parse(paramStr);
var serverName = server + ":" + port;
var encoded = Base64().encode(paramStrObj.userName + ':' + pass);
var authType = 'Basic ' + encoded;
var option = endpoint+"?action=start¶ms=" + paramStr;
var URL = serverName + "/rest/bpm/wle/v1/service/"+option;
$.ajax({
url: URL,
type: "POST",
crossDomain: true,
jsonp: "callback",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", authType);
},
success: function (result) {
console.log("MobileMockUp getData() ajax success result="+JSON.stringify(result));
if (endpoint === "ENDPOINT1"){
app.displayData(paramStr, endpoint,"Departments", result.data.data.depts.items);
}
else if (endpoint === "ENDPOINT2"){
app.displayData(paramStr, endpoint,displayHeader, result.data.data.checklists.items);
}
else if (endpoint === "ENDPOINT3"){
app.displayData(paramStr, endpoint,displayHeader, result.data.data.checks.items);
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Unable to retrieve '+displayHeader);
},
});
},
displayData: function(currParms,currEndPt, headerText, list){
var nextEndpt;
var nextHeaderText;
var currParmsObj = JSON.parse(currParms);
if (currEndPt === "MD#getDeptsForUser"){
nextEndpt = "MD#getCheckLists";
nextHeaderText = "Check Lists";
}
else if (currEndPt === "MD#getCheckLists"){
nextEndpt = "MD#getChecks";
}
var htmlListString="";
var parmObj;
var newLink;
$('#headerText').text(headerText);
for (var i = 0; i < list.length; i++){
parmObj = new Object();
if (currEndPt === "ENDPOINT1"){
parmObj.userName=currParmsObj.userName;
parmObj.dept=list[i];
}
else if (currEndPt === "ENDPOINT2"){
parmObj.userName=currParmsObj.userName;
parmObj.dept=currParmsObj.dept;
parmObj.checklist=list[i];
}
else if (currEndPt === "ENDPOINT3"){
nextHeaderText = list[i];
}
var str = JSON.stringify(parmObj);
str = str.toString().replace(/"/g, '\\"');
newLink = "<a style='background:#ffffff;padding-top:5%;border-top: thin solid black; display:block;font-size:12px;font-weight:normal;color:#000000;text-decoration: none;' href='#' onclick='app.getData(\""+str+"\",\""+nextEndpt+"\",\""+nextHeaderText+"\")'><pre>" + list[i] + " </pre></a><br>";
htmlListString=htmlListString+newLink;
}
$('#taskListUL').empty();
$('#taskListUL').append(htmlListString);
}
};
Could this be multiple binding?
i figured out it was multiple bindings
I am trying to make an image take a value in as a source, after the image tag (and a related radio button) has been created using JavaScript. I have discerned the following from testing and alert outputs:
If the image src is provided at the creation of the image tag using an exact filepath, it will show the image correctly (e.g. src='images/0.jpg'). However, this is not helpful since I need it to work for any given image, not a specific one.
If the image src is provided at the creation of the image tag using a variable containing a filepath, it fails to generate the image tag or the radio button at all (e.g. src='" + result + '").
NOTE: The last example is not present in the code below. The result was found by moving the '$.post' section to the line directly under the 'out +=' line within the for loop.
If the image src is left blank at the creation of the image tag, the image tag and radio button are created, though the image is blank as expected. If I then try to use 'getElementByID(imgID).src' to change the image source after this, it fails to do anything. ('imgID' here is an example, not what the code says).
On top of the above, using alerts and dumping info into divs indicate that the comicID is being correctly posted, and the filepath of the image src is definitely being found, and is being copied into the variable 'result' correctly, even one line before the creation of the tag or the attempt to edit it using 'getElementById'.
At this point I'm stumped, I don't know what could logically be stopping the src from reading in.
--
Javascript:
<script>
// Loads the user's comic list from the database.
function loadComic()
{
var xmlhttp = new XMLHttpRequest();
var getID = '<?php echo $_SESSION["userID"]; ?>';
var url = "loadCom.php?userID="+getID;
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
loadComicJSON(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
// JSON parsing for 'loadComic'.
function loadComicJSON(response)
{
var arr = JSON.parse(response);
var i;
var out = "";
document.getElementById("loadList").innerHTML="";
if (arr.length == 0)
{
//Irrelevant manipulation of HTML.
}
else
{
out+="<br>";
for(i = 0; i < arr.length; i++)
{
out += "<hr><br><img name = '" + ('cm' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='' ><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br>";
}
document.getElementById("loadList").innerHTML=out;
for(j=0; j< arr.length; j++)
{
tempID = (arr[j].comicID);
$.post("getCover.php", {comicID:tempID}, function(result)
{
document.getElementById("loadList").innerHTML+="<p>"+result+"</p>";
document.getElementById("com"+arr[j].comicID).src = result;
}
);
}
}
}
</script>
PHP (getCover.php):
<?php
if (isset($_POST["comicID"]))
{
include_once('includes/conn.inc.php');
$checkID = $_POST["comicID"];
$query = ("SELECT pageLocation FROM page WHERE comicID = '$checkID' ORDER BY pageNum");
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
print_r($row["pageLocation"]);
}
else
{
$checkID = null;
echo "Error. No comic found.";
}
?>
To my knowledge, loadList.php is working perfectly, so I didn't list its code to keep things relevant.
I copied your code and tweaked it a little so I could run it without the web services and it works great. Here is the HTML page I created:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script>
// JSON parsing for 'loadComic'.
function loadComicJSON()
{
var arr = [{comicID: 1},{comicID: 2},{comicID: 3}];
var result = "monkey.jpeg";
var i;
var out = "";
document.getElementById("loadList").innerHTML="";
if (arr.length == 0)
{
//Irrelevant manipulation of HTML.
}
else
{
out+="<br>";
for(i = 0; i < arr.length; i++)
{
out += "<hr><br><img name = '" + ('cm' + arr[i].comicID) + "' id='" + ('com' + arr[i].comicID) + "' onclick='resizeThumb(this)' height='100px;' src='' ><input name='comicList' type='radio' id='" + arr[i].comicID + "' value='" + arr[i].comicID + "'>" + arr[i].comicName + " </option><br><br>";
}
document.getElementById("loadList").innerHTML=out;
for(j=0; j< arr.length; j++)
{
var imgSrc;
tempID = (arr[j].comicID);
document.getElementById("loadList").innerHTML+="<p>"+result+"</p>";
document.getElementById("com"+arr[j].comicID).src = result;
}
}
}
</script>
</head>
<body>
<div id="loadList"></div>
<button onclick="loadComicJSON()">Try it</button>
</body>
</html>
As you can see, I created an array of JSON objects that hold the comicID and am statically creating the image as 'monkey.jpeg'.
The code works so there is either an issue with the 'response' that you pass into your loadComicJSON method or the result from your POST method.
Add a couple of console.log statements and look at the two values I mentioned and you will likely see the issue.
Solved the issue myself. It turned out that the $.post needed to be $.get and that it needed to technically be outside of a loop (i.e. in its own function) to work properly. Works fine now after that and a couple minor tweaks.
I have one image saved in Notes with every form in my CRM Online 2013 custom entity. I am using the following code to query the image and show it in an Image tag in a Web Resource on the form. For debugging purposes I was calling the following code through a button, but I want this process of querying the Notes and displaying the image in the web resource to be automatic when the form load. Here is my code:
<html><head><meta charset="utf-8"></head>
<body>
<img id="image" src="nothing.jpg" style="width: 25%; height: auto;" />
<script type="text/javascript">
$(windows).load(function()
{
var recordId = window.parent.Xrm.Page.data.entity.getId();
var serverUrl = Xrm.Page.context.getServerUrl().toString();
var ODATA_ENDPOINT = "XRMServices/2011/OrganizationData.svc";
var objAnnotation = new Object();
ODataPath= serverUrl+ODATA_ENDPOINT;
var temp= "/AnnotationSet?$select=DocumentBody,FileName,MimeType,ObjectId&$filter=ObjectId/Id eq guid'" + recordId + "'";
var result =serverUrl + ODATA_ENDPOINT + temp;
var retrieveRecordsReq = new XMLHttpRequest();
retrieveRecordsReq.open('GET', ODataPath + temp, false);
retrieveRecordsReq.setRequestHeader("Accept", "application/json");
retrieveRecordsReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
retrieveRecordsReq.onreadystatechange = function ()
{
if (this.readyState == 4 /* complete */)
{
if (this.status == 200)
{
this.onreadystatechange = null; //avoids memory leaks
var data = JSON.parse(this.responseText, SDK.REST._dateReviver);
if (data && data.d && data.d.results)
{
SuccessFunc(JSON.parse(this.responseText, SDK.REST._dateReviver).d.results);
}
}
else
{
alert(SDK.REST._errorHandler(this));
}
}
};
var x = new XMLHttpRequest();
x.open("GET", result, true);
x.onreadystatechange = function ()
{
if (x.readyState == 4 && x.status == 200)
{
var doc = x.responseXML;
var title = doc.getElementsByTagName("feed")[0].getElementsByTagName("entry")[0].getElementsByTagName("content")[0].getElementsByTagName("m:properties")[0].getElementsByTagName("d:DocumentBody")[0].textContent;
document.getElementById('image').src ="data:image/png;base64,"+title;
}
};
x.send(null);
});
</script>
</body></html>
I have removed the button tag..now I want this the query to happen on page Load, but nothing happens when I refresh the form. In my opinion the function loads before the annotation loads. Is there a way to make it wait and load the last?
If you want to wait for the parent window to load I think $(windows).load(myFunction); should do the trick.
Maybe $ is undefined because you did not add jQuery to your webressource.
There are also a few little mistakes and unattractive things:
First:
You will get a wrong server url.
If you want to access the Xrm-object in a webresource you always have to use window.parent.Xrm or you put it in a variable var Xrm = window.parent.Xrm;
For example:
var Xrm = window.parent.Xrm;
var recordId = Xrm.Page.data.entity.getId();
var serverUrl = Xrm.Page.context.getServerUrl().toString();
Second:
The ODataPath variable is not declared. Use var ODataPath= serverUrl+ODATA_ENDPOINT; instead. By the way the value of the ODataPath has nothing to do with OData. It is more the REST-Endpoint of Dynamics CRM.
My script would look like this:
var Xrm, recordId, serverUrl, restEndpointUrl, odataQuery, fullRequestUrl, xmlRequest;
Xrm = window.parent.Xrm;
recordId = Xrm.Page.data.entity.getId();
serverUrl = Xrm.Page.context.getServerUrl().toString();
restEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc";
^ I think a '/' was missing there
odataQuery = "/AnnotationSet?$select=DocumentBody,FileName,MimeType,ObjectId&$filter=ObjectId/Id eq guid'" + recordId + "'";
fullRequestUrl = restEndpointUrl + odataQuery;
I also dont understand why you use the second HttpRequest.
All of this code is not tested.
I will start off by saying I am new to Javascript and JQuery. What I want to accomplish is have a submit button on an HTML page that will call the dbQuery function in my .js file that will print the value of variables to the screen and then add them into a MySQL database.
I need to use the JavaScript variable selectedVisibleValue that is defined in my first function dbQuery The reason I want to do this is because I have four drop downs, three of which are hidden drop downs that are only shown depending on the first non hidden dropdown, only one of the hidden drop downs is ever visible.
I want to work with these variables in my PHP page formPage to do the Database functions. My code is below I want to add the testing1 function into the dbQuery function.
I have tried just copying and pasting it into the dbQuery function but it does not work. I am not trying to work with the selectedVisibleValue in the code below. I am just trying to do some testing with some bogus variables.
var dbQuery = function(){
var description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
var selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
var selectedVisibleValue = $(".unitDropDowns select:visible").val();
document.getElementById("descriptionSummary").innerHTML = "<h3>Description</h3>" + "<p>" + description + "</p>";
document.getElementById("equipmentRan").innerHTML = "<h3>Equipment Ran </h3>" + "<p>" + selectedEquip1 + "</p>" + "<h3>Unit Number</h3>" + "<p>" + selectedVisibleValue + "</p>";
document.getElementById("equipmentRan").style.display = "block";
document.getElementById("descriptionSummary").style.display = "block";
}
var testing1 = function() {
$.get(
"formPage.php",
{paramOne : 123, paramX : 'abc'},
function(data) {
document.getElementById("equipmentRan").innerHTML = ('page content: ' + data);
}
);
}
//cache references to static elements
var jobDescription = $('#jobDescription')
, selectedEquip = $('#equipmentList')
, descriptionSummary = $('#descriptionSummary')
, equipmentRan = $('#equipmentRan')
;
function dbQuery(){
//gather params
var params = {
jobDescription : jobDescription.val(),
selectedEquip1 : selectedEquip.val(),
selectedVisibleValue = $(".unitDropDowns select:visible").val()
}
//show summary
descriptionSummary.html('<h3>Description</h3><p>'+description+'</p></h3>').show();
equipmentRan.html('<h3>Equipment Ran</h3><p>'+selectedEquip1+'</p><h3>Unit Number</h3><p>'+selectedVisibleValue+'</p>').show();
//do a get
$.get('formPage.php',params,function(data) {
equipmentRan.html('page content: ' + data);
}
}
jsFiddle DEMO
Passing variables between functions might come in useful for your project.
HTML:
<div id="theBox"></div>
<button>Press Me</button>
JS
$(document).ready(function() {
// This is some other Do More function, defined prior to the next variable function.
// This is your .get() request.
function doMore(target){
// For the incomming targer, add a class style of a larger font.
$(target).css('font-size', 30);
}
// The main function.
var dbQuery = function() {
// Show dynamic text on the HTML page.
var extra = $('#theBox').html('Dynamic Text Results');
// Run some other function, also... send the private variable in use.
doMore(extra);
};
// The submit button.
$('button').on('click', function() {
// Start the function.
dbQuery();
});
});
Here is the working code:
function dbQuery() {
window.description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
window.selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
window.selectedVisibleValue = $(".unitDropDowns select:visible").val();
testing1();
}
function testing1() {
$(document).ready(function() {
$.get(
"formPage.php",
{paramOne : window.selectedVisibleValue, paramX : window.description, paramY : window.selectedEquip1},
function(data) {
document.getElementById("equipmentRan").innerHTML = (data);
}
);
});
}