How to call existing REST api from a HTML form? - javascript

I have a REST API that I am using in a mobile application to register/store data into a Mongo database. I would now like to view the data stored in the DB on a webpage.
I know that I basically have all of the functionality already (the login request used in my mobile application) but I am so confused on how to call my REST from my HTML page.
Something like this: How to call a REST web service API from Javascript button Handler? ?
I am also confused on how/where I should be creating my html page. Any help is appreciated.
Thanks, Joe

Typically When user would like to get data from the server. client need to send a request to the server and get a response. Usually programmer will bind a request function with an specific element and events.
In this case you need to bind a request function with form element. As you didn't mention which event you want to happen, so I couldn't tell exactly solution.
The following code is a simple code that call REST API when user type on a text input, and show the result below the input text
Note that replace "URL" with your API call.
<!DOCTYPE html>
<html>
<body>
<form>
Keyword:<br>
<input type="text" name="keyword" onkeyup="callREST()"><br>
</form>
<div id="response"></div>
<script>
function callREST() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("response").innerHTML = this.responseText;
}
};
xhttp.open("GET", "URL", true);
xhttp.send();
}
</script>
</body>
</html>

This is how you do it...
HTML Code:
<form id="form" onsubmit="return setAction(this)">
<input name="senderEmail" type="email" placeholder="Email" required>
<textarea name="senderMessage" cols="30" rows="10" placeholder="Message.." required></textarea>
<button type="submit">Send message</button>
</form>
Javascript:
function setAction(form) {
const url = 'https://example.com/xyz?';
const andSign = '&';
const senderParameter = 'sender='+form.senderEmail.value;
const bodyParameter = 'body='+form.senderMessage.value;
const newUrl = url+senderParameter+andSign+bodyParameter;
fetch(
newUrl,
{
headers: { "Content-Type": "application/json" },
method: "POST",
body: ""
}
)
.then(data => data.json())
.then((json) => {
alert(JSON.stringify(json));
document.getElementById("form").reset();
});
return false;
}
This also resets your form after a successful api call is made.

Related

how to ajax for chatting website without page reload

want to create a fully dynamic chat UI for my website, But it reloads the whole page if a person submits the button page should not reload like many chat website.
<form action="action.php" method="post" id="formpost">
<input type="text" id="input" value="php echo">
<input type="submit" value="send">
</form>
I want to submit this form through ajax and show the last xml <message> containing <message>talk 123<message>
<messages category="short">
<person1>
<time>
r
<message>Djssjs</message>
</time>
</person1>
<person2>
<time>
r
<message>1234fdg</message>
</time>
</person2>
<person1>
<time>
r
<message> talk 123</message>
</time>
</person1>
</messages>
i want to show that talk 123 in the html document bit confused how to do that
//for form submit
$("#formpost").submit(function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: action.php,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
//for xml
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "name.xml", true);
xhttp.send();
}
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var msg = "";
//how to select the last person's of the <messages> child
msg = getElementsByTagName("messages").lastChild.childNodes[1].nodeValue ;
document.getElementById("demo").innerHTML = msg;
}
$("#formpost").on('submit', function(event){
event.preventDefault();
// rest of your ajax code here...
});
Points to note
1. Make sure you have also added JQuery script source on the head tag of your chat page.
2. Make sure to put preventDefault() immediately before any other code is executed.
You can use reverse ajax method pulling data from the server.
In reverse ajax a request is auto-generated at a certain time interval or hold the request for fetching new message.
There are three technologies for reverse ajax:-
Piggyback
Polling
Comet

How to post json and get back an json response using ajax with javascript?

<script>
window.onload = function() {
document.getElementById("Save").onclick = function fun() {
var x = document.forms["myForm"]["machine_id": "TNTEST004"].value;
var y = document.forms["myForm"]["wifi_mac_address": "80:56:f2:18:12:11"].value;
var Url = "http://192.168.1.9:8080/machine_reg/";
var xhr = new XMLHttpRequest();
xhr.open('POST', Url, true);
xhr.send(x);
xhr.send(y);
xhr.onreadystatechange = processRequest;
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText.headers.Host);
var response1 = JSON.parse(xhr.responseText);
document.getElementById("updated_time").innerHTML = response1.updated_time;
document.getElementById("id").innerHTML = response1.id;
}
}
}
}
</script>
</head>
<!DOCTYPE html>
<html>
<head>
<body>
<center>
Javascript Post Request Test
<br><br>
<form name="myForm">
<input type="text" placeholder= "machine id" name="machine_id"/>
<input type="text" placeholder= "wifi mac address" name="wifi_mac_address"/>
<input type="button" id="Save" onclick="function fun()" value="get_values"/>
</form>
<br><br>
<table>
<tr><td>id :</td><td id="id"></td></tr>
<tr><td>updated_time :</td><td id="updated_time"></td></tr>
</table>
</center>
</body>
</html>
http://192.168.1.9:8080/machine_reg/ this is my URL. And its a POST method. Now in this URL, if I POST ("machine_id": "TNTEST004","wifi_mac_address":"80:56:f2:18:12:11") these two JSON datas, it will generate an ID (eg:"id: 3"). I have to pass this two json datas in the text boxes with the submit button and on the button click, I should have the id returned in a alert window. I am bit confused getting an error. resolve this for me using ajax in javascript.
I will pass as like this.
{
"machine_id": "TNTEST009",
"wifi_mac_address": "80:56:f2:18:12:11"
}
This is the ID generated if I pass the machine ID and the wifi mac address.
{
"id": 5,
"machine_id": "TNTEST009",
"wifi_mac_address": "80:56:f2:18:12:11",
"auth_token": "",
"updated_time": "2018-05-01T13:14:42.372174Z"
}
Note:(Use Advanced Rest Client app for referrence if you wanna see how this actually works on the post request.)
I'm not sure I understand your question... But this is how you do an ajax request with jquery.
$.ajax({
url: '/User/PrevalidateLevelThree',
type: 'POST',
data: {
machine_id: 'TNTEST009',
wifi_mac_address: '80:56:f2:18:12:11'
},
success: function (result) {
alert(result);
},
});
Again, i'm not sure I understand your question but I think this will give you a good start...

Submit Embedded Mailchimp Form with Javascript AJAX (not jQuery)

I have been trying to submit an embedded Mailchimp form with AJAX but without using jQuery. Clearly, I am not doing this properly, as I keep ending up on the "Come, Watson, come! The game is afoot." page :(
Any help with this would be greatly appreciate.
The form action has been altered to replace post?u= with post-json?u= and &c=? has been added to the end of the action string. Here is my js:
document.addEventListener('DOMContentLoaded', function() {
function formMailchimp() {
var elForm = document.getElementById('mc-embedded-subscribe-form'),
elInputName = document.getElementById('mce-NAME'),
elInputEmail = document.getElementById('mce-EMAIL'),
strFormAction = elForm.getAttribute('action');
elForm.addEventListener('submit', function(e) {
var request = new XMLHttpRequest();
request.open('GET', strFormAction, true);
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var resp = JSON.parse(request.responseText);
request.send(resp);
} else {
console.log('We reached our target server, but it returned an error');
}
};
request.onerror = function() {
console.log('There was a connection error of some sort');
};
});
}
formMailchimp();
});
Also, I anticipate the inevitable "why don't you just use jQuery" comment. Without going into the specifics of this project, jQuery is not something I am able to introduce into the code. Sorry, but this HAS to be vanilla javascript. Compatibility is for very modern browsers only.
Thanks so much for any help you can provide!
A few days back I've had the exact same problem and as it turns out the MailChimp documentation on native JavaScript is pretty sparse. I can share with you my code I came up with. Hope you can build from here!
The simplified HTML form: I've got the from action from the MailChimp form builder and added "post-json"
<div id="newsletter">
<form action="NAME.us1.list-manage.com/subscribe/post-json?u=XXXXXX&id=XXXXXXX">
<input class="email" type="email" value="Enter your email" required />
<input class="submit" type="submit" value="Subscribe" />
</form>
</div>
The JavaScript: The only way to avoid the cross-origin problem is to create a script and append it to the header. The callback occurs then on the ā€œcā€ parameter. (Please note there is no email address validation on it yet)
function newsletterSubmitted(event) {
event.preventDefault();
this._form = this.querySelector("form");
this._action = this._form.getAttribute("action");
this._input = this._form.querySelector("input.email").value;
document.MC_callback = function(response) {
if(response.result == "success") {
// show success meassage
} else {
// show error message
}
}
// generate script
this._script = document.createElement("script");
this._script.type = "text/javascript";
this._script.src = this._action + "&c=document.MC_callback&EMAIL=" + this._input;
// append script to head
document.getElementsByTagName("head")[0].appendChild(this._script);
}
var newsletter = document.querySelector("#newsletter")
newsletter.addEventListener("submit", newsletterSubmitted);

I am having difficulty reaching a web service. Any ideas what changes are needed on my code?

I have struggled with this task for so long that I am hoping for a reprieve.
We have a web service called Validate on a separate server/domain.
Due to same domain restrictions, I came up with proxy server (code) to work around it.
The code below called Validate.asp, points to the webservice:
Set http = Server.CreateObject("msxml2.ServerXMLHTTP")
http.Open "POST", "http://servername1/folder1/folder2/folder3/Validation/Validate", False
http.setRequestHeader "Content-type","application/x-www-form-urlencoded"
http.Send Request.Form
Response.Write http.ResponseText
Response.End
%>
Then the code markup below invokes Validate.asp.
<!DOCTYPE html>
<html>
<body>
<form>
Enter name: <input id="user" /><br/>
Enter Pass: <input id="pass" /><br/>
<input type="button" value="Get web response via AJAX" onclick="ajaxViaProxy()" />
</form>
<hr/>
Ressponse: <div id="result"></div>
<script type="text/javascript">
function ajaxViaProxy( )
{
var uname = document.getElementById("user").value;
var upass = document.getElementById("pass").value;
var http = new XMLHttpRequest();
http.open("POST", "Validate.asp", true );
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
http.onreadystatechange=function()
{
if (http.readyState==4 && http.status==200)
{
document.getElementById("result").innerHTML =
"Response from web server was '" + http.responseText + "'";
}
}
http.send("username=" + encodeURIComponent(uname)
+ "&password=" + encodeURIComponent(upass));
}
</script>
</body>
</html>
If everything goes well, we should get response similar to this one below:
{"Value":{"TokenId":35,"LoginName":"validUser","Created":"2013-12-03T09:53:35","Expires":"2013-12-24T09:53:35","LastUsed":"2013-12-03T09:53:35"},"Status":0,"Message":null}
This is the exact response we get when I paste the code below into an address bar and hit the enter key:
http://servername/folder1/folder2/folder3/Validation/Validate?data={"User":"validUserName","Password":"validPassword"}
However, when I use the markup to invoke proxyValidate.asp, rather than get the response with token, I get the following:
{"Value":null,"Status":2,"Message":"Invalid username or password"}
Does anyone know what I need to change in the markup or in proxyValidate.asp so that when I run the code, I get a properly formatted URL string like this below?
http://servername/folder1/folder2/folder3/Validation/Validate?data={"User":"validUserName","Password":"validPassword"}
Thanks alot in advance

AJAX file upload/form submit without jquery or iframes?

Is it possible to do an AJAX form submit without jQuery or IFrames (so just pure JavaScript)? I'm currently sending to a struts fileUploadAction that works. Would the action's code still work with the asynchronous submit, or are there additions required to pick up the async form submit?
I am using struts 1.x and current my form is:
<html:form action="fileUploadAction" method="post" enctype="multipart/form-data">
...form elements...
<html:file property="theFile" />
...other elements...
</html:form>
Can this form be submitted, and thus the file uploaded with AJAX?
If I understood you correct, you can use the following code to upload the file async. Modify it as you like
var AjaxFileUploader = function () {
this._file = null;
var self = this;
this.uploadFile = function (uploadUrl, file) {
var xhr = new XMLHttpRequest();
xhr.onprogress = function (e) {
...
};
xhr.onload = function (e) {
...
};
xhr.onerror = function (e) {
...
};
xhr.open("post", uploadUrl, true);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-File-Type", file.type);
xhr.send(file);
};
};
AjaxFileUploader.IsAsyncFileUploadSupported = function () {
return typeof (new XMLHttpRequest().upload) !== 'undefined';
}
if (AjaxFileUploader.IsAsyncFileUploadSupported) {
ajaxFileUploader = new AjaxFileUploader();
$("form").submit(function () {
var uploader = $("#fileUploader")[0];
if (uploader.files.length == 0) {
return;
} else {
ajaxFileUploader.uploadFile(
"/YourUploadUrl",
uploader.files[0]);
}
return false;
});
}
To upload the form use the FormData class, populate it with form values and post it with XHR.
Update:
For HTML4 try the following
http://www.albanx.com/?pid=5&subid=21
Asynchronous file upload (AJAX file upload) using jsp and javascript
http://fineuploader.com/ is a ajax file-uploader.
This plugin uses XHR for uploading multiple files with progress-bar in FF3.6+, Safari4+, Chrome and falls back to hidden iframe based upload in other browsers, providing good user experience everywhere.
The up-to-date (march 2022), pure js solution, can be found in here. Summary:
You can use fetch optionally with await-try-catch
let photo = document.getElementById("image-file").files[0];
let formData = new FormData();
formData.append("photo", photo);
fetch('/upload/image', {method: "POST", body: formData});
No need to add jquery or any other third party library, just add IPerfect JS library and you are good to go.
IP_uploadFile(URL,responseType,this[object],[dynamicFunctionForResponse])
if user select responseType as 'html' then dynamicFunctionForResponse will get response in HTML format. In below example you will get 'done' response in alert.
HTML
<script type="text/javascript" src="http://services.iperfect.net/js/IP_generalLib.js"></script>
<script language='javascript'>
function testResponse(data){
alert(data)
}
</script>
Body
<form method="POST" enctype="multipart/form-data" onsubmit="IP_uploadFile('testupload.php','html',this,testResponse); return false;">
<input type="file" name="file1">
<input type="submit" name="submit1" value="Click here">
</form>
PHP: testupload.php
move_uploaded_file($_FILES['file1']['tmp_name'], realpath("./")."/upload/".$_FILES["file1"]["name"]);
echo "done";

Categories

Resources