I am new to REST and I am trying to add a variable to the JSON body so I can have an input form for the values.
I have also tried using getElementID along with this HTML form after wrapping the the script in a function, but I am having no success.
var requestBody = "{'companyid':'getElementById('companyid')','knowledgeid':'getElementById('knowledgeid')','source_code':'getElementById('source')','article_title':'getElementById('title')'}";
var client=new XMLHttpRequest();
client.open("post","<URL>");
client.setRequestHeader('Accept','application/json');
client.setRequestHeader('Content-Type','application/json');
client.setRequestHeader('Authorization', 'Basic '+btoa('admin'+':'+'admin'));
client.onreadystatechange = function() {
if(this.readyState = this.DONE) {
document.getElementById("response").innerHTML=this.status + this.response;
}
};
client.send(requestBody);
Here is the form:
<form enctype="application/json" action="<URL>" method="post">
Title:<input id="title" type="text"></input>
Company:<input id="companyid" type="text"></input>
KnowledgeID:<input id="knowledgeid" type="text"></input>
HTML:<input id="source" type="text" ></input>
<input type="button" value="Send" onClick="restRequest()"></input>
When defining the value of requestBody you don't want to get the element itself, but it's value. You also have that single quoted so it's not going to get evaluated.
var requestBody = "{'companyid': '" + document.getElementById('companyid').value + "', 'knowledgeid': '" + document.getElementById('knowledgeid').value + "', 'source_code': '" + document.getElementById('source').value + "', 'article_title': '" + document.getElementById('title').value + "'}";
you need to be careful when constructing a body use proper concatenations see following with alertbox
var requestBody = "{companyid: " + document.getElementById(companyid).value + ", knowledgeid: " + document.getElementById(knowledgeid).value + ", source_code: " + document.getElementById(source).value + ", article_title: " + document.getElementById(title).value + "}";
alert(requestBody);
I will recommend take some time and look at JQuery framework. It will make your life lot easier
Related
Is there any way to use a form in leaflet mapping to open another page?
I'm using a post route for this and have even tried embedding it in an tag but to no avail.
At the moment the form data is in a for loop like so
map_data.forEach(element => {
console.log('program=' + element.program + ', lat=' + element.gps_lat + ', long=' + element.gps_lon);
data[i] = L.marker([element.gps_lon, element.gps_lat], {icon: redIcon}).addTo(map);
var url = '{{ route("opentraining", ":training_id") }}';
var alt_url = '{{ route("opentraining") }}';
url = url.replace(':id', element.id);
data[i].bindPopup(
'<strong>' + element.program + '</strong>'
+ '<br />'
+ '<b>Location:</b> ' + element.location + ', ' + element.district + ', ' + element.province
+ '<br />'
+ '<b>Description:</b> ' + element.description
+ '<br /><br />'
+ '<form onsubmit="' + alt_url + '" method="POST" class="formEditTraining">#csrf<input type="hidden" name="training_id" value='+ element.id + '>'
+ '<button type="submit" value="submit" class="btn btn-primary trigger-submit">View Record</button>'
+'</form>'
).openPopup();
i++;
});
Even when use the route directly within the form it makes no difference all I get is an error saying POST method isn't supported.. What could I be missing ?
You're using the wrong attribute for the URL in your <form> tag. onsubmit is for specifying a JS function to run before the form is submitted. To specify the URL you want to submit the form to, use action. Since you are not specifying action at the moment, it's posting it back to the same URL that the form is on, which evidently is not set up to receive POSTs.
I am trying to make a contact list in HTML. When adding a new contact, a menu comes up in which the user can enter information about the contact. For some reason, when I try to console.log the values of any of the fields (as I need to use the firstnamefield field to determine whether or not the contact is valid), it says that it can not find the value of null. As a result, my if statements aren't working and I am unable to keep the user from making a totally blank contact.
Code below, any help appreciated.
function addContact() { //called by the "add contact button", inserts the fields for the custom
document.getElementById("description").innerHTML="<h2><input type='text' id='firstnamefield' placeholder='First Name' value=''></h2><h2><input type='text' id='middlenamefield' placeholder='Middle Name'></h2><h2><input type='text' id='lastnamefield' placeholder='Last Name'></h2><input type='text' id='nicknamefield' placeholder='Nickname'><br><br><input type='text' id='phonefield' placeholder='Phone'><br><input type='text' id='emailfield' placeholder='Email'><br><br><input type='text' id='birthdayfield' placeholder='Birthday'><br><button type='button' id='finishbutton' onclick='finalizeContact()'>Finished</button>";
}
function finalizeContact() { //called by the "finished" button on the contact information form that appears when adding a contact, turns the information that has just been input by the user into a contact under the custom section at the bottom of the list
var firstname=document.getElementById('firstnamefield').value;
console.log(firstname);
if(document.getElementById("firstnamefield").value != null || firstname != '') {
document.getElementById('custom').innerHTML = document.getElementById('custom').innerHTML + "<button type='button' class='customcontact' onclick=\"display('" + document.getElementById('firstnamefield').value + "', '" + document.getElementById('nicknamefield').value + "', '" + document.getElementById('lastnamefield').value + "', '" + document.getElementById('nicknamefield').value + "', '" + document.getElementById('phonefield').value + "', '" + document.getElementById('emailfield').value + "', '" + document.getElementById('birthdayfield').value + "')\">" + document.getElementById('firstnamefield').value + " " + document.getElementById('lastnamefield').value + "</button>";
display(document.getElementById('firstnamefield').value, document.getElementById('middlenamefield').value, document.getElementById('lastnamefield').value, document.getElementById('nicknamefield').value, document.getElementById('phonefield').value, document.getElementById('emailfield').value, document.getElementById('birthdayfield').value)
if(document.getElementById('custom').style.display=="none") { // if there hasn't been a custom contact created yet, the CUSTOM section isn't visible. therefore, if the CUSTOM section is hidden, this function will make it visible
document.getElementById('custom').style.display="block";
}
} else {
document.getElementById("firstnamefield").style.border = "5px solid red";
document.getElementById("description").innerHTML = "Please enter a name.<br>" + document.getElementById("description").innerHTML;
}
}
I am using jQuery with REST in my application and I want to get the ouput mentioned below using the jQuery within my webpage .
I used the code below to search by get a company by id (each company has id, name other info supplier and buyers) but the result does not show up for me with my code, any suggestion on what have I missed?
REST is a concept for HTTP request exchange, so you're making RESTful request calls (e.g. 'get') against the REST-API you implemented on server side.
<input name="find" type="text" maxlength="300" id="find"/>
<button onclick="findId()"> Find By ID </button>
<div id="info"></div>
<script>
function findId()
{
var id = document.getElementById("find").value;
$("#info").html("");
$.getJSON("http://localhost:8080/company/" + id, function(data)
{
for (var i in data) {
$('#info').append("<p>ID: " + data[i].id + "</p>")
$('#info').append("<p>Name: " + data[i].name + "</p>")
$('#info').append("<p>Other Info: " + data[i].otherInfo + "</p><br>")
$('#info').append("<p>Supplier: " + data[i].suppliers + "</p><br>")
$('#info').append("<p>Buyers: " + data[i].buyers + "</p><br>")
}
});
}
When I type http://localhost:8080/company/ into my browser I get the following output:
[{"id":1,"name":"Test 1","otherInfo":"Test 1","suppliers":[{"id":1,"name":"Test 1","address":"Test 1","buyers":[{"id":1,"name":"Test 1","address":"Test 1"}]},{"id":2,"name":"Test 2","address":"Test 2","buyers":[{"id":3,"name":"Test 3","address":"Test 3"},{"id":2,"name":"Test 2","address":"Test 2"}]}]},{"id":2,"name":"Test 2","address":"Test 2","suppliers":[{"id":3,"name":"Test 3","address":"Test 3","buyers":[{"id":4,"name":"Test 4","address":"Test 4"}]}]}]
If i type http://localhost:8080/company/1 into my browser i get
{"id":1,"name":"Test 1","otherInfo":"Test 1","suppliers":[{"id":1,"name":"Test 1","address":"Test 1","buyers":[{"id":1,"name":"Test 1","address":"Test 1"}]},{"id":2,"name":"Test 2","address":"Test 2","buyers":[{"id":3,"name":"Test 3","address":"Test 3"},{"id":2,"name":"Test 2","address":"Test 2"}]}]}
Is it a cross domain request? If so you can get around it by using jsonp instead of json.
function findId()
{
var id = document.getElementById("find").value;
$("#info").html("");
$.getJSON("http://localhost:8080/company/?callback=?" + id, function(data)
{
for (var i in data) {
$('#info').append("<p>ID: " + data[i].id + "</p>")
$('#info').append("<p>Name: " + data[i].name + "</p>")
$('#info').append("<p>Other Info: " + data[i].otherInfo + "</p><br>")
$('#info').append("<p>Supplier: " + data[i].suppliers + "</p><br>")
$('#info').append("<p>Buyers: " + data[i].buyers + "</p><br>")
}
});
}
I want to send html table as form input using a javascript form POST. Post request is received in the servlet, however I am only getting part of the input table is "table id=". Please help me resolve this issue.
Javascript code:
var htmlFormat = $.trim($('#report_table').html()).split("+").join("%2b");
var form = $('<form action="./csvReportDownload" method="post" enctype="application/x-www-form-urlencoded" accept-charset="UTF-8">' +
'<input type="hidden" name="userId" value="' + $('#user_id').val() + '"/>' +
'<input type="hidden" name="new_tokens_dv" value="' + htmlFormat + '"/>' +
'</form>');
$('body').append(form);
$(form).submit()'
Servlet code:
String param_DETAILS = "report_table";
String temp = null;
if (request.getParameter(param_DETAILS) != null) {
temp = new String(request.getParameter(param_DETAILS).getBytes("ISO8859_1"), "UTF8");
log.info("Parameter value: "+temp);
}
Console Output: Parameter value: <table id="
Please , I have a JQuery code when appends data to a div element sucessfully like this
$('#conversation').append('<div id="receiver"><p><b>' + username + ':</b> ' + data + '</p></div><br>');
Now supposing I want to have an anchor tag which will have a hyperlink inside as an atrribute and I want to pass a variable to that href attribute not the link itself since I don't know the kind of link that will be sent. I have problems tring to append this.
$('#conversation').append('<div id="receiver"><p><b>' + username + ': <a id="link" href="'+ data +"></a></p></div><br>');
This does not work. Any idea how to go about this.
This is my whole code snippet
socket.on('updatechat', function (username, data) {
//showing username and the message sent
var checkifdataisalink=data;
var check=checkifdataisalink.split('://')
if((check[0]=='http')||(check=='https'))
{
$('#conversation').append('<div id="receiver"><p><b>' + username + ': <a id="link" href="'+ data +"></a></p></div><br>');
}else{
$('#conversation').append('<div id="receiver"><p><b>' + username + ':</b> ' + data + '</p></div><br>');
}
});
Apart from the missing quote, your or part of the if condition was missing [0]. See below.
//For demo purposes only
var check = ["http", "other-part-of-the-url"];
var username = "user";
var data = "data";
// --;--
if(check[0] == 'http' || check[0] == 'https') {
$('#conversation').append('<div id="receiver"><p><strong>' + username + ':</strong> <a id="link" href="' + data + '">' + data + '</a></p></div><br/>');
} else {
$('#conversation').append('<div id="receiver"><p><strong>' + username + ':</strong>' + data + '</p></div><br/>');
}
Demo#fiddle
Change
$('#conversation').append('<div id="receiver"><p><b>' + username + ': <a id="link" href="'+ data +"></a></p></div><br>')
into:
$('#conversation').append('<div id="receiver"><p><b>' + username + ': <a id="link" href="'+ data +'"></a></p></div><br>');
Just one ' was missing after data