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
Related
I have ajax connection with controller
function changeEmail() {
$.ajax({
...
contentType: "application/json",
dataType: "json",
...
error: function (error) {
var obj = error.responseText;
console.log('Error: ' + obj);
console.log('Obj length: ' + obj.fieldErrors.length);
}
});
}
Which in case of error returns a list of errors in json.
However, he is not able to refer to this list.
https://zapodaj.net/e6354b8c71f4c.png.html
I do not know, for example, how to refer to the first element of a list to the
message
variable
Depending on the content-type response from your server, the default response type is probably text/html or some other incorrect content-type.
You have two ways to fix this.
First, you can set obj = JSON.parse(error.responseText)
or, you can make sure that the server sets the correct content-type on errors as well.
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
I'm attempting to use jQuery in order to fire off an Ajax call after clicking a certain button. I've read several examples of the syntax and issues that may be encountered, but have failed to find a working solution for my cause. Here's the code.
Controller Method: (HomeController.cs)
[HttpPost]
public JsonResult ChangeCompany(string companyCode)
{
return Json(new { result = companyCode }, JsonRequestBehavior.AllowGet);
}
jQuery Code:
function changeCompany(company) {
$.ajax({
url: '#Url.Action("ChangeCompany", "Home")',
type: 'POST',
data: JSON.stringify({ companyCode: company }),
success: function (data) {
alert("Company: " + data);
},
error: function (req, status, error) {
alert("R: " + req + " S: " + status + " E: " + error);
}
});
}
And finally, I'm calling this function with:
$('.companyButton').click(function () {
compCode = $(this).text();
debug("Click event --> " + $(this).text());
changeCompany(compCode);
});
My debug message displays properly, and the Ajax call constantly fails with the following alert: R: [object Object] S: error E: Not Found
I'm not entirely sure what to make of that.
I know there are several questions on this topic, but none of them seem to resolve my issue and I'm honestly not sure what's wrong with these code blocks. Any insight would be appreciated.
EDIT:
In case it's worth noting, this is for a mobile device. Testing on Windows 8 Phone Emulator (Internet Explorer), alongside jQuery Mobile. Not sure if that affects Ajax at all
EDIT 2:
After taking a look at the raw network call, it seems that 'Url.Action("ChangeCompany", "Home")' is not being converted into the proper URL and is instead being called directly as if it were raw URL text. Is this due to an outdated jQuery, or some other factor?
Ok with your EDIT2 it seems you are using url: '#Url.Action("ChangeCompany", "Home")', in a separate JavaScript file. you can only write the razor code inside the .cshtml file and it is not working inside the .js files
You are missing some important parameters in your AJAX call. Change your AJAX call as below:
function changeCompany(company) {
$.ajax({
url: '#Url.Action("ChangeCompany", "Home")',
type: 'POST',
data: JSON.stringify({ companyCode: company }),
success: function (data) {
alert("Company: " + data);
},
error: function (req, status, error) {
alert("R: " + req + " S: " + status + " E: " + error);
}
});}
You can then annotate your controller method with [HttpPost] attribute as below;
[HttpPost]
public JsonResult ChangeCompany(string companyCode)
{
return Json(new { result = companyCode }, JsonRequestBehavior.AllowGet);
}
Note that your action is not returning companyCode directly. You're assigning it to Json result property therefore
In your success function to display result you need to have:
success: function (data)
{
alert("Company: " + data.result);
}
Also this: E: Not Found tells me that you may have some routing issues. If you set a break point inside of your ChangeCompany Action, is it being hit ?
I have made Restfull WS in VS 2010 with two simple method (one GET, another POST). They look like:
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "createUser")]
string createUser();
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, UriTemplate = "loginUser/{email}/{password}")]
string loginUser(string email, string password);
}
Definition of these methods is simple:
public class Service1 : IService1
{
public string createUser()
{
return "Successful POST call !!! ";
}
public string loginUser(string email, string password)
{
return "Successful GET call !!! " + email + " - "+ password;
}
}
I have published this service to IIS and tested my method in browser (only loginUser (GET) method, cannot test createUser (POST) method by the browser) and method (loginUser ) work fine.
When I tried to call method by jQuery AJAX, I am always getting error call without any notification. I checked my fiddler and there are the right response.
My Ajax method:
$(document).ready(function(){
$("#button2").click(function(){
$.ajax({
type: "GET",
url: "http://localhost/AutoOglasi/Service1.svc/loginUser/bole/bole",
success: function (response) {
alert("respons "+response);
},
error: function (request, status, error) {
alert(request.responseText+" -- " + status + " --- "+ error);
}
});
});
});
I mozila firebug i section XML I get this:
XML Parsing Error: no element found Location: moz-nullprincipal:{ba25ef4a-f215-486e-b965-e70714c5af31} Line Number 1, Column 1:
^
What I am doing wrong here, I just cannot figure out, because fiddler is giving me good response?
You state ResponseFormat = WebMessageFormat.XmlResponseFormat and what you return is not xml but a string. It expects the first character to be a < but its a S thats why its not finding an element at position 1
I have this controller method:
public JsonResult List(int number) {
var list = new Dictionary <int, string> ();
list.Add(1, "one");
list.Add(2, "two");
list.Add(3, "three");
var q = (from h in list where h.Key == number select new {
key = h.Key,
value = h.Value
});
return Json(list);
}
On the client side, have this jQuery script:
$("#radio1").click(function() {
$.ajax({
url: "/Home/List",
dataType: "json",
data: {
number: '1'
},
success: function(data) {
alert(data)
},
error: function(xhr) {
alert(xhr.status)
}
});
});
I always get an error code 500. What's the problem?
Thank you
If you saw the actual response, it would probably say
This request has been blocked because
sensitive information could be
disclosed to third party web sites
when this is used in a GET request. To
allow GET requests, set
JsonRequestBehavior to AllowGet.
You'll need to use the overloaded Json constructor to include a JsonRequestBehavior of JsonRequestBehavior.AllowGet such as:
return Json(list, JsonRequestBehavior.AllowGet);
Here's how it looks in your example code (note this also changes your ints to strings or else you'd get another error).
public JsonResult List(int number) {
var list = new Dictionary<string, string>();
list.Add("1", "one");
list.Add("2", "two");
list.Add("3", "three");
var q = (from h in list
where h.Key == number.ToString()
select new {
key = h.Key,
value = h.Value
});
return Json(list, JsonRequestBehavior.AllowGet);
}
While JustinStolle's answer solves your problem, I would pay attention to the error provided from the framework. Unless you have a good reason to want to send your data with the GET method, you should aim to send it with the POST method.
The thing is, when you use the GET method, your parameters gets added to your request url instead of added to the headers/body of your request. This might seem like a tiny difference, but the error hints why it's important. Proxy servers and other potential servers between the sender and the receiver are prone to logging the request url and often ignore the headers and/or body of the request. This information is also often regarded as non important/secret so any data exposed in the url is much less secure by default.
The best practice is then to send your data with the POST method so your data is added to the body instead of the url. Luckily this is easily changed, especially since you're using jquery. You can either use the $.post wrapper or add type: "POST" to your parameters:
$.ajax({
url: "/Home/List",
type: "POST",
dataType: "json",
data: { number: '1' },
success: function (data) { alert(data) },
error: function (xhr) { alert(xhr.status) }
});