Why do I get this 501 Not Implemented error? - ajax

I am performing the following AJAX call:
$(document).ready(function() {
$.getJSON('https://sendgrid.com/api/user.stats.json',
{
'api_user': 'me#mydomain.com',
'api_key': 'MYAPIKEY',
'user': 'me#mydomain.com',
'category': 'MY_CATEGORY'
},
function(response){
alert('received response');
}
);
});
and I get no alert message as expected. Instead, Firebug says I get "501 Not Implemented."
Why? What do I need to do to fix this?
If I go to the URL corresponding to the AJAX call in Firebug, I get a JSON file as a download, and it contains the expected data.
One thing I've noticed is that firebug says OPTIONS instead of GET:
alt text http://grab.by/grabs/b1a13d92a4fc69aa310880a5d7a06b95.png

I don't know if this is related, but generally when requesting JSON on the client to a server in a different domain you'll need to use JSONP instead of JSON due to the Same Origin Policy. Unfortunately, it doesn't appear that their API supports using JSONP -- so they must expect you to interact with their site from your server. In that case you'll need proxy methods on your server to translate the calls to their API so that the client calls are made to a server in the same domain as the page.

As this is the top Google match for "jQuery 501 (Method not implement)" I thought I'd share what worked for me when experiencing this on the same domain (which is not your problem).
My problem was that I was not returning valid JSON, I was just returning "1". So to fix this, either:
Ensure you return valid JSON, or if you don't require a JSON response,
Swap your call to use $.ajax instead of $.getJSON, or
If you're already using &.ajax, remove type: "json"
Hope that helps some people.

I had the same problem, and realized it was an encoding problem. It was solved by encoding the values of the data sent to the server. Try something like:
$(document).ready(function() {
$.getJSON('https://sendgrid.com/api/user.stats.json',
{
'api_user': encodeURIComponent('me#mydomain.com'),
'api_key': encodeURIComponent('MYAPIKEY'),
'user': encodeURIComponent('me#mydomain.com'),
'category': encodeURIComponent('MY_CATEGORY')
},
function(response){
alert('received response');
}
);
});
end then decode the data on backend. Hope it helps someone.

Related

Cannot POST strings containing fragmented HTML tags

I'm making an ajax call to POST a string to a shared hosting server I rent from Namecheap.com. I cannot seem to POST a stirng that contains some fragmented HTML tags such as <b><b, <tag><tag<tag. When I do this, I get a 403 Forbidden error. I tried the same thing using the escape function from Underscore.js, but the result was the same.
Here is the code I am using.
JavaScript
$.ajax({
type: 'POST',
url: '/test.php',
data : {
pass : '<b><b' // pass : _.escape('<b><b') gives the same result
}
})
.done(function (res) {
console.debug(res);
})
.fail(function (err,textStatus,errorThrown) {
console.debug('failed');
});
PHP
<?php
$password = $_POST['pass'];
echo $password;
?>
I tested this on XAMPP Linux on my local machine and this did not happen. Why is this happening?
You are almost certainly running into some sort of ill-conceived "security" feature of your web host. Contact their support staff.
For anybody who has the same issue, I fixed (See EDIT) this by double escaping the text as in _.escape(_.escape('<b><b')). This will output &lt;b&gt;&lt;b.
Sam Deufel also suggested me to use base64 encoding. I think this will work, too.
EDIT: I found that JavaScript statements such as alert() or document.write() are also not allowed to be POSTed via ajax on Namecheap hosting servers. So double escaping it does not always work. Using base64 or similar methods is probably better.

ajax call to cross domain using jsonp

Hello I am struggling to get this work.
var url = 'http://xxxx/getCustomerCardInfo?requestor_email=honey#gmail.com&callback=?';
$.getJSON(url, function(data){
alert(data);
});
The ajax call is successful. But this url gives the JSON in response i.e
{"targetRequestUri":"/getCustomerCardInfo","javax.servlet.request.key_size":256,"outputMap":{"emailId":"honey#gmail.com","orderList":[{"orderId":"ST210340","orderDate":"2013-04-24 07:12:54.187","orderStatus":"ORDER_COMPLETED","totalMoney":1}],"partyId":"10810","customerName":"honey goyal","telephoneNumber ":"9023605155"},"_FORWARDED_FROM_SERVLET_":true,"javax.servlet.request.cipher_suite":"DHE-RSA-CAMELLIA256-SHA","thisRequestUri":"json"}
But my Firefox error console gives the error in JSON:-
SyntaxError: invalid label
on second character of beginning of JSON, i mean on " in
{"targetRequestUr
And I does not get any alert. Any idea what i was doing wrong.
I think this need only JSONP response and padding is missing in above JSON.
Got the solution. I need to append padding before the JSON from web Server.
But this is not perfect solution according to me because it force me to change third party code. Still waiting for the perfect one so it can work by only changes to client side scripting. like
functionName({"firstName": "John","lastName": "Smith","age": 25});

Mootools: How to get redirected if ajax request returns redirect code?

I need to redirect user if request returns 302 or 303. It seems that there isn't a standard way to do this (odd, I thought it's quite a common task).
I have this code:
var request = new Request({
url: "/some-url/",
method: 'get',
evalScripts: true,
onComplete: function(){
console.log(this.status);
}
});
Console prints 0 status but web inspector shows that the status code is 302 Found, so I can't manually check the code and get redirected. Anyone know what I'm doing wrong?
Thanks.
normally, an ajax request to a 301/302/303 etc will follow the new location and re-issue the request as per specification. if you are not seeing a second request, something is wrong, like an infinite loop or similar...
more here: http://dev.w3.org/2006/webapi/XMLHttpRequest/#infrastructure-for-the-send-method
I've tryed both cases (302 and 303) and it follows the spec: user agent automatically redirects to url, specified in the Location: header of response. So, finally console.log(this.status) indeed return 200, but no worry because redirect is handled by browser automatically (at least in FF and Chrome).
That is the firebug console:

jQuery AJAX JSON dataType Conversion

Hopefully that title isn't too cryptic. What's happening is I have a jQuery AJAX script that I'm trying to use to access an API on a remote server, which returns a JSON response. However, the API returns the JSON as MIME type "text/html" (in the response header) instead of "application/json". It would seem obvious that I simply need to change the returned content type from text to JSON, to make the AJAX call interpret the data correctly.
Unfortunately, this is not the case. I have tried this in a multitude of different ways, all of which fail. The closest I've gotten to getting this API call to work is when the debugger tells me "Resource interpreted as Script but transferred with MIME type text/html". And the AJAX call errors out with my debug message that dumps the jqXHR object in JSON format, which tells me: {"readyState":4,"status":200,"statusText":"parsererror"}
Here is an example of my code (although I have changed the code many various ways, in my attempts at getting it to work, but this version seems to be the closest to correct):
$.ajax({
type: 'GET',
url: 'http://username:api-key#www.kanbanpad.com/api/v1/projects.json',
contentType: 'application/json',
dataType: 'jsonp',
converters: {
'jsonp': jQuery.parseJSON,
},
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log(textStatus+': '+errorThrown);
}
});
If anyone can figure out what I need to do differently to make this work, I will be extremely grateful.
It may also be worth noting that if you copy/paste the API URL into a browser address bar and hit go, it gives the proper JSON response with the proper response header ("application/json")
So unless Kanbanpad updates their API, it cannot be directly accessed with JS. You will have to use PHP (or some other) to handle the requests.
It works just as well, it just requires an extra step is all.
Just for anyone that was looking for a solution.
dataFilter(data, type)Function
A function to be used to handle the raw response data of XMLHttpRequest.
This is a pre-filtering
function to sanitize the response. You should return the sanitized data. The function
accepts two arguments: The raw data returned from the server and the 'dataType' parameter.
I would change the content type in the dataFilter interceptor to json. Bear in mind this affects all ajax calls, so use info from data to decide which ones you want to convert.
Verify that your server is sending a jsonp response. This means the json should be enclosed with a string of your callback.
The callback name is passed in the parameters, and if you're not setting it explicitly, looks something like: jQuery15102810791094068532_1300988427891 (As per http://www.json-p.org/)
On your server, you need to format the response:
jQuery15102810791094068532_1300988427891({...json response ...});
Where you use the callback defined in your GET parameter 'callback'.
You might try setting the type to "json" and see if it works. I've had a number of parsererror's with the jquery's jsonp - you might try http://code.google.com/p/jquery-jsonp until it's a bit smoother.
Try changing your content-type to this
contentType: "application/json; charset=utf-8",

JQuery ajax calls not working in Firefox browser

I am trying to test Jquery ajax calls in Firefox but it it not working. I mean my server is not receiving any requests. But when I test in IE8 it works fine. Here is my ajax call:
$("#getWeatherReport").click(function(){
$cityName = "New York";
$.ajax({
type: "POST",
dataType:"xml",
url: "http://localhost:8080/Test/WeatherServlet",
data: "cityName="+$cityName,
success: function(data) {
alert($("report", data).text());
},
error: function(xhr, textStatus, errorThrown) {
alert('ERROR['+xhr.statusText+']');
}
});
});
It is not even calling error function. And from my server code(java) I am setting content type as "text/xml".
Any suggestions?
Your string is not correctly serialized, I'm not sure if that's the issue, but it may be and it's definitely a potential one for later, try this for an immediate test:
var $cityName = "New+York";
As a more permanent solution, pass data as an object, like this:
data: {cityName: $cityName},
Have you installed Firebug?
Your best bet would be to install Firebug, which comes with a console that'll notify you of any javascript errors. You can also use it (via the "Net" tab) to monitor all requests made by your page.
From what I can see, your code looks OK (other than the possible issue pointed out by #Nick Craver)
Also, why the '$' on your cityName variable? The '$' prefix in Javascript is meant to be reserved for machine-generated code (so that it has no chance of conflicting with user code).
try installing firebug plugin in ff :: https://addons.mozilla.org/en-US/firefox/addon/1843/
Then check the :::: Net Tab >> All selected
Refresh the page and see is your ajax call actually getting called. If yes is there any syntax error in the call or any variable null error. If all is fine then you can think of further issues
Usually, when I end up with a parseerror that means that the return header type is wrong or that somehow the server sent extra data with the response. For instance, if I'm looking to get JSON back and I get the JSON and some HTML from x-debug.
Also, The OPTIONS request is for cross-domain requests which is what #Nick was alluding to.
A helpful link to get you started.

Resources