I am creating a button in javascript (I can't create it using HTML - system limitation) and I want this button to go to a certain url (REST - getting JSON file). Afterwards, I'd like to display an alert with the value from that file and/or save the value from JSON file on a page where the button is placed. So far, I figured how to call the REST URI. Could anyone help me move forward with that?
<script>
oraclecrmod.onReady(function() {
if(oraclecrmod.ctx.isObject("Account") && oraclecrmod.ctx.isDetailPage()) {
var on_click = function httpGet("https://example.crmondemand.com/OnDemand/user/Rest/027/Accounts")
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "https://example.crmondemand.com/OnDemand/user/Rest/027/Accounts", false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
// Read the "Test Read" button on the main Account TitleBar
var tb = oraclecrmod.getTitleBar("AccountFormTB");
var bt = oraclecrmod.createButton({
id:"TestBtn",
text:"Test Read",
parent:tb
});
bt.on("click",on_click);
}
});
</script>
Is this better? How can I improve it? It still doesn't work.
Once you navigate to another page, your current JavaScript will stop executing. The current Document gets unloaded when you navigate pages.
See the HTML5 spec for more details: http://www.w3.org/TR/html5/browsers.html#the-location-interface
Related
I want to view and manipulate Javascript localStorage information on a PHP page using PHP. I have gotten pretty far with this, but I'm not where I need to be. I'm using PHP 7.3 and vanilla JS.
I have AJAX POSTing the data to a PHP processing page (not the one that calls the javascript function). However, I need to access the POST variable on the page that called the javascript. How can I pass the information back without a click?
The page wishlist.php contains a link to the js file and <div id="temporary_wishlist"></div>.
Javascript called from wishlist.php:
window.addEventListener("load", function() {
loadWishlist();
});
// get wishlist contents
function loadWishlist() {
var items = wishlistStorage.data.items.join("%20");
var item_notes = wishlistStorage.data.item_notes.join("%20");
var comments = wishlistStorage.data.comments;
var wishlistRequest;
var response = null;
if(window.XMLHttpRequest) {
wishlistRequest = new XMLHttpRequest();
} else {
wishlistRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
wishlistRequest.onreadystatechange = function() {
if(wishlistRequest.readyState == 4 && wishlistRequest.status == 200) {
response = wishlistRequest.responseText;
document.getElementById("temporary_wishlist").innerHTML = response;
}
}
wishlistRequest.open("POST", "/wishlist-processor.php", true);
wishlistRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
wishlistRequest.send("wishlist_items=" + encodeURIComponent(items)
+ "&wishlist_itemnotes=" + encodeURIComponent(item_notes)
+ "&wishlist_comments=" + encodeURIComponent(comments));
}
Given the above, I have access to $_POST['wishlist_items'] inside wishlist-processor.php. Whatever I output inside of wishlist-processor.php is visible to the visitor on wishlist.php inside <div id="temporary_wishlist"></div>. It is not, however, visible in the Console.
On wishlist.php, I want to load the information into a PHP variable so I can send it to a MySQL query. If I could just POST to self like I do with form validation I would have access to $_POST['wishlist_items'] from wishlist.php. I already tried setting the URL in the open("POST", URL, true) function to _self or wishlist.php, and that didn't work for me.
I know it's suggested that I use Fetch, but I'm already overwhelmed learning new things I want to understand AJAX better. Also, Fetch doesn't work on Firefox Android.
I'm building a web site which lets users post requests on site and others to respond. I have built an app-like form to collect information. In that form I need to display 3 pages.
So I have created one page with the from and and a JavaScript file to handle these 3 pages. Other form-pages are designed separately (HTML only).
I'm planning to load the other two pages into that 1st page with XMLHttpRequest and it works.
But I need to take 3rd page into the 1st form-page (display the 3rd page of form) and change the innerHTML of that 3rd page. I tried it with
function setFinalDetails() {
document.getElementById("topic").innerHTML = object1.start;
}
//creating a XMLHttpObject and sending a request
//requiredPage is the page we request.
//elementId is the element we need to display
function requestAPage(requiredPage) {
selectElementId(requiredPage);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
m = xhttp.responseXML;
y = m.getElementById(elementId).innerHTML;
document.getElementById("hireForm").innerHTML = y;
//m is a global variable
//m is the object recieved from XMLHttpRequest.
//it is used to change the innerHTML of itself(m) and display.
//y is displaying the 3rd page in the form-page one("id =hireForm")
return m;
}
};
xhttp.open("GET", requiredPage, true);
xhttp.responseType = "document";
xhttp.send();
}
but that gives an error:
Cannot set a .innerHTML property of null
find my work on https://github.com/infinitecodem/Taxi-app-form.git
It it hard to help you in detail because we do not have a way to reproduce your error and test your code. I can suggest you to use a service like plunker to share your code. I do not know if this service will support to do some xhrRequest on other files in its working tree, you can try.
Your error message seems to reveal that one of your document.getElementById(...) is returning null instead of the html elt you want (so the id do not exist in the page).
But again without a way to test, it is hard to help you more sry. I really encourage you to try to share a link to a service (like plunker, etc) that will help others to play with your use case.
I have some custom script that adds the latest note value to a hidden text field, and the hidden text field is subsequently displayed in one of my views for the entity. When I click save and close after adding a new note, the view does not update with the newest note since the form was not refreshed. What can I do so that the form will be refreshed if the user clicks on save and close?
EDIT: #Arthur For some reason, I cannot add a comment to your post.
Anyhow, I tried as you have suggested. When I tried to click on "save" alone, the form refreshed and the value returned was true, so the flag was tripped. However, when I tried the same with "save and close" the form did not refresh, and consequently the flag was not tripped. This is leading me to assume that I must refresh the form in order for the view to update.
EDIT 2: Here is the code that retrieves the information.
function GetLatestNote() {
var req = new XMLHttpRequest();
req.open("GET", encodeURI(Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/AnnotationSet?" + "$select=NoteText&$filter=ObjectId/Id eq guid'" + Xrm.Page.data.entity.getId() + "'&$orderby=CreatedOn desc&$top=1"), true);
req.setRequestHeader('Accept', 'application/json');
req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
req.onreadystatechange = function() {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var note = JSON.parse(req.responseText).d;
var results = note.results;
var NoteText = results[0].NoteText;
var newnote = Xrm.Page.getAttribute("new_lastcomment").setValue(NoteText);
}
}
};
req.send();
}
new_lastcomment is the hidden field. What I am trying to do now is that if the user clicks on save and close, to stop the save event, reload the page, and use the script to close the form. Here is the code for that function:
function save(executionObj) {
var savestate = executionObj.getEventArgs.getsavemode();
if (savestate == 2) {
executionObj.getEventArgs().preventDefault();
window.location.reload(true);
Xrm.Page.data.entity.save("saveandclose");
}
}
What happens when I test this code however is that I get the following message when I attempt to save and close :
There was an error with this field's customized event.Field: crmForm, Event: onsave, Error: Object does not support property or method 'getsavemode'
However, once I click ok, the script closes and the view is updated as I want it! But now there is a problem because I do not want this error message popping up every time I hit save and close. To add more depth here, I run both of these function as an onsave event, and for the save function, I have "Pass execution context as first parameter" checked. I tried to run it without checking this box, and got an error that the value was undefined, but once again, after I clicked ok, the form would close and the view updated. Why is this error coming up now?
EDIT: #Arthur The form is now refreshing, but I am still getting the same error message that I was getting before.
Typically a "isdirty" flag gets triggered whenever there is a change to the form.
This flag lets CRM know that there have been modifications to the form in question, and to make sure to display the "There are unsaved changes" dialog box.
My guess is that this flag is not being tripped when you update the textbox.
if you put
console.log(Xrm.Page.data.entity.getIsDirty())
in your javascript and check out the resulting code, does it say true or false?
If it's false you'll need to set the dirty flag using
Xrm.Page.data.setFormDirty()
EDIT: I don't think this is the issue any more. refer to below.
After you set the value of the text box try executing this:
Xrm.Page.data.refresh(save);
That should save it, that way the save and close button doesn't have to.
After doing some research, I have found out what the issue was.
In my function GetLatestNote(), I was retrieving the data from the note field asynchronously. This may have resulted in the control returning to the user before the code was executed and the field was populated on the form. Therefore, this resulted in the information not being brought over when I clicked save and close.
Here is the code with the JSON code being executed synchronously, for those who may need it in the future. Works like a charm :)
function GetLatestNote() {
var req = new XMLHttpRequest();
req.open("GET", encodeURI( Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/AnnotationSet?" + "$select=NoteText&$filter=ObjectId/Id eq guid'"+Xrm.Page.data.entity.getId()+"'&$orderby=CreatedOn desc&$top=1"), false);
req.setRequestHeader('Accept', 'application/json');
req.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
req.send(null);
var note = JSON.parse(req.responseText).d;
var results = note.results;
var NoteText = results[0].NoteText;
var newnote = Xrm.Page.getAttribute("new_lastcomment").setValue(NoteText);
}
#Arthur thank you very much for trying to help me out. I truly appreciated it!
My need is to get response code the web page using java script. I have to inject this java script in current loading page and get the response code. Is that possible?
function httpGet(){
var url = "test.aspx";
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false);
xmlHttp.send( null );
alert(xmlHttp.responseText);}
Try this one.
Finally i wrote a IE browser extension to return responsecode once the page is loaded.
Written BHO using VC++ refering
http://msdn.microsoft.com/en-us/library/bb250489(v=vs.85).aspx
added listener for events OnDocumentComplete (DISPID_DOCUMENTCOMPLETE),OnNavigateError(DISPID_NAVIGATEERROR) of DIID_DWebBrowserEvents2
now i can able to get pointer of IWebBrowser2 during document complete and navigation error events and also Response code from OnNavigateError->StatusCode->lval.
using IWebBrowser i can append my content to existing webpage after page load and during navigation error.
I'm trying to do a simple AJAX call to an ASP page, that resets session variables and posts a little message back on completion. I'm doing this purely to learn AJAX.
The example came from W3 Schools website but since applying it to my page, I can't seem to get it to work and it's not producing any errors, which is annoying, because I can't debug it.
This is my JS, which is called when a user hits a button [Clear Form]:
function resetSearchForm()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("notification").innerHTML=xmlhttp.responseText;
document.getElementById('notification').style.visibility = 'visible';
}
}
xmlhttp.open("GET","clearSearchData.asp",true);
xmlhttp.send();
document.searchFrm.searchStr.value='';
document.searchFrm.vertical.checked = true;
document.searchFrm.horizontal.checked = true;
document.getElementById('dateRange').selectedIndex = 0;
document.searchFrm.searchStr.focus();
}
And this is the ASP (clearSearchData.asp) that clears my session variables and writes a message:
Response.Expires = -1
Session("search-str-boolean") = ""
Session("search-str-plain") = ""
Session("date-range") = ""
Session("date-from") = ""
Session("date-to") = ""
Session("specificDate") = ""
Session("peopleStr") = ""
Session("orientation") = ""
Response.Write "Form has been reset"
Can anybody see where I'm going wrong? I have been looking at it for a long time and I just can't see it.
The function itself works because the last part of the function gets processed, the bit that clears the form values... but... the AJAX call doesn't happen because the session variables still contain data and the message doesn't appear.
Many thanks in advance...
UPDATE - - - - - - - - - - -
It now works. The problem was I didn't include the full URL to the ASP page. Thanks for 'thedaian' (below) for pointing that out
Chances are, something is wrong with the page you're trying to get via AJAX. Check what xmlhttp.status is, if it's 404, then you're never going to get to the point where you're printing the AJAX response. Make sure that "clearSearchData.asp" is accessible from the same directory as your javascript. This is a common problem if you have your javascript code in a separate folder from the rest of your site. Or simply put in the full URL path for the "clearSearchData.asp" so it'll definitely work.
Something to point out, the function in xmlhttp.onreadystatechange is (usually) called after it's declared in the code. In this case, it gets called after your search form fields are cleared out and reset.
The ajax call does not automatically send along a session cookie. That means the session you're clearing is not the user's session, but just a session that's been created for that ajax call alone.