Error 400 with ajax request - javascript

I am new to web development, and I guess that it is a basic issue, but I couldn't find a solution on the internet.
To start, what I am trying to do is to have a script, loaded on a webpage using TamperMonkey, download a xml file located on a php server.
The process worked perfectly when I tested it on localhost (using MAMP), but then I put it on a 000webhost server, and it's not working, I get an Error 400 Bad request in the ajax response. I also tried on other web hosting services and I get the same error.
On the other hand, the request works perfectly on the 000webhost server when I'm just sending it though my google chrome searchbar. Also, the url to which it is sent is well formed, as when I console.log it, and then click the link, it does what it should.
I am using the GM_xmlhttpRequest method. Here is the code :
let url = some_correct_url;
GM_xmlhttpRequest({
methode: "GET",
url: url,
headers: {
"Accept": "text/xml"
},
onload: function(response){
var r= null;
if (!response.responseXML){
r= new DOMParser().parseFromString(response.responseXML, "text/xml");
}
r= response.responseXML;
console.log(r);
console.log(response.responseText);
});
});

You have a typo in your request body.
Typo: methodE: "GET"
Please correct the typo so it reads method: "GET" and let us know the results.

Related

jquery $.ajax gives 404 not found. Im using node.js with express

This jquery:
$.ajax({
method: "post",
data: JSON.stringify(data),
contentType: "application/json",
url: "http://localhost:3000/ajax"
});
is giving error 404 not found. Here is my server side:
router.get('/ajax', function(req, res ,ext){
var strings = ["rad", "bla", "ska"]
console.log('body: ' + JSON.stringify(req.body));
console.log("AJAX RECEIVED");
res.send(strings);
});
so i do have the /ajax route. When i go to http://localhost:3000/ajax im able to acccess the site . However, when I try to access it with the ajax method I get the 404 error. So im wondering if the error could be with my code, or if it could be the firewall on my computer. Im actually using a company computer that has a firewall that blocks certain sites and I cannot disable it.
If you want to do a HTTP POST, use router.post, not router.get.
your $.ajax call is using POST but your route in express.js is only listening for GET requests.
When you hit the URL through the browser it's doing a GET, so it worked.
You would need to set up a route for POST with router.post('/ajax', ...)

JQuery ajax GET request to URL fails although HTTP status is 200 OK

I apologize if this question has already been answered.
I am trying to retrieve data from a REST web service that exposes a JSON interface using jQuery .ajax call.
When I call the service using the URL, the jQuery call fails although I get a HTTP status code 200 OK.
When I copy the response into a file on the filesystem and retrieve this, the same call works.
Both the file I am accessing and the web service I am calling are on the same machine.
Some notes on the url used in the code below:
Using:
url: "http://localhost:9090/app/user/861",
the call fails, goes into .fail on all browsers.
The URL itself returns the json on all browsers:
{
"userid": 861,
"employeeno": "123",
"jobdesc": "Developer",
"firstname": "Jasper",
"lastname": "Fitussi"
}
when using "test.json" in the local filesystem following is the behavior:
url: "ajax/test.json",
On Firefox, the call executes, goes into .done and displays the result on page.
On Chrome, the call fails with status 404 and the following message -
"No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."
I tried different combinations changing dataType:"jsonp", adding a ?callback=? to the end of the URL, and enclosing the data in the test.json with a '(' and a ')' without luck.
Please understand I am new to UI programming, javascript and jQuery.
Please help with what I am doing wrong. Here's the javascript:
<script src="http://code.jquery.com/jquery-1.10.2.js" type="text/javascript">
</script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url:"ajax/test.json",
// the following commented call fails, goes into .fail
// url:"http://localhost:9090/app/user/861",
contentType: "application/json",
accepts: "application/json",
dataType: "json"
})
.done(function(data) {
alert("Success");
console.log(data);
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>");
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
})
.fail(function(data) {
console.log(data);
alert("Failed");
})
.always(function() {
alert("In Always");
});
});
</script>
The following is the output when I paste the url into the browser (also the contents of ajax/test.json):
{
"userid": 861,
"employeeno": "123",
"jobdesc": "Developer",
"firstname": "Jasper",
"lastname": "Fitussi"
}
Your problem is not about UI programming, it's about the security model of modern browsers :p
Access-Control-Allow-Origin errors occurs when you call a webservice (ie: load a JSON file) from a domain that is different from the one hosting your HTML page.
In your case, you are opening the html file from your hard drive (file:///) and calling a webservice on localhost.
This is a security feature in all modern browsers that forbid getting data from a foreign webservice without the webservice owners authorizing you (or everyone, wildcards are allowed) to call it.
I recommend reading the following guide from MDN, so that you understand WHY you are having this problem.
It will then be easy to resolve
https://developer.mozilla.org/en/docs/HTTP/Access_control_CORS
If you control the source code of the webservice, or the webserver hosting it, you need to add Access-Control-Allow-Origin HTTP headers.
Do you make your ajax call using Apache on wamp, lamp, xampp or mamp or not? I think you work directly using some files lets say on your desktop and not from the www file of wamp. If the browser sends a correct url then the backend responds great, your frontend code seems fine so i think chrome complains about your not using localhost. Am i right? Whats your local development setup?
If it's a local file on the client-side, use file:/// to prefix the URL:
url: 'file:///ajax/test.json'
The third / in file:/// indicates:
As a special case, can be the string "localhost" or the empty
string; this is interpreted as `the machine from which the URL is
being interpreted'.
3.10
Reference here
Download a tool called fiddler, from http://fiddler2.com/ great way to debug web requests and to see why they are failing.
This will help you narrow down the issue you are experiencing and we can help you further because currently its all guess work.
I had the same issue, all worked fine in I.E and FireFox, a had one ajax call to a rest service using jsonp and it worked fine in chrome, however when I tried to load a file using jsonp I got the cross domain error. In short i had to add "file:" to my file path in the url
$.ajax({
type : 'GET',
url : 'file:jsondata/rain_acc_data.json',
dataType : 'jsonp',
jsonpCallback : "jsoncallback",
success : function(data) {
aler('ok');
},
error : function(jqXHR, status) {
alert("Failed to load list" + status + jqXHR);
}
});
this worked for me, make sure to wrap your json in the file with jsoncallback("your jason here");

Send a request with openlayers

I am trying to make a request to a SOS service using Openlayers like this (part of the code):
var params = {'service':'SOS','version':'1.0.0','request':'getCapabilities'};
var paramString = OpenLayers.Util.getParameterString(params);
url = OpenLayers.Util.urlAppend(this.url, paramString);
OpenLayers.Request.GET({url: url,
success: this.parseSOSCaps, scope: this,
failure: alert(url)});
}
For some reason the url that I produced in this code is not correct. The failure function, alerts this url:
http://cawa.gfz-potsdam.de:8080/SOS/sos?service=SOS&version=1.0.0&request=getCapabilities
I also tried manually, through my browser to send the request (using the above url) but it doesn't work. I am sure that the host server is correct.
My questions are: what am I doing wrong? Is the above format of the url wrong? What would be the alternative? Perhaps to send the request in XML format?
Thanks
Dimitris
After all I managed to make the above code to work. There is not a bug in the code. The problem was that I haven't included in the allowedHosts of the proxy.cgi (wamp\bin\apache\apache2.2.22\cgi-bin\proxy.cgi) file, the host of the service. After I did it was working perfectly.

Sinatra not recognising javascript for session

I'm trying to log into a Sinatra app with jQuery, but Sinatra is just not seeming to recognise it at all for some reason, here is my code to see if the user is logged in:
Sinatra app:
get '/logged_in' do
if session[:logged_in] == true
status 200
"OK"
else
status 200
"False"
end
end
When I browse to /logged_in in my browser, I see OK, but when I execute the following Javascript, I get False printed to the console - seems bizarre to me.
var r = $.ajax({
type: "GET",
url: "http://xxx-xxx.com/logged_in"
});
r.success(function(msg) {
console.log(msg);
});
Any insight would be appreicated!
It would be good if you could give more details. (Browser, chronological request log including HTTP status codes, or even a dump from wireshark.) However here is my guess:
var r = $.ajax({
cache: false,
type: "GET",
url: "/logged_in",
success: function(msg) {
console.log(msg);
}
});
Some browsers aggressively cache AJAX requests, in particular GET requests. So you may want to try cache: false. Adding the success function later also seems odd to me, I have never seen that in any code.
Edit: Is the server answering the AJAX request on the same domain? (The domain must be the same as in your browser test.) Usually it should not be necessary to specify the domain inside the URL, so I removed it in the code here. So after all it might be a problem due to the Same Origin Policy.
I would place my bet on this being a jQuery issue rather than a Sinatra issue. Check that the cookie is being sent for the ajax request. There are a number of reasons why the cookie is not getting sent.

Ajax call from Greasemonkey to a Servlet: response failure

Though I've programming experience, am completely new to GS, JS, or anything related to UI.
Scenario: Making an AJAX call from Greasemonkey script to a Servlet
Greasemonkey/JS Code:
function getResultsData(query){
alert("Getting the Data");
$.ajax(
{
cache: false,
data: {"q":query},
dataType:"text",
url: "http://myserver.com:8000/search?",
success: processData
}); //end of $.ajax }
function processData(data){
alert("Got the data");
var myResultDiv = document.getElementById("searchRes");
myResultDiv.innerHTML = data; }
Servlet Code:
System.out.println("-----------This is an AJAX call------------------");
//Commented the original logic
resp.setContentType("text/plain");
resp.setCharacterEncoding("UTF-8");
resp.getWriter().write("Text from Servlet");
Problem:
GS/JS code works perfectly if the url (in $.ajax) is some other existing API. Response reflects in the UI
However, when I give my server's url, I can observe in the Firebug.Console that there's no http response for that call but the status says 200 OK with the whole entry turned 'RED'.
When I test the url copied from Firebug's 'http call entry', it's working perfectly as I can see the response 'Text from Servlet' on the new tab.
Can someone please help.
NOTE Website on which greasemonkey runs, and my server belong to same domain, i.e.
Greasemonkey website: wwww.example.com
My server: www.myserver.example.com
Thanks to #mattedgod. His comment triggered me to research more and I found the answer.
Add the following snippet to make it work.
response.setHeader("Access-Control-Allow-Origin", "*");
Surprisingly, it doesn't work if I explicitly specify my own server's full http address in the header. I yet to find out why.

Categories

Resources