I have a problem with a webservice i need to call to.
Situation
I need to get information from a webservice, build by the company I work for. If i try to get the information via SOAPUI there isn't any problem and i get the information i need in the response. But after editing a script so i can get it via the browser i get a 500 error.
Code
function soap() {
try {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'https://**testserver**/test/services/smsproxy2.smsproxy2HttpsSoap11Endpoint', true);
// build SOAP request
var sr =
'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sms="http://**service**/smsreport">' +
'<soapenv:Header/>' +
'<soapenv:Body>' +
'<sms:GetSMSReport>' +
'<sms:FromDate>2015-01-01</sms:FromDate>' +
'<sms:ToDate>2015-12-12</sms:ToDate>' +
'</sms:GetSMSReport>' +
'</soapenv:Body>' +
'</soapenv:Envelope>';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert('Working fine! See the console.');
}
}
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
var result = xmlhttp.send(sr);
}
catch (error) {
alert('An error occurred: ' + error);
}
}
soap();
Explanation
This entire code is put in a html file. This code is between script tags in the html head tag.
The **testserver** and **service** parts are different in the real script.
Problem
As soon as i open this (html)file in the browser, i get an 500 (internal Error) message in the console. The row which is specified with this message is the row on which the xmlhttp.send(sr) action is set.
Effect
I can't get the information i need within the server. So i can't show anything on the webpage.
Questions
Why do i get a 500 error in the browser and does this work without problems in SOAP UI? The URL which is called is exactly the same in the browser as it is in SOAP UI, so this shouldn't be possible.
How do i solve this?
Tried
A lot of things, but nothing helped.
After making the connection easier (directly and not via a proxy), there was an error in the errorlog.
It said that the endpoint wasn't right, but this seemed okay. Also the XML seemed okay.
After trying some things i found the solution:
Solution
The following row gives the error:
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
I've deleted this row from my script and now it works fine.
Related
I have a number of AJAX requests (made with regular JS) that seem to be causing trouble when they make requests of my Python GAE back end. Here's an example:
newGame: function() {
// Calls API to begin a new game, tells view to show placements
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === XMLHttpRequest.DONE) {
// ... removed unnecessary code for this question
}
};
var requestOjb = {"user_name": battleshipCtrl.user};
xhttp.open('POST', requestPath + 'game', true);
xhttp.send(JSON.stringify(requestOjb));
},
I am getting a code 400 with a Parse Error, but only on my deployed server. Everything works fine on the dev server. The error says the problem is with my back-end function "new_game", but does not specify a line where the error occurred. The endpoint function works correctly when I access it directly from the API explorer, so I figure the problem must be a result of the data sent from my JS file. Here's that function anyway:
#endpoints.method(request_message=NEW_GAME_REQUEST,
response_message=GameForm,
path='game',
name='new_game',
http_method='POST')
def new_game(self, request):
"""Creates new game"""
user = User.query(User.name == request.user_name).get()
# ... removed unnecessary code for this question
return game.to_form('Good luck playing Battleship!')
The request message it's expecting takes the form of {'user_name': 'some_name'} and it appears, through console.log, that JS is sending it in the right format.
The log where the parse error comes up is interesting, because it shows a 200 code POST request, although it mentions the 400 error when I dive into that log.
I've double and triple checked that my code works on the dev server, and that I've got the exact same code deployed. I don't know where to look next to continue debugging this thing. Any help is appreciated.
Figured it out. I tried running the AJAX request with jQuery, and got a slightly different error message, which lead me to find that I had to set the request header, because it was causing the server to read the incoming data differently than it should have. The following AJAX request now works perfectly.
newGame: function() {
// Calls API to begin a new game, tells view to show placements
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === XMLHttpRequest.DONE) {
// ... removed unnecessary code for this question
}
};
var requestOjb = {"user_name": battleshipCtrl.user};
xhttp.open('POST', requestPath + 'game', true);
xhttp.setRequestHeader('Content-type', 'application/json');
xhttp.send(JSON.stringify(requestOjb));
},
i want to make a script that makes every video's comment section look like the ones that still have the old kind.
for example, videos on this channel:https://www.youtube.com/user/TheMysteryofGF/videos
in Firebug, in the Net tab, i noticed the comment JSON file's URL it is requested from is different.
i tried to run a code on the youtube watch page which would request the file the same way, but it doesnt work, and in firebug it says it was forbidden.
the URL is the same, they are both POST, and i cant figure out what is different. i can even resend the original request in firebug and it works... so anyway, here is a code i tried on a video with "1vptNpkysBQ" video url.
var getJSON = function(url, successHandler, errorHandler) {
var xhr = typeof XMLHttpRequest != 'undefined'
? new XMLHttpRequest()
: new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('post', url, true);
xhr.onreadystatechange = function() {
var status;
var data;
// https://xhr.spec.whatwg.org/#dom-xmlhttprequest-readystate
if (xhr.readyState == 4) { // `DONE`
status = xhr.status;
if (status == 200) {
data = JSON.parse(xhr.responseText);
successHandler && successHandler(data);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
getJSON('https://www.youtube.com/watch_fragments_ajax?v=1vptNpkysBQ&tr=time&frags=comments&spf=load', function(data) {
alert('Your public IP address is: ' + data);
}, function(status) {
alert('Something went wrong.');
});
You are using Ajax to get data. Ajax has 1 restriction: You can only get data from your own server. When you try to get data from another server/domain, you get a "Access-Control-Allow-Origin" error.
Any time you put http:// (or https://) in the url, you get this error.
You'll have to do it the Youtube way.
That's why they made the javascript API. Here is (the principal of) how it works. You can link javascript files from other servers, with the < script > tag
So if you could find a javascript file that starts with
var my_videos = ['foo', 'bar', 'hello', 'world'];
then you can use var my_videos anywhere in your script. This can be used both for functions and for data. So the server puts this (dynamically generated) script somewhere, on a specific url. You, the client website can use it.
If you want to really understand it, you should try building your own API; you'll learn a lot.
Secondary thing: Use GET.
POST means the client adds data to the server (example: post a comment, upload a file, ...). GET means you send some kind of ID to the server, then the server returns its own data to the client.
So what you are doing here, is pure GET.
I am running Flask on GAE with a google app engine backend. I submit a form on my site, send it to the backend, the backend returns an xml file and I would like to serve up that xml file. However, I have an issue serving up my file.
This is the only way I could figure out how to serve up my file, it works, but it returns 2 identical files in the browser instead of one, what am I doing wrong?
On the frontend jQuery:
$.get('submit',
dat,
function(data, status, request) {
if (status = 'success'){
console.log(status);
$("body").append("<iframe src='" + request.getResponseHeader('redirect')+ "' style='display: none;' ></iframe>");
}
else
alert("There is an exception on server side while submitting the response!");
},
'xml');
On the frontend Python:
#app.route("/submit", methods=["GET"] )
def submit():
... do some stuff to get the data and url packaged...
headers = {'content-type': 'application/json', 'charset':'UTF-8'}
r = requests.post(url, data=json.dumps(jsonstring), headers=headers)
response = make_response(r.text)
response.headers["Content-Type"] = 'application/xml'
response.headers.add("redirect", request.url)
response.headers["Content-Disposition"] = 'attachment; filename="exportChecklists.xml"'
return response
Basically, I added a redirect url which was my request url to start with, so when the file was ready, I just created an hidden iFrame that modern browsers redirect to and prompt for download.
How can I modify this to only get 1 file instead of 2?
Thanks for the help.
UPDATE
I have tried doing a synchronous post and still no prompt for download. (I am making a call to my server, and response comes as an XML file from my server).
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "POST", "/submit", false );
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send( JSON.stringify(dat ));
return xmlHttp.responseText;
Response Headers:
Cache-Control:no-cache
content-disposition:attachment; filename="exportChecklists.xml"
Content-Length:76
content-type:application/xml
Date:Fri, 27 Dec 2013 22:59:27 GMT
Expires:Fri, 01 Jan 1990 00:00:00 GMT
Server:Development/2.0
UPDATE #2
I still can't figure out how to do this so I only serve one file. While the below explanation is good in general, I can't figure out how to serve only 1 file using jQuery. Could someone please provide an example on how to do this.
The only probable thing i can think of without seeing the server side code, is the following scenario:
SCENARIO:
First lets do some reverse engineering, lets examine the following snippet in your code:
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "POST", "/submit", false );
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send( JSON.stringify(dat ));
return xmlHttp.responseText;
OBSERVATION 1:
The line 6 of the snippet return xmlHttp.responseText; proves that the page that you're opening outputs something, i.e. the XML code, since you're attempting to return it.
CONCLUSION 1:
This output that you're printing, is one of the two XML files that get downloaded.
OBSERVATION 2:
Lets see this line of code content-disposition:attachment; filename="exportChecklists.xml"
This prompts the browser to download the XML, to the computer.
CONCLUSION 2:
This is the second XML file that gets downloaded.
NOTE:
This is the best guess made by me without looking at your server code, so think before you downvote, please...
MY RESEARCH AFTER, AlexIIP'S COMMENT:
Let's analyse the jQuery code:
$.get('submit',
dat,
function (data, status, request) {
if (status = 'success') {
console.log(status);
$("body").append("<iframe src='" + request.getResponseHeader('redirect') + "' style='display: none;' ></iframe>");
} else alert("There is an exception on server side while submitting the response!");
},
'xml');
Specifically this line:
$("body").append("<iframe src='" + request.getResponseHeader('redirect') + "' style='display: none;' ></iframe>");
when you append the result of request.getResponseHeader('redirect') as the source of the iframe, its clear that the request doesn't return the XML but a redirect header attribute that points to the XML, so, you get the XML in the iframe and the header content-disposition:attachment; filename="exportChecklists.xml" prompts a download, that's why, you get two downloads. (probably, the iframe and the doc, both try a download, resulting in 2 downloads..)
Now the reason why you get no downloads in JavaScript can be easily understood once you understand the above paragraph, what we can conclude from the above paragraph is:
The response doesn't contain any XML, but a header of the response ("redirect") points to XML code file...
So in JavaScript, when you do return xmlHttp.responseText; you are returning the text (HTML) that the response has, but what really you have is a redirect header with the url of the XML file. So to get XML, instead of:
return xmlHttp.responseText;
you shall do this:
return xmlHttp.getResponseHeader('redirect');
but the above line will return the path to the XML file, and hopefully prompt one download...
I am quite new in this area.
I need to find out how to make a request to my solr server using Ajax
How can I give a url(my solr server's url) in request
Any body know how to deal with this?
How can i make a request to the below mentioned url
http://mysite:8080/solr/select/?q=%2A%3A%2A&version=2.2&start=0&rows=100&indent=on
See here: Corrected the Code Snippet as below
function getProductIds() {
var xmlhttp;
if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) console.dir(xmlhttp);
else alert('no response');
var ajaxURL = "http://localhost:8080/solr/select/?q=*:*&version=2.2&start=0&rows=100&indent=on";
xmlhttp.open("GET", ajaxURL, true);
xmlhttp.send();
}
This is my code, it always showing "no response"
Thanks.
You will have to prepare the URL before sending in the request first get the URl using javascript and then encode it to ajax format like below
var URL = location.href;
var ajaxURL = encodeURIComponent(URL);
xmlhttp.open("GET",ajaxURL,true);
after reading your question clearly it seemed it is a static URL hence you can do below
var URL = "http://localhost:8080/blah blah blah";
xmlhttp.open("GET",URL,true);
Are you sure it is Get request. because get requests are most of the time cached. also log the response object into Firebug console and inspect the object to know more. Since you get no response that means the server did not send you anything for the request you made.
I'm just now working on XMLHttpRequests to solr as well and I was stuck with what seems like an identical problem. I too am quite new at this. However, the problem for me was that of same origin policy. Firefox seems to give very little feedback when this problem occurs. Chrome at least give you a error message (most of the time?).
In Chrome you can get around this, but only for development purposes, by starting it with the '--disable-web-security' command line option.
I'm yet to find a good workaround for this problem for Solr. In general you avoid the restriction by only using requests with relative paths, but that doesn't seem possible when doing a request to another port.
Ways to circumvent the policy (I haven't had time to study this too much yet)
$.ajax({
url: "url path",
context: document.body
}).done(function(data) {
alert(data);
});
This one also will work.
I have an XMLHttpRequest opened with the POST method, to a URL that I know exists because I've just done a GET on it.
However, the send() call on the XHR doesn't actually open any connection to the server or send any data -- I've verified this with WireShark.
Instead, it just fails the request, calls the onreadystatechange event handler, setting status to 0 (meaning, according to the spec, that the "error flag" is set).
But... there's no way for me to inspect WHAT is going wrong. I've tried this in FireBug, and the headers and body look OK; there is no response body or response headers. The line in the console output is a POST /url (x) where the (x) is a red circle with an X in it. No error reason is visible anywhere. That same line is not in the NET panel at all. This is probably a clue, but I don't know of what.
function save_edits(url, txt, cb)
{
var xhr = new XMLHttpRequest();
console.log("'POST' " + url);
xhr.open('POST', url, true);
xhr.onreadystatechange = function(ev)
{
if (xhr.readyState == 4)
{
console.log('post complete status:' + xhr.status);
cb();
}
}
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var text = "&" + edit_what + "=" + escape(txt.replace(/\r/g, '\n'));
try
{
xhr.send(text);
}
catch (e)
{
console.log('send() error: ' + e.toString());
}
This outputs in the FireBug console:
'POST' http://mydomain.com/srv.json.section-xna.latest
POST http://mydomain.com/srv.json.section-xna.latest source.js (line 70)
post complete status:0
Line 1) is my console log statement.
Line 2) is the POST XHR request, which is red, with the circle-X showing failure.
Line 3) is the console log statement from the onreadystatechange handler.
There is no exception raised (I put that check in there just for paranoia) -- even if I make the open() be synchronous instead of asynchronous.
Again, this is not a server-side problem, because the request doesn't even make it onto the wire, and I don't know how to figure out why that is.
Is the URL on your domain or an alternative domain? If it is an alternative domain you are most likely being blocked due to cross domain security issues.
Thanks for the suggestions, everyone! It turns out to be a problem at a higher level.
The code that was calling the save function was then immediately calling window.location.reload() to see the new data, which ended up canceling the outstanding POST request.
Can't believe I had to go through WireShark AND Stack Overflow just to be able to see that problem...