How to send an API get request using JavaScript with HTML variables - javascript

I am trying to make a GET request to a web API using what is inputted in a textbox. So far I have the input value established but can't seem to figure out to send the request.
const inputdata = document.getElementById('request');
const requestdata = inputdata.value;
console.log(requestdata);
This function correctly but I can't seem to figure out the rest.
I am trying to do the following:
https://api.example.com/request?=${requestdata}
or
https://api.example.com/request/${requestdata}/test
Keep in mind that this is a static HTML site with no Node

Something like this should work to make an asynchronous GET request:
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true);
xmlHttp.send(null);
}
const inputdata = document.getElementById('request');
const requestdata = inputdata.value;
httpGetAsync("https://api.example.com/request?=${" + requestdata + "}");
<input type="text" id="request" value="test">
If you check the developer tools > network tab you should see the GET request to the API endpoint.

Related

XHTTP request from REST API

I have this API
[HttpGet("data")]
public dynamic GetData(){
return context.DataTable.ToList();
}
I tried calling it on my Javascript using this snippet;
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true);
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
var resp = xhttp.responseText;
}
However, it only returns empty XMLHttpRequest.
I think what's wrong there is the URL. How I may able to call the API to my Javascript?
Since u have not cheked the response of ur answer, i susspect there is something wrong in ur backend. But, here is a sample of functional solution:
<!DOCTYPE html>
<html>
<body>
<h2>Using the XMLHttpRequest Object</h2>
<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>
<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log("Status is: "+this.status);
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "xmlhttp_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
You van find more info here. But in the line
xhttp.open("GET", "api/myclass/data", true);
The second parameter is the address of a file in ur server. r u sure u have wrotten the correct format? what is the extension of ur data file.
I guess, both backend and front end should be reconsidered. To do it:
Try to send a reuqest using postman to backend
in frontend check the status of response using my answer
To make sure make it async = false with
xhttp.open("GET", "api/myclass/data", false);
Therefore, there wouldn't be a delay as #Alex Kudryashev pointed
Solution:
You need to first find the result of line
console.log("Status is: "+this.status);
in ur browser's console.
If u get the responseText as empty it may come because u have sent an empty string from backend,(we are not sure because u have not tested ur backend with postman) but it is crucial to know the status of response.
The request may take time to receive the response so you have to wait. Something like this.
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true); //the request is asynchronous
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.state == 200){ //**this** is xhttp
//data are received and ready to use
var resp = this.responseText;
//do whatever you want with resp but never try to **return** it from the function
}
}
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
//var resp = xhttp.responseText; //too early ;(
}

xhr does not get invoked from js

i am using phonegap and trying to invoke a xhr POST on click of a button.
my flow goes to the method call but doesn't invoke the xhr code and i am failing to understand why.
The call looks like:
function fetchTags(){
console.log("Fetched url is:" + IMAGE_URL);
//var url = "http://localhost:8080/echo";
var url ="http://localhost:8080/echo";
console.log("#1");
var xhr = new XMLHttpRequest();
console.log("#2");
xhr.addEventListener("error", onError);function onError(evt) { console.log("An error occurred while transferring the file."); }
console.log("#3");
xhr.setRequestHeader("Content-type", "application/json");
console.log("#4");
xhr.open('POST', url, true);
console.log("#5");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
window.alert(response);
}else{
window.alert(xhr.status);
}
};
console.log("#5");
//var msg = "{'message' : '" + IMAGE_URL + "'}";
console.log("sending request");
xhr.send(JSON.stringify({"message" : "my msg"}));
}
Button code:
<button class="button button-raised larger" type="button" onclick="fetchTags()">Vision</button>
The console prints:
Fetched url is:undefined
#1
#2
#3
To clarify i can see first console.log getting printed. but that's it. nothing happens after that.
just for everyone's benefit the issue was not the javascript but invoking from the phonegap using the localhost.
I was unders the assumption that phonegap will be able to access my api at localhost (not sure why had this stupid idea) but yes using the actual ip of the host machine made it work right away.

Sending Http POST Request through Rest API in Javascript

I am trying to send an Http post request to parse.com server through Rest API keys. Not sure if I am doing it right as below. The following is my whole script and makes a button which should trigger the post request in a simple HTML page.
<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />
<script>
xmlhttp = new XMLHttpRequest();
var url = "https://api.parse.com/1/classes/english";
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.setRequestHeader("X-Parse-Application-Id", "VnxVYV8ndyp6hE7FlPxBdXdhxTCmxX1111111");
xmlhttp.setRequestHeader("X-Parse-REST-API-Key","6QzJ0FRSPIhXbEziFFPs7JvH1l11111111");
xmlhttp.onreadystatechange = function () { //Call a function when the state changes.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
var parameters = {
"ephrase": "english",
"pphrase": "farsi",
"nvote": 0,
"yvote": 0
};
// Neither was accepted when I set with parameters="username=myname"+"&password=mypass" as the server may not accept that
function doFunction() {
xmlhttp.send(parameters);
}
</script>
xmlhttp.send(parameters);
^^^^^^^^^^
That needs to be a string, but it is an object, so will be converted to the string: "[object Object]".
You need to convert the data to the proper encoding first.
You've said:
xmlhttp.setRequestHeader("Content-type", "application/json");
so you can use JSON.stringify(parameters) for that.

Send Custom HTTP Body with AJAX POST request

How do I send a custom HTTP body with my POST AJAX request in plain Javascript (not JQuery)? I am actually trying to send a JSON file in the body. I can set the custom header fields but can't find how to set HTTP body.
below is the code
function calculateorder() {
document.getElementById("finalize").style.display = "inline";
url1 = "https://ethor-prod.apigee.net/v1/stores/";
url2 = "/orders/calculate?apikey=wSgbv9PE8aJhDOI17vvTUX1NlAceUXG7";
url = url1 + store_id + url2;
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify(calculate));
}
When I used the same headers and JSON file with Rested (a OSX HTTP client) It works perfectly
Add parameter in XmlHttpRequest Obeject's .send() method
Like this:
xhr.send('username=me');
Send JSON Format Data myData Like this:
xhr.send(JSON.stringify(myData));

send an http request without XHR in an event handler

How to send an http request with either post/get method using javascript as an eventhandler? Thanks! Paul
Okay, you don't want to use Ajax.
You can use an event handler to submit a form!
<a href='#' onclick='cow_submit("zoodle")'>send</a>
<form method='post' id='formie' action='find_some_action.php'>
<input type='hidden' id='snoutvar' name='snoutvar' value='snout'>
</form>
<script>
function cow_submit(a_var_to_set){
var plip=document.getElementById('formie');
var snout=document.getElementById('snoutvar');
snout.value=a_var_to_set;
plip.submit();
}
See https://developer.mozilla.org/en/DOM/form
use XmlHttpRequest
sample code:
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "test.xml");
client.send();
function handler()
{
// your handler
}
You can use XMLHttpRequest for sending request from javascript
Sending GET request
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("GET", url+"?"+params, true);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(null);
Sending POST request
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
And don't forget to encode parameters using encodeURIComponent for param value encoding in case of user input
e.g.
params="paramName="+encodeURIComponent(paramValue);
The standard class for doing this is XmlHttpRequest, but it's not universally supported. On some browsers you have to use ActiveXObject("Microsoft.XMLHTTP") instead.
Look into the jQuery system which provides HTTP download (AJAX style) methods regardless of the underlying browser APIs (hence avoiding a lot of the code shown in Tzury's answer).
The jQuery AJAX documentation is at http://docs.jquery.com/Ajax
You should try to add atring in a hidden field and then call the form.submit() to submit your form into the page define in action.
<script type="text/javascript">
function doTestFormSubmit(yourString) {
document.getElementById("myString").value=myString;
document.getElementById("testForm").submit();
}
</script>
<form name="testForm" id="testForm" action="yourDesiredPage.php" method="post">
<input type="hidden" name="myString" id="myString" value=""/>
</form>
Ajax Tutorial (http://code.google.com/edu/ajax/tutorials/ajax-tutorial.html)
var obj;
function ProcessXML(url) {
// native object
if (window.XMLHttpRequest) {
// obtain new object
obj = new XMLHttpRequest();
// set the callback function
obj.onreadystatechange = processChange;
// we will do a GET with the url; "true" for asynch
obj.open("GET", url, true);
// null for GET with native object
obj.send(null);
// IE/Windows ActiveX object
} else if (window.ActiveXObject) {
obj = new ActiveXObject("Microsoft.XMLHTTP");
if (obj) {
obj.onreadystatechange = processChange;
obj.open("GET", url, true);
// don't send null for ActiveX
obj.send();
}
} else {
alert("Your browser does not support AJAX");
}
}
function processChange() {
// 4 means the response has been returned and ready to be processed
if (obj.readyState == 4) {
// 200 means "OK"
if (obj.status == 200) {
// process whatever has been sent back here:
// anything else means a problem
} else {
alert("There was a problem in the returned data:\n");
}
}
}

Categories

Resources