Why do my functions keep reading input from my input text field? - javascript

The input on my html form has a problem. Curently I am taking the input which is a twitter name into an Ajax function that calls tweets via php from the twitter api.
As I have a setInterval function to keep checking for updates, the input is passed again and again into the function to get tweets.
The problem is that the function seems to be reading the input directly from what is in the text input box. So if the user changes the text without pressing enter or hitting the button, the function keeps reading that text as the input. So the input entered initially is not fixed after pressing enter or hitting the button to submit.
Here is the html form taking in the input:
<div id="topdiv">Input Twitter ID: <input type="text" id="userid" onkeydown="if(event.keyCode===13) {document.getElementById('tweet-button').click();}">
<input type="submit" id="tweet-button" onclick="getStatusesX();" value="Get recent tweets">
<p id="tweetbox"></p>
</div>
Here are the functions:
function getStatusesX() {
var userID = document.getElementById("userid").value;
getStatuses(userID);
var intervalstop = setInterval(function() {getStatuses(userID);}, 20000);
clearInterval(intervalstop);}
//Create a cross-browser XMLHttp Request object
function getXMLHttp() {
var xmlhttp;
if (window.ActiveXObject) {
XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
XMLHttp = new XMLHttpRequest();
} else {
alert("Your browser does not support XMLHTTP!");
}
return XMLHttp;
}
//function that searches for the tweets via php
function getStatuses(userID){
XMLHttp1 = getXMLHttp();
//ajax call to a php file that will extract the tweets
XMLHttp1.open( 'GET', 'TwitterGlimpsePHP.php?userid='userID, true);
// Process the data when the ajax object changes its state
XMLHttp1.onreadystatechange = function() {
if( XMLHttp1.readyState == 4 ) {
if( XMLHttp1.status ==200 ) { //no problem has been detected
document.getElementById("tweetbox").innerHTML=XMLHttp1.responseText;
}
}
}
XMLHttp1.send(null);
}
I want the input to be taken as the text after enter is pressed. I have tried assigning it to variables but cannot work out why it keeps reading from the input field. Any help appreciated.

This is not an official answer - just trying to clear up my comments
This is what I mean by declaring outside the function...
var intervalstop;
function getStatusesX() {
clearInterval(intervalstop);
var userID = document.getElementById("userid").value;
getStatuses(userID);
intervalstop = setInterval(function() {getStatuses(userID);}, 20000);
}
that way you initialize the var and inside the function you clear first to ensure it's not compounding. Then you set the var to a new interval to begin again.
You said twitter doesn't like something about this code if the user clicks many times - Makes perfect sense. They will want to throttle the API to prevent someone from making 50,000 requests per minute cause of improper coding. You should check the API specs to make sure you're within a realistic zone and consider caching the results locally if you are pushing boundaries.

The issue is that you are re-reading the value of the textbox every time getStatuses is called.
Try capturing the value of the textbox first, and passing it into your getStatuses function:
So your new getStatusesX is:
function getStatusesX() {
var userID = document.getElementById("userid").value;
getStatuses(userID);
setInterval(function() {
getStatuses(userID);
}, 20000);
}
Update getStatuses to take a userID parameter and delete the line where you're reading the textbox's value inside of getStatuses.
That having been said, it might be an issue if this is possible to begin with - what if the user clicks the button to automatically refresh statuses multiple times? You might want to disable the button/textbox after it's been clicked, or have it clearInterval the old interval first.

Related

How to set textbox input to a variable

I'm currently just getting into JavaScript with HTML. I have been using HTML and CSS for a while now, but I only just recently got into Python, so now I feel I'll be more capable / able to understand JavaScript.
I'm currently working on an idea I've had, a Fortune Cookie Maker. The user inputs text into a textbox input. This is stored in a variable. When the user clicks ok, it gets the text from the textbox, and sets it to that variable. Then, it switches the page, and gets the variable from the script, and sets a paragraph to the text value of that variable.
However, my problem is, the paragraph won't display the text.
Here's my code:
var fortune = null;
function dispTxt() {
var txt = document.getElementById('textbox').value;
var hid = document.getElementById('conftxt');
if (txt.length > 0) {
//hid.style.display = 'block';
document.getElementById("conftxt").style.opacity = 1;
document.getElementById("textbox").style.color = "#ffffff";
} else {
//hid.style.display = 'none';
document.getElementById("conftxt").style.opacity = 0;
//document.getElementById("textbox").style.color = "#000000";
}
document.getElementById("txt").addEventListener("onkeyup", function() {
dispTxt();
})
};
function confirm() {
//Get the text that is inputted by the user.
fortune = document.getElementById("conftxt").value;
window.location = "fortune.html";
window.alert(fortune);
}
function setFortune() {
document.getElementById('fortunetext').value = fortune;
}
And here's a link to the repl itself for reference.
Also, if anyone has any tips for how I should go about making the fortune cookie itself, please, let me know.
I essentially just want it to be so that once you confirm what the fortune says, the fortune cookie appears, and you can click on it, and break it open, and it reveals the fortune.
Thanks!
You say fortune = document.getElementById("conftxt").value;, but #conftxt is the button element.
fortune = document.getElementById("textbox").value; will do
But because the page refreshes/redirects to fortune.html the variable fortune is cleared again.
You have two options:
Use one HTML page, so you don't use redirects
Store the variable in localStorage or sessionStorage
Pass the value into the URL param. Links: Pass variable to URL and Get the passed variable from URl
I recommend 1.
You can't get the value because you are getting the wrong element
function confirm () {
fortune = document.getElementById("conftxt").value;
...
}
Should be
function confirm () {
fortune = document.getElementById("textbox").value;
...
}
Also, you are navigating between different pages, so, you need to pass this value

CRM javascript button calls json url and parse a value

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

Refresh form after save and close

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!

Edit checkboxes based on url on page back

I have been struggling for a few hours with something that sounds very simple.
What i have is a list of checkboxes, if a checkbox is checked the page url will change (to save a filter option, so you can share the url to the filter). It works perfectly except one point, when the user wants to go back. the checkboxes should be unchecked.
Using jQuery
setBoxes() is the function;
I tried:
function pageLoad() {
setBoxes();
}
And
$(document).ready(function(){
setBoxes();
}
Also I added
window.onunload = function(){};
But none of these solutions worked ( the function doesn't run, i checked it).
After that I thought I might could do it with php (get the url to an array, if in the array echo checked), but php wont run again (I guess its cashed).
Is there any option i can try cause I really cant solve this simple looking problem.
because my code is very big I made a very small example http://jsfiddle.net/yzoztp05/1/ of the situation, updating the url in jsfiddle is blocked so it doesn't work completely.
To make the situation more clear i made a video https://www.youtube.com/watch?v=jaSc1fmaJD4&feature=youtu.be.
the code to set my checkboxes
//convert the url to array
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
// Set the checkboxes to checked if they are in the array
function setBoxes()
{
var prijsUrl = getQueryVariable("prijs");
// first set all checkboxes on unchecked
$('.prijsFilterBox').prop('checked', false);
alert("Loaded");
if(prijsUrl != false)
{
var res = prijsUrl.split("-");
for(var i = 0; i < res.length; i++ )
{
$('.prijsFilterBox[value='+res[i]+']').prop('checked', true);
console.log("prijs = "+res[i]);
}
}
else
{
console.log("prijs = null");
}
}
It works if I refresh the page, but it wont run on when user presses the back button. If its not possible to run javascript on page back I will try to make a different script with php.
TLDR
How can i run a jquery function on page back (all browsers)?
It may be possible ( and I think that many are using this way ) to have timeOut function that is called every 500ms that checks if URL has changed, but instead of using '?' use hash '#' so user is always on same page and you can catch URL change.
If you need to stick to '?' , maybe you could do something with window.onbeforeunload function.

websockets do not work when assigned to global var

I use websockets along with javascript and html5
I have the following code.
<input type="text" onFocus=" so = new websocket('ws://localhost:1234');" onBlur="so.close();" onKeyUp="keyup();" >
<script type='text/javascript'>
var so; //this is global...
//wait a little (user stops typing)
function keyup(){
if (timeout) {clearTimeout(timeout);}
timeout = setTimeout(lookup, 250);
}
function lookup(){
//it's global, so use it right away
so.onopen = function(){
//send data to server to get responce...
So, websockets open/close if user clicks/or not a textfield. User types something on textfield. The value of textfield is sended to the server, a query is executed and if there are matching results, they render on the screen of the user.
If I click on the text field I see in the console "connected" and if I click anyware else I see "closed normally", as I should. That's ok.
But when I type letteres to the textfield, to send data to server, nothing is sended. I see nothing in the console. I see no errors.
What am I missing? It's like so.onopen never get executed.
Any advice?
Thanks in advance
The problem is that you recreate the socket but don't bind the onopen event handler.
On focus, you should call a function doing both : create the websocket and bind the onopen event handler :
<input id=someid type="text" onBlur="so.close();" >
<script type='text/javascript'>
var so, field = document.getElementById('someid');
field.onfocus = function(){
so = new websocket('ws://localhost:1234');
so.onopen = function(){
// do things
}
}

Categories

Resources