I have a list which is pulled from a Postgres database and I need to be able to reference/manipulate it with JavaScript.
I have updated the code as shown below:
Here is the Servlet's doGet method:
protected void doGet(HttpServletRequest req, HttpServletResponse json)
throws ServletException, IOException {
List<Employee> employees = uds.findAll();
req.setAttribute("employees", employees);
json.setContentType("application/json");
json.getWriter().write(String.valueOf(employees));
}
And here is what I currently have in JavaScript:
var ajax = new XMLHttpRequest();
ajax.open("GET", "http://localhost:8080/project1attempt/servlet", true);
// send request
ajax.send();
// event to get response
ajax.onreadystatechange = function() {
// Case state is 4 e o http.status for 200, your request is OK.
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
// the return
console.log(data);
}
}
}
The issue I am having at this point is that the client is not receiving data in JSON format. If I log the data as shown above, the log will produce something along the lines of the following:
[Employee{, employee_id='123456', email='lt#gmail.com', firstName='Juan',
lastName='Terri'}, Employee{, employee_id='2', email='sstark#mail.com',
firstName='Sansa', lastName='Stark'}]
This is the correct data, but not in a useful format.
However, if I try to do console.log(JSON.parse(data)), then I receive Uncaught SyntaxError: Unexpected token E in JSON at position 1.
I believe this is a simple syntax error on my part in the servlet, but am unsure of how to fix it.
You should use request.getAttribute():
<%
List<Employee> theEmployees = request.getAttribute("employees");
%>
But if you want to effectively use it in your javascript , it is recommended to convert it to json .
Try change your servlet response to json and get your data with Ajax
This is a sample to do it!
var ajax = new XMLHttpRequest();
ajax.open("GET", "your_url_here", true);
// send request
ajax.send();
// event to get response
ajax.onreadystatechange = function() {
// Case state is 4 e o http.status for 200, your request is OK.
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
// the return
console.log(data);
}
}
For other noobs like me, I've compiled the following complete solution for this issue:
The Servlet should look something like this:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
resp.setContentType("application/json");
List<Employee> employees = uds.findAll();
String json = new ObjectMapper().writeValueAsString(employees);
resp.getWriter().write(json);
uds.findAll() is a method which returns a list of objects. ObjectMapper is a Jackson utility (Gson is another option, I believe). This puts the list into JSON format.
The HTML or JSP should look like this:
var ajax = new XMLHttpRequest();
ajax.open("GET", "http://localhost:8080/project1attempt/servlet", true);
// send request
ajax.send();
// event to get response
ajax.onreadystatechange = function() {
// Case state is 4 e o http.status for 200, your request is OK.
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText;
// the return
console.log(JSON.parse(data));
}
}
This will get the list of objects in a usable format which you can then manipulate with JavaScript to do whatever you'd like. Hopefully this will help someone!
Related
I followed some guides on how to send json objects to the server(written using node.js) and it doesn't work, I have no idea what is wrong. I know that my server works fine since I tested it on postman so it's my js code that's the problem, all the tutorials I see follow a similar XMLHttpRequest format.
this is my code
var ing = new Ingredient(name, date, qty, rp);
var url = "http://localhost:8081/addIngredient";
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
//Send the proper header information along with the request
// application/json is sending json format data
xhr.setRequestHeader("Content-type", "application/json");
// Create a state change callback
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// Print received data from server
result.innerHTML = this.responseText;
}
};
// Converting JSON data to string
var data = JSON.stringify(ing);
document.write(data);
// Sending data with the request
xhr.send(data);
I used document.write to check where the code stops working but everything passes (since the document.write prints something), I suspect that there is something wrong/missing from xhr.send(data) but I can't tell what. Finally, nothing gets printed from the callback.
It's better to use onload instead of onreadystatechange
xhr.onload = function() {
if (xhr.status == 200) {
console.log(`Response length = ${xhr.response.length}`);
// store xhr.response here somewhere
}
};
I am a beginner in web development (self learner),and I am trying to connect my javascript .js file to java servlet through AJAX where I am stuck. It's not making the AJAX call, or not entering the java code, returning to the call back function. Is my url mapping or path specified correct? Or can you see some other error? Thanks!
JS code:
a = parseInt(document.getElementById("num"+ 0).value);
var xhr = new XMLHttpRequest();
xhr.open("GET", "/add?num1=" + a , true ); // true is for Asynchronous request
alert("here3 a=" + a);
xhr.send();
var ret = eval(xhr.responseText); //just trial
alert("eval" + ret);
xhr.onreadystatechange = () => {
if(xhr.readyState == 4 && xhr.status == 200){
document.getElementbyId('ajaxResponse').innerHTML = xhr.responseText;
var ret = eval(xhr.responseText);
alert("Callback1 = " + ret);
}
else(alert("Callback failed"))
};
Java servlet:
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
System.out.println("Add Servlet called");
int i = Integer.parseInt(req.getParameter("num1"));
// int j = Integer.parseInt(req.getParameter("num2"));
// int k = i+j;
PrintWriter out = res.getWriter();
out.println("Result is i=" + i);
res.setContentType("text/plain");
res.getWriter().write(i);
}
Web.xml
(servlet): callJava
com.AddServlet
(servlet-mapping):callJava
/add
It just goes in else condition of callback function ("Callback failed"). Also, does the location/folder structure of the servlet or js file matters, if mapping is done in .xml file? Thanks!
I can't really help you with the server side part as I'm not familiar with the framework that you are using. But the following are my recommendations for the client side code:
Use let instead of var;
true flag to make request async is not necessary because it is the default and will be soon deprecated.
It is preferable to use the new addEventListener API instead of directly adding the handler to the intended target.
Fully setup your request before calling open and send.
Use === operator instead of ==.
const a = parseInt(document.getElementById("num" + 0).value);
let xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', (e) => {
if(e.target.readyState === 4){
document.getElementbyId('ajaxResponse').innerHTML = e.target.responseText;
}
});
xhr.open("GET", "/add?num1=" + a);
xhr.send();
Please let me know if it works. If it does, you may want to check if your server is correctly setting the "found" response code (200).
Ok I figured it out, the url should just be "add?num1=" instead of "/add?num1=". It does map through .xml file! Now I am reaching java file and status is 200 :D
Next I am trying to figure out how to return back value any ajax response value from java servlet to javascript file or html file. Should I do it somehow in xhr.onreadystatechange() function? It's still not satisfying both conditions [if(xhr.readyState == 4 && xhr.status == 200)]. Any suggestions?
I have a js function which goes to a spring controller class returning a json object with data like :
{"prop1":"val1",
"prop2":"val2"}
The js function is something like :
accessValue(a,b,c){
var xmlhttp = new XMLHttpRequest();
alert("This works 1");
xmlhttp.onreadystatechange = function() {
alert("This works 2");
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
alert("This works 3" + xmlhttp.status);//line 1
if (xmlhttp.status == 200) {
var jsonobj = JSON.parse(this.responseText); //line 1
alert("Hi ");
document.getElementById(b).innerHTML = jsonobj.prop1;
document.getElementById(c).innerHTML = jsonobj.prop2;
console.log(jsonobj.prop2);
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
}
};
xmlhttp.open("GET", a + "--spring controller class path --");
xmlhttp.send(null);
}
In the function parameters b and c are div ids which I want to update with the data which comes in the json object. Parameter a is a URL which is appended with spring path of the controller class, this class returns json object which runs perfectly fine.
At line 1, I am getting status for xmlhttp.status as 0 which is empty response. After searching online I found out that this may happen bcz the file may be accessed locally properly but through server its not happening. The same code when used on localhost works great. Is there a way I could access this spring controller returned json object on server using proper http url and parse the data to update my divs ?
I'm trying to implement an ajax request that sends simple form data to a Go webserver, then return the same values in a response to the client (website).
Ajax request in javascript:
function addWheel(){
title = document.getElementById('title').value;
desc = document.getElementById('desc').value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhttp.open("GET", "/getCardInfo?title=" + title + "&desc=" + desc, true);
xhttp.send();
}
There error from the browser console I recieve says the internal server error occurs in "xhttp.send();"
Code from the webserver:
func ajaxHandler(w http.ResponseWriter, r *http.Request) {
//parse request to struct
fmt.Println("Ajaxhandler")
var d Data
err := json.NewDecoder(r.Body).Decode(&d)
q := r.URL.Query()
d.Title = q.Get("title")
d.Desc = q.Get("desc")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// create json response from struct
a, err := json.Marshal(d)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
_, err = w.Write(a)
if err != nil {
fmt.Println("handle error")
}
}
It runs all the way through without throwing any errors. It looks like it sends it at w.Write(a), so I assume there's an issue in my javascript. The variable d Data is just a struct containing 2 strings.
The handle function is defined in main like this: http.HandleFunc("/getCardInfo", ajaxHandler)
Can anyone see where the error lies?
This is regarding passing an array to a php page.Is it possible to send an array like this(code below)? if its not possible , what changes should i bring about to my code?
function ajax_post(){
var hr = new XMLHttpRequest();
hr.open("POST", "get_numbers.php", true);
hr.setRequestHeader("Content-type", "application/json");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
var results=document.getElementById("ace");
//results.innerHTML=data.u1.port;
for (var obj in data)
{
results.innerHTML+=data[obj].port;
}
}
}
var cards= new Array();
cards[0]="hearts";
cards[1]="spades";
hr.send(cards);
results.innerHTML = "processing...";
}
.send() doesn't take a javascript array. There are a number of forms of data you could send and you will have to decide which form is appropriate, but an array is not one of them. The simplest would be to turn the array into a JSON string and send that.
var cards = [
"hearts",
"spades"
];
hr.send(JSON.stringify(cards));
Then, on the receiving end of things, you would parse the JSON back into whatever language form you are using on the server end. If it's PHP, then you can use the PHP functions for parsing the JSON which will put the data into a PHP array on your server.
Per the MDN doc page for the XMLHttpRequest object, .send() can take the following types of data:
void send();
void send(ArrayBufferView data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);
Using JSON would be using the string type.