Need to implement html button to access REST get resource - javascript

Fairly new to REST and web application and would like to create a front-end site with a button and a place where a result is displayed.
I have REST API structured like this:
http://hostserver.com/MEApp/MEService
This returns a value when browsing to it.
Now I would like to implement a GUI so that when you browse to c:\resourcebutton.html
There will be a button and when I click on it, it will call the REST API resource and returns the result. If I understood REST correctly it should work like this.
I have a html code:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to trigger a function.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</body>
</html>
How and where should I insert the GET method to call the API? Is it common to use Javascript?

Yes, you have to do this with JavaScript. In fact, you need Ajax.
To simplify things, you should download and include JQuery to your site, and then use something like this:
$.post( "http://hostserver.com/MEApp/MEService", function( data ) {
document.getElementById("demo").innerHTML = data;
//Or, in the JQuery-way:
$('#demo').html(data);
});
The jQuery Source can be found here: http://code.jquery.com/jquery-2.1.1.js
Your html-file would then look like this:
<!DOCTYPE html>
<html>
<head>
<script src="the/Path/To/The/Downloaded/JQuery.js"></script>
<script>
//Usually, you put script-tags into the head
function myFunction() {
//This performs a POST-Request.
//Use "$.get();" in order to perform a GET-Request (you have to take a look in the rest-API-documentation, if you're unsure what you need)
//The Browser downloads the webpage from the given url, and returns the data.
$.post( "http://hostserver.com/MEApp/MEService", function( data ) {
//As soon as the browser finished downloading, this function is called.
$('#demo').html(data);
});
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>
</html>

Related

How to alert all content of page on button click with JavaScript

I need to get all the content of page including all codes on JavaScript alert. Please check the code.
function getContent() {
var content = document.getElementsByTagName('html').value;
alert(content);
}
<html>
<head>
</head>
<body>
Some more code..........
Get Content
</body>
</html>
I am trying to execute the function from inside the page and trying to get the value. It is giving me undefined error
.getElementsByTagName() returns a NodeList collection of elements. You need to access the first index with [0]. In addition to this, it does not have a .value property. You're looking for .innerHTML instead.
Note that you also shouldn't make use of onclick, and instead should make use of unobtrusive JavaScript by adding an event listener.
This can be seen in the following:
function getContent() {
var content = document.getElementsByTagName('html')[0].innerHTML;
alert(content);
}
document.getElementsByTagName('a')[0].addEventListener('click', getContent);
<html>
<head></head>
<body>
Some more code..........
Get Content
</body>
</html>
Note: this will not work as expected in a Fiddle, but will work as expected on a proper website.
This can be achieved via the innerHTML field of a DOM element. Consider making the following changes to your getContent() function:
function getContent() {
var { innerHTML } = document.querySelector('html');
alert(innerHTML);
}
<html>
<head>
</head>
<body>
Some more code..........
<p> and some more content </p>
Get Content
</body>
</html>

Calling variable from javascript in an html doc

I work in schools and use google forms to keep track of a number of things.
One of these forms emails people with information from the sheet that is entered.
I have managed to cobble together a good script that provides this service, however, I want it to look good.
My question is simple (or so I believe it is):
When I put in my HTML for the body of the email, how do I call the variables that I have defined earlier in the script?
Do I need to define them in the HTML or can I call them from the JavaScript?
I am not a serious coder by any means but this one has seemed to escape my ability to google it.
Any help would be appreciated.
calling a value of the variable created in javascript, outside the script.
<html>
<script>
var somevariable = "hi"; //this is the variable you create in JavaScript
window.onload = function() {
document.getElementById("blabla").innerHTML = somevariable; //here you send the value of 'somevariable' to html.
}
</script>
<body>
<input type="text" id="blabla" name="someInput"></input>
</body>
</html>
I am not too sure what your code looks like so this is only an attempt to answer what I understand so far.
In you HTML document you don't call variables, you call functions. for example when you click a button, the text would change to what your variable is by calling the onclick Event inside the button, ChangeText() will be the function for the first example:
<!DOCTYPE html>
<html>
<body>
<p id="p1">Hello</p> <br />
<button onclick="ChangeText()">Button</button> <!-- onclick event -->
<script>
var p1 = document.getElementById("p1"); //variable created
function ChangeText () {
//when you click the button this function will be called
p1.innerHTML = "Changed text on button click!";
}
</script>
</body>
</html>
You could also call on the load of the document (but this would mean that you would't see what it was before):
<!DOCTYPE html>
<html>
<body>
<p id="p1">Hello</p> <br />
<script>
var p1 = document.getElementById("p1"); //variable created
p1.innerHTML = "Changed text on page load!"; //change text on load
</script>
</body>
</html>
hope this helps.

ReferenceError when I add C# row to the JavaScript code in view razor page

I have this code in razror view page:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">
Click me</button>
<p id="demo">
</p>
#{
List<UserContact> userContacts = ViewBag.contacts;
String contacts1 = Html.Partial("~/Views/Shared/Contacts.cshtml", userContacts).ToHtmlString();
}
<script type="text/javascript">
var contacts2 = #contacts1;
function myFunction() {
alert(contacts2);
}
</script>
</body>
</html>
when I press button Click me I get this error:
ReferenceError: myFunction is not defined
Why I get this error?
Any idea why I get this error?
Looks like you have some pretty broken HTML. You have assigned the contacts1 server side variable to an HTML fragment:
String contacts1 = Html.Partial("~/Views/Shared/Contacts.cshtml", userContacts).ToHtmlString();
and then you injected it inside a tag:
<script type="text/javascript">
var contacts2 = #contacts1;
function myFunction() {
alert(contacts2);
}
</script>
which totally breaks your markup. Look at the source code of the generated page in the browser and you will see how broken it is.
And how can I fix it?
It's not quite clear what you are trying to achieve so it's pretty hard to say how to fix this issue, but for starters you might try having valid markup and javascript:
<script type="text/javascript">
function myFunction() {
alert('The button was clicked');
}
</script>
It looks like you are trying to load some markup from the server when the button is clicked. You might consider using AJAX if this is the case.
UPDATE:
It looks like you are trying to assign a server side string variable to a javascript variable. This can be done by properly encoding it:
<script type="text/javascript">
var contacts2 = #Json.Encode(contacts1);
function myFunction() {
alert(contacts2);
}
</script>

javascript change html in event listener

I'm starting to experiment with building Chrome extensions (first exposure to HTML and Javascript as well) and got stuck on a basic task. I have the popup.html file, which is what the user sees. What I'd like to do is have some placeholder text that is initially displayed to the user. The popup will also have a button so that when the user clicks on the button the placeholder text is replaced with something else.
Here is what I tested:
popup.html:
<!doctype html>
<html>
<head>
<title>Test Extension</title>
<script src="popup.js"></script>
</head>
<body>
<form id="testForm">
<input id="testButton" type="submit" value="testButton" />
</form>
<h3 id="textHeader">This will change.</h3>
</body>
</html>
popup.js:
function changeText() {
document.getElementById('textHeader').innerHTML = 'Changed!';
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('testForm').addEventListener('submit', changeText);
});
When I debug the script, I see the initial addEventListener call which calls changeText and causes the text in the popup to change to 'Changed!'. However, I then see a second call of the addEventListener, which then reverts back to the original popup.html form. The net effect is that 'Changed!' only appears for a brief instant.
Is there a way to make changes to the HTML file in an event listener permanent to get the intended behavior? I realize that I really need to gain an understanding of the DOM model and how Javascript can interact with it in the browser. I'm looking for a book or some other resource to consult (the Mozilla Developer Network site looked like a good authoritative source, but seemed kind of sparse), but in the meantime was hoping to gain at least some additional understanding by working through this simple example. Thanks!
EDIT:
Thank you everyone for the prompt responses! Disabling the form submissions makes sense. I'm adding this edit to my question post because the original task I was trying to achieve did in fact need to make use of a form.
What I'm trying to do is take in input from the user through a form, query an external site (ex: Wikipedia) for the phrase that user typed in, and then display in the popup content that's taken from the query.
Here is a skeleton outline of what I attempted:
popup.html:
<!doctype html>
<html>
<head>
<title>Test Extension</title>
<script src="popup.js"></script>
</head>
<body>
<form id="WikipediaForm">
<input type="text" id="userQuery" size="50"/>
<input id="submitQuery" type="submit" value="Ask Wikipedia" />
</form>
<h3 id="WikipediaResponse">placeholder</h3>
</body>
</html>
popup.js:
function changeText() {
var req = new XMLHttpRequest();
askURL = 'http://en.wikipedia.org/wiki' + encodeURIComponent(document.getElementById('userQuery').value);
req.open("GET", askURL, false);
req.onload = function (e) {
if (req.readyState === 4) {
if (req.status === 200) {
document.getElementById('WikipediaResponse').innerHTML = req.responseText; // i'm just dumping everything for now
}
} else {
console.error(req.statusText);
}
}
};
req.send(null);
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('WikipediaForm').addEventListener('submit', changeText);
});
This again also faces the same issue that I saw with the previous example where the response flashes for an instant before reverting back to the placeholder text. However, I can't follow the earlier answers now because I need the form to be submitted. What is the usual way of changing content in an event listener for a form?
On another note, I'm using the synchronous XMLHttpRequest call, which I know isn't recommend. But when I used the asynchronous call it didn't seem to go through and I couldn't figure out how to fix that, so that's another problem I'm also working on.
Use:
function changeText() {
document.getElementById('textHeader').innerHTML = 'Changed!';
//Returning false will prevent that the form submission completes
return false;
}
But if your form is never going to send data anywhere, you don't need a form at all (unless you're going to use a reset button for your fields). So you can just add type="button" to your element.
<body>
<input id="testButton" type="button" value="testButton" />
<h3 id="textHeader">This will change.</h3>
</body>
You need to return false from the event handler to prevent the normal form submission after the handler runs:
function changeText() {
document.getElementById('textHeader').innerHTML = 'Changed!';
return false;
}

How to call a JavaScript function, declared in <head>, in the body when I want to call it

I have a working JavaScript function declared in the head of an HTML page. I know how to create a button and call the function when the user clicks the button. I want to call it myself some where on the page:
myfunction();
How do I do it?
You can call it like that:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var person = { name: 'Joe Blow' };
function myfunction() {
document.write(person.name);
}
</script>
</head>
<body>
<script type="text/javascript">
myfunction();
</script>
</body>
</html>
The result should be page with the only content: Joe Blow
Look here: http://jsfiddle.net/HWreP/
Best regards!
I'm not sure what you mean by "myself".
Any JavaScript function can be called by an event, but you must have some sort of event to trigger it.
e.g. On page load:
<body onload="myfunction();">
Or on mouseover:
<table onmouseover="myfunction();">
As a result the first question is, "What do you want to do to cause the function to execute?"
After you determine that it will be much easier to give you a direct answer.
Just drop
<script>
myfunction();
</script>
in the body where you want it to be called, understanding that when the page loads and the browser reaches that point, that's when the call will occur.
You can also put the JavaScript code in script tags, rather than a separate function. <script>//JS Code</script> This way the code will get executes on Page Load.

Categories