Asp / ajax call web service and GET xml - javascript

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

Related

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

Javascript getJSON to PHP file in IIS using jsonp with variable

I am hosting an HTML5, JavaScript, and CSS3 https application on Windows IIS (Internet Information Services). How the root directory looks is this:
index.html, src/index.js, src/send_payment.php
I am trying to return a simple string at the moment from the php file using getJSON with jsonp (for security). Here is non-working code:
index.js
var json_obj = {
"data_value": 5489798123489725,
"payment_amount": 10.50,
}
var json_str = JSON.stringify(json_obj);
$.getJSON("https://localhost:443/src/send_payment.php?callback=?", "json_str=" + json_str, function (data) {
try {
console.log("SUCCESS >> " + JSON.stringify(data));
}
catch (e) {
console.log("ERROR >> " + e.toString());
}
});
send_payment.php
<?php
try {
// 1. get data
$json_str = $_GET["json_str"];
// 2. parse the json string
$json_obj = json_decode($json_str);
// 3. get the parameters
$data_value = $json_obj->{"data_value"};
$payment_amount = $json_obj->{"payment_amount"};
}
catch (Exception $e) {
trigger_error("ERROR >> exception = " + $e->getMessage(), E_USER_ERROR);
}
return "test successful";
?>
I'm not sure if the code is right or missing anything, but the issue is that I get 404 (Page not found) from getJSON. Is the URL wrong? I am accessing IIS locally, thus the localhost in the URL. I get error 405 (Method not allowed) when using AJAX POST instead with the same URL. Thank you.
I would recommend you to go for $.ajax and POST method like below:
$.ajax({
type: 'POST',
url: 'src/send_payment.php',
async: false,
data: {'data_value': 5489798123489725,'payment_amount': 10.5 },
success: function (response) {
//do whatever you want here }
});

Download file using API not working

I have an issue with my API call to my download method.
Here is the JS code I'm using, it's used with knockout:
self.downloadFile = function(file) {
// Ajax Call Get All Leave Records
$.ajax({
type: "POST",
url: "/api/v1/CompanyFilesApi/DownloadFile",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: ko.toJSON(file),
success: function (data) {
console.log("Here is your file");
},
error: function (error) {
alert(error.status + " <--and--> " + error.statusText);
}
});
// Ends Here
};
And here is my API solution:
public HttpResponseMessage DownloadFile(FileModel file)
{
var path = file.FilePath;
var result = Request.CreateResponse(HttpStatusCode.OK, file.FileName);
var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}
The file parameter contains the file path and name.
Can anyone tell me what I'm doing wrong?
The response is always ok but it goes on the error branch and the file is not open. The files are PDF, Excel, Word.
EDIT 2:
You can use target="_blank" instead of download to open the pdf in a new tab.
To modifify the 'a' tag :
$("#your-a-tag-id").attr("href", "data:application/octet-stream;base64," + fileDataString);
EDIT:
This could also help you
link
One solution would be to encode to base64 and use it as such :
...
dataType: "application/octet-stream;base64"
...
then put the response data in a href
<a href="data:application/octet-stream;base64,/*YOUR FILE DATA*/" download="your filename">
I'm not sure how to deal with that in your API though.

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

AJAX Not Loading JSON Object

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);
}
});

Categories