AJAX Not Loading JSON Object - javascript

I'm trying to do a simple GET request with an acronym finder API but for some reason the JSON is not being returned. Here is the code:
$.ajax('http://www.nactem.ac.uk/software/acromine/dictionary.py?sf=DOD', {
crossDomain:true,
dataType: "jsonp",
success: function(data){
console.log(data);
}
});
If I visit the url directly in my browser, I can easily see the requested JSON, but my Chrome console only returns:
Resource interpreted as Script but transferred with MIME type text/plain: "http://www.nactem.ac.uk/software/acromine/dictionary.py?sf=DOD&callback=jQuery1111025898682116530836_1417074190743&_=1417074190744".
The Chrome Debugger network tab indicates that the correct file was downloaded but why isn't the JSON being logged to the console?

The error message indicates that the response MIME type is 'text/plain'. But it is expecting a Script MIME type.
So you need to setup your response at backend dictionary.py (if it is under your control). Add content-type "application/x-javascript" to the response header. Something similar to (in Java):
#RequestMapping(value = "/test/fake")
public void testFake(HttpServletRequest request,
HttpServletResponse response) throws IOException {
String callback = request.getParameter("jsonpcallback");
SimpleJson json = new SimpleJson("Success", 0);
JSONObject resultJSON = JSONObject.fromObject(json);
response.setContentType("application/x-javascript"); // Set content-type to "application/x-javascript"
PrintWriter out = response.getWriter();
if (callback == null) {
out.println("{error: 'Callback function is not defined.'}");
} else
out.println(callback + "(" + resultJSON.toString(1, 1) + ")");
}

Try using this
$.ajax('http://www.nactem.ac.uk/software/acromine/dictionary.py?sf=DOD', {
crossDomain:true,
dataType: "json",
contentType: "application/json",
success: function(data){
console.log(data);
}
});

Related

Can't receive the json response being passed from rest api in html

Rest Api in is able to create json but my ajax is not able to receive the json content being passed from rest api.
function loadJsonData(){
var dropDownValue = document.getElementById("dropdown").value;
$.ajax({
url:'http://localhost:8085/ParsingJson/rest/service/resources/getjsondata/'+dropDownValue,
type:'get',
contentType: 'application/json; charset=utf-8',
cache:false,
success:function(data){
alert(data);
document.getElementById("mySavedModel").value = data;
load();
},
error:function(){alert('error');}
}
);
}
Rest api response code:
#RequestMapping(value = "/getjsondata/{dropDownValue}", method = RequestMethod.GET)
public ResponseEntity<DummyPojo> getJsonData(#PathVariable String dropDownValue) throws ApplicationException, ParseException{
System.out.println("In For Json Data:: " + dropDownValue);
DummyPojo dp = new DummyPojo();
dp.setAge("14");
dp.setName("Cap");
return new ResponseEntity<DummyPojo>(dp,HttpStatus.OK);
}
I want the JSON data in my html file.
There seems to be two possibility
dropDownValue is null OR
mySavedModel is not loaded yet
Please make sure that your page DOM is loaded before calling the loadJsonData

Asp / ajax call web service and GET xml

My code returns : interne server error
var parameters = "<?xml version='1.0' encoding='utf-8'?>" +
"<soap:envelope xmlns:xsi='ttp://www.w3.org/2001/xmlschema-instance' xmlns:xsd='http://www.w3.org/2001/xmlschema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" +
"<soap:body>" +
"<listeVille xmlns='http://..../b1'>" +
"<ville>"+ "Test" +"</ville>" +
"</listeVille>" +
"</soap:body>" +
"</soap:envelope>";
$.ajax({
type: "POST",
url: _URL_SITE + "webservices/b1.asmx",
dataType: "xml",
data: parameters,
contentType: "application/soap+xml; charset=utf-8",
headers: {
Accept: '*/*',
SOAPAction: 'http://.../webservices/b1/ListeVille' },
success: function (xml) {
alert('test');
//var _xmldoc
//_xmldoc = new activexobject("microsoft.xmldom");
//_xmldoc.async = "false";
//_xmldoc.loadxml(xml);
},
error: function () {
alert('error');
}
});
And my web service :
<WebMethod(True)> Public Function ListeVille(ByVal ville As String) As System.Xml.XmlDocument
Dim _xml As System.Xml.XmlDocument = New System.Xml.XmlDocument
Dim _hsh As New ParameterCollection
Try
_hsh.Add("#Ville", "")
_xml.LoadXml(_hsh)
Catch ex As Exception
AjoutJournal(ex)
End Try
Return _xml
End Function
I try to call my web service and get a xml file.
For information, don't focus on my function ListeVille, it returns the great value.
Thanks!
You are getting an Internal Server Error which means that there is an Exception in your server Side Code.
If you enable the Remote Errors then you can see the errors on the remote machine. Otherwise, if you debug the code on the machine, you can see the exception Details.
Moreover, the usage of XmlDocument.LoadXml Method doesn't seem to be correct as posted in your question. The Parameter to the LoadXml is a String containing the XML document to load. Try to pass in a valid XML. You can find more details on msdn here

XMLHttpRequest error on send

i'm doing my baby steps in web-development.
I have a Html+JS(jQuery) Frontend and a C# Backend.
For now i just want a ping-pong request/response.
The JS looks like this :
$(document).ready(function() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "http://testhttp/", false ); // false for synchronous request
xmlHttp.send();
console.log(xmlHttp.responseText);
});
The C# looks like this
if (!HttpListener.IsSupported)
{
...
}
string[] prefixes = {"http://testhttp/"};
// Create a listener.
HttpListener listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
Console.WriteLine("Listening...");
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = "<p> Hello world!</p>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer,0,buffer.Length);
// You must close the output stream.
output.Close();
listener.Stop();
The Backend receives the request. However the response will not be transmitted correctly or permission is denied (on Firefox and Chrome).
jquery-3.2.0.min.js:2 Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://testhttp/'.
I read that it might has something to do with the origin of the response and i need to set Access-Control-Allow-Origin. But those attempts failed.
Can someone pls guide me here?
Edit
Based on comments the js looks like this
$(document).ready(function() {
$.ajax({
url: "http://testhttp/",
type: "GET",
crossDomain: true,
dataType: "json",
success: function (response) {
$('#Test').html(response);
},
error: function (xhr, status) {
alert("error");
}
});
});
and in C# backend i added
response.Headers["Access-Control-Allow-Origin"] = "*";
Getting
GET http://testhttp/ net::ERR_CONNECTION_RESET

How to have NanoHTTPD respond to AJAX

I'm attempting to get NanoHTTPD (on an android device) to respond to AJAX requests in a way that the requesting javascript can interpret the response.
I've implemented the NanoHTTPD serve method:
public NanoHTTPD.Response serve(String uri, NanoHTTPD.Method method,
Map<String, String> header,
Map<String, String> parameters,
Map<String, String> files) {
String msg = "Hello, you have connected.";
return newFixedLengthResponse( msg );
}
And if I connect from the local webbrowser to "http://127.0.0.1:8080" it loads a page with the source:
<html>
<head></head>
<body>Hello, you have connected.</body>
</html>
So far so good, although I'm not sure where the html formatting is introduced.
But what I am stuck on is if I use AJAX from javascript to try to pass data:
$.ajax({
url: 'http://127.0.0.1:8080',
type: 'POST',
data:{ printData: dataToPrint },
success: function(d){
alert('success');
},
error: function (jqXHR, textStatus) {
alert("failed, jqXHR: " + jqXHR.responseText + " " + jQuery.parseJSON(jqXHR.responseText) + " textStatus: " + textStatus);
}
})
(This is just one example, I've tried success/fail/done/error methods, I've tried specifying the datatype, I've tried different parameters in the return functions, none of it works). When this javascript is run the NanoHTTPD server receives the printData just fine, but when it sends it response it is only ever the error/fail method that is triggered and the method parameters never contain anything - I cannot set the status or the return message or anything.
I've tried different returns from the Serve method including:
String mime_type = NanoHTTPD.MIME_PLAINTEXT;
String msg = "{\"status\":\"1\",\"responseText\":\"this is the response\"}";
InputStream testReply = new ByteArrayInputStream(msg.getBytes(StandardCharsets.UTF_8));
// return newFixedLengthResponse(NanoHTTPD.Response.Status.OK, "", msg);
// return new NanoHTTPD.Response( NanoHTTPD.Response.Status.OK, mime_type, testReply);
// return NanoHTTPD.newFixedLengthResponse( NanoHTTPD.Response.Status.OK, mime_type, msg);
// return NanoHTTPD.newFixedLengthResponse(msg);
None of these work.
I also tried this javascript:
$.get("http://127.0.0.1:8080", function( my_var ) {
console.log(my_var);
});
If this is run my breakpoint on NanoHTTPD is triggered, but the javascript method is not triggered at all.
I think you need to add these headers in your server response:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE
Access-Control-Max-Age: 86400

JSON Parse error: Unexpected EOF with AJAX, Javascript and Servlet in Java

I have an issue with my login request.
I get this error :
[object Object]
parsererror
SyntaxError: JSON Parse error: Unexpected EOF
The request is sent correctly (according to the network console) but when I'm receiving the response I get this error but I can't visualise the JSON object.
I'm using JavaScript, Ajax, jQuery and for the server side I'm using servlets in Java.
Here is my code
function connect(login, password){
$.ajax({
type : "GET",
url :"http://adress/log",
data : "login=" + login + "&pwd=" + password,
dataType : "json",
success : traiteReponseConnexion,
error : function(XHR, testStatus, errorThrown) {
console.log("echec");
alert(XHR + "\n" + testStatus + "\n" + errorThrown);}
});
}
function traiteReponseConnexion(el){
if(el.error != undefined){
console.log("ici" +el.id);
}else{
alert("I'm here");
window.location.href="main.jsp?id="+el.id+"&login="+el.login+"&key="+el.key+"";
}
}
In my servlet
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{
Map<String,String[]> pars = req.getParameterMap();
if(pars.containsKey("log") && pars.containsKey("pwd")){
String log = req.getParameter("log");
String pwd = req.getParameter("pwd");
resp.addHeader("Access-Control-Allow-Origin", "*");
resp.setContentType("application/json");
JSONObject user = UserLogin.authentifiateUser(log, pwd);
resp.getWriter().println(user);
}
}
I don't understand where is the problem. I have no response from the server in
the network console but in others services I don't seem to have this problem (logout for instance).
You may need to send more than just Access-Control-Allow-Origin; you may well need Access-Control-Allow-Methods and/or Access-Control-Allow-Headers as well, if a preflight is happening. If so, I believe you'll need to handle those in doOptions (not doGet).

Categories