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>")
}
});
}
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'm working on online SharePoint site, where I want to have Table of Contents on my pages. It went successful, but I'm not satisfied with links to headers, which are in this style: PageName#heading_[number], where I would like to have PageName#{headingName}.
Is it possible? Here is link to my script: https://pastebin.com/MVsJf0hr . I suppose that it must be written somewhere here:
$(this).attr("id", "heading_" + i);
$("#theTOC").append("<a href='#heading_" + i + "' title='" + theLevel + "'>" + theLevelString + " " + $(this).text() + "</a><br />");
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
I am trying to create email templates just using an html file. This file will display a list of mailto links that, when clicked, will open a template with message. I got it working for the most part but some of these templates use prompts to add information to the message before creating it. The problem is that it doesn't seem to work right. Here is my code.
function sendReport(emailName, addresseList){
document.writeln('<a onClick="setPrompt(this,\'' + addresseList + '\')" href="mailto:' + addresseList + '?subject=' + 'Report' + '&body=' + 'Here is the report.' + '">' + emailName + '</a><br />');
}
function setPrompt(obj, addresseList){
var reportName = prompt("Report name","");
obj.attr('href', ='mailto:' + addresseList + '?subject=' + reportName + '&body=' + "Here is the report."); //<-- this is the line that is giving me trouble.
}
You have a typo in the last line and there is no .attr() built in function in Javascript. This should fix it:
obj.setAttribute('href', 'mailto:' + addresseList + '?subject=' + reportName + '&body=' + "Here is the report.");
I'm trying to work through the 2nd question on this set of problems. I have to be able to click on a legislator's name and have additional information about him/her show up. Here's what I have so far.
$(function() {
$("form#get-zip").submit(function() {
var zip = $("input#zip").val();
$.get("http://congress.api.sunlightfoundation.com/legislators/locate?apikey=191e116b2a244fb48c5028e8f370488b&zip=" + zip, function(responseText) {
responseText.results.forEach(function(legislator) {
$("ul#legislators").append("<li>" + " " + legislator.first_name + " " + legislator.last_name + " (" + legislator.chamber + ")" + "</li>");
$("li").click(function() {
$(this).append("<p>Party: " + legislator.party + ", District: " + legislator.district + "</p>");
});
});
});
return false;
});
});
The problem is that when I click on a legislator's name it reveals information about all the legislators in the list rather than the particular legislator I clicked on. This is my first experience with A.P.I.s and I'm very much still a novice programmer. I'm finding all these moving parts to be very mentally exhausting. So I really appreciate any help I can get with this. Thanks.
I would suggest building out all your html on submit, even the details that appear below each legislator. Then hide all that extra detail. And set up the function of your li's to show the relative details.
$(function() {
$("form#get-zip").submit(
function() {
var zip = $("input#zip").val();
$.getJSON("http://congress.api.sunlightfoundation.com/legislators/locate?apikey=191e116b2a244fb48c5028e8f370488b&zip=" + zip,
function(responseText) {
$.each(responseText.results,
function(i,legislator) {
var newEl = $("<li>" + " " + legislator.first_name + " " + legislator.last_name + " (" + legislator.chamber + ")" + "<p>Party: " + legislator.party + ", District: " + legislator.district + "</p></li>");
newEl.appendTo("ul#legislators");
$("ul#legislators li").last().find("p").hide(); // hide the last added one
}); // end each
}); // end get function
}); // end submit function
$("ul#legislators").on("click", "li",
function() {
var details = $(this).find("p");
if (details.is(":visible")) {
details.hide();
} else {
details.show();
}
}); // end click function
}); // end document ready function
When the click event fires, the legislator variable no longer contains the data you looking for.