Verify the existence of a twitter account using AJAX/JSON - javascript

I am trying to build a simple check that will accept a string and check to see if a twitter account exists by that string.
I have successfully managed to get a positive result, but I can't seem to get a negative one. $.ajax() has an error element, but it is not firing.
Working Example
Code:
var testTwit = function(username){
$.ajax({
url: 'http://twitter.com/statuses/user_timeline.json?screen_name='+username+'&count=1&callback=?',
dataType: 'json',
success: function(){
alert("username is valid");
},
error: function(){
alert("username is valid");
}
})
}
​

You are using the JSONP transport. In this transport, the requested URL is simply added as a <script> tag in the document. If the URL returns a non-200 status code, the browser won't execute it: that's why you can't see negative responses.
One solution is to use the suppress_response_codes parameter, so that the API always return a 200 status code.
See Things Every Twitter Developer Should Know:
suppress_response_codes: If this parameter is present, all responses will be returned with a 200 OK status code - even errors. This parameter exists to accommodate Flash and JavaScript applications running in browsers that intercept all non-200 responses. If used, it’s then the job of the client to determine error states by parsing the response body. Use with caution, as those error messages may change.
BTW, Twitter is suppressing non-authenticated access to the API, so JSONP access may be suppressed too.

Just a summarize of arnaud576875's answer:
Add a suppress_response_codes=1 parameter
Check for ID returned
So, the result will be something like this:
var testTwit = function(username){
$.ajax({
url: 'http://twitter.com/statuses/user_timeline.json?suppress_response_codes=1&screen_name='+username+'&count=1&callback=?',
dataType: 'json',
success: function(d){
if (d && d.id)
$('span').html('username is valid!');
else
$('span').html('username is not valid.');
}
});
}

Usually API's always returns a response when a request is received. That's why no error is given. You should parse the response coming from the API to find out if a user exists or not.

Errors are not triggered when using JSONP-requests. Read more at jQuery Forums.

Related

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.

Calling a web service in JQuery and assign returned Json to JS variable

This is my first time attempting working with JQuery, Json AND calling a web service.. So please bear with me here.
I need to call a webserivce using JQuery, that then returns a Json object that I then want to save to a javascript variable. I've attempted writing a little something. I just need someone to confirm that this is indeed how you do it. Before I instantiate it and potentially mess up something on my company's servers. Anyways, here it is:
var returnedJson = $.ajax({
type: 'Get',
url: 'http://172.16.2.45:8080/Auth/login?n=dean&p=hello'
});
So there it is, calling a webservice with JQuery and assigning the returned jsonObject to a javascript variable. Can anyone confirm this is correct?
Thanks in advance!
var returnedJson = $.ajax({
type: 'Get',
url: 'http://172.16.2.45:8080/Auth/login?n=dean&p=hello'
});
If you do it like this returnedJson would be an XHR object, and not the json that youre after. You want to handle it in the success callback. Something like this:
$.ajax({
// GET is the default type, no need to specify it
url: 'http://172.16.2.45:8080/Auth/login',
data: { n: 'dean', p: 'hello' },
success: function(data) {
//data is the object that youre after, handle it here
}
});
The jQuery ajax function does not return the data, it returns a jQuery jqHXR object.
You need to use the success callback to handle the data, and also deal with the same origin policy as Darin mentions.
Can anyone confirm this is correct?
It will depend on which domain you stored this script. Due to the same origin policy restriction that's built into browsers you cannot send cross domain AJAX requests. This means that if the page serving this script is not hosted on http://172.16.2.45:8080 this query won't work. The best way to ensure that you are not violating this policy is to use relative urls:
$.ajax({
type: 'Get',
url: '/Auth/login?n=dean&p=hello'
});
There are several workarounds to the same origin policy restriction but might require you modifying the service that you are trying to consume. Here's a nice guide which covers some of the possible workarounds if you need to perform cross domain AJAX calls.
Also there's another issue with your code. You have assigned the result of the $.ajax call to some returnedJson variable. But that's not how AJAX works. AJAX is asynchronous. This means that the $.ajax function will return immediately while the request continues to be executed in the background. Once the server has finished processing the request and returned a response the results will be available in the success callback that you need to subscribe to and which will be automatically invoked:
$.ajax({
type: 'Get',
url: '/Auth/login?n=dean&p=hello',
success: function(returnedJson) {
// use returnedJson here
}
});
And yet another remark about your code: it seems that you are calling a web service that performs authentication and sending a username and password. To avoid transmitting this information in clear text over the wire it is highly recommended to use SSL.

URL in AJAX call

I am persisting the data in a textbox before redirecting the page to another. When the user clicks the back button in the page load function of the page (in javascript) I am getting the data from the textbox like
var pageval = $('#grid')
.load('/Dealer/AllClaims?page=5&__=634673230919806673 #grid', CallBackFunction);
I want to send an AJAX call by using the URL from the above data. I.e from /Dealer/AllClaims?page=5&__=634673230919806673 #grid. So I replaced the 'pageval' unnecessary data with (.replace()) in javascript. Now I store it as
var urlmain = '/Dealer/AllClaims?page=5&__=634673230919806673 #grid';
When I send an AJAX call with this 'urlmain' like
$.ajax({
type: "GET",
url: urlmain,
success: function (data) {
$("#allclaimsdiv").html(data);
},
it throws error like 'status not found' as the URL is like
http://localhost:46408/Dealer/%22Dealer/GetDealerClaims?page=3&__=634673387913756213
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
The above bold data is there in the URL before users click on the back button. I think it is concatenating the data.
But for testing purpose I had given directly the URL as:
$.ajax({
type: "GET",
url: "/Dealer/AllClaims?page=5&__=634673230919806673 #grid",
success: function (data) {
$("#allclaimsdiv").html(data);
},
Then it works fine.
What is the difference between these two? Why doesn't it work?
you have a problem in the called url:
first: there is a /22 which stands for a url-encoded doublequote
second: you have Dealer two times in the url - so you may have to remove /Dealer from your urlmain
Is there a quote character getting encoded somewhere along the line? The reason I'm wondering is the URL you've given in bold has "%22" in it:
http://localhost:46408/Dealer/%22Dealer/
See here for some info on what certain characters get encoded to.
A 500 error means a problem has occurred on your web server. Check your server log files or enable error reporting for more info - that might give you some hints or even tell you exactly what's wrong.

AD FS 2.0 Authentication and AJAX

I have a web site that is trying to call an MVC controller action on another web site. These sites are both setup as relying party trusts in AD FS 2.0. Everything authenticates and works fine when opening pages in the browser window between the two sites. However, when trying to call a controller action from JavaScript using the jQuery AJAX method it always fails. Here is a code snippet of what I'm trying to do...
$.ajax({
url: "relyingPartySite/Controller/Action",
data: { foobar },
dataType: "json",
type: "POST",
async: false,
cache: false,
success: function (data) {
// do something here
},
error: function (data, status) {
alert(status);
}
});
The issue is that AD FS uses JavaScript to post a hidden html form to the relying party.
When tracing with Fiddler I can see it get to the AD FS site and return this html form which should post and redirect to the controller action authenticated. The problem is this form is coming back as the result of the ajax request and obviously going to fail with a parser error since the ajax request expects json from the controller action. It seems like this would be a common scenario, so what is the proper way to communicate with AD FS from AJAX and handle this redirection?
You have two options.
More info here.
The first is to share a session cookie between an entry application (one that is HTML based) and your API solutions. You configure both applications to use the same WIF cookie. This only works if both applications are on the same root domain.
See the above post or this stackoverflow question.
The other option is to disable the passiveRedirect for AJAX requests (as Gutek's answer). This will return a http status code of 401 which you can handle in Javascript.
When you detect the 401, you load a dummy page (or a "Authenticating" dialog which could double as a login dialog if credentials need to be given again) in an iFrame. When the iFrame has completed you then attempt the call again. This time the session cookie will be present on the call and it should succeed.
//Requires Jquery 1.9+
var webAPIHtmlPage = "http://webapi.somedomain/preauth.html"
function authenticate() {
return $.Deferred(function (d) {
//Potentially could make this into a little popup layer
//that shows we are authenticating, and allows for re-authentication if needed
var iFrame = $("<iframe></iframe>");
iFrame.hide();
iFrame.appendTo("body");
iFrame.attr('src', webAPIHtmlPage);
iFrame.load(function () {
iFrame.remove();
d.resolve();
});
});
};
function makeCall() {
return $.getJSON(uri)
.then(function(data) {
return $.Deferred(function(d) { d.resolve(data); });
},
function(error) {
if (error.status == 401) {
//Authenticating,
//TODO:should add a check to prevnet infinite loop
return authenticate().then(function() {
//Making the call again
return makeCall();
});
} else {
return $.Deferred(function(d) {
d.reject(error);
});
}
});
}
If you do not want to receive HTML with the link you can handle AuthorizationFailed on WSFederationAuthenticationModule and set RedirectToIdentityProvider to false on Ajax calls only.
for example:
FederatedAuthentication.WSFederationAuthenticationModule.AuthorizationFailed += (sender, e) =>
{
if (Context.Request.RequestContext.HttpContext.Request.IsAjaxRequest())
{
e.RedirectToIdentityProvider = false;
}
};
This with Authorize attribute will return you status code 401 and if you want to have something different, then you can implement own Authorize attribute and write special code on Ajax Request.
In the project which I currently work with, we had the same issue with SAML token expiration on the clientside and causing issues with ajax calls. In our particular case we needed all requests to be enqueud after the first 401 is encountered and after successful authentication all of them could be resent. The authentication uses the iframe solution suggested by Adam Mills, but also goes a little further in case user credentials need to be entered, which is done by displaying a dialog informing the user to login on an external view (since ADFS does not allow displaying login page in an iframe atleast not default configuration) during which waiting request are waiting to be finished but the user needs to login on from an external page. The waiting requests can also be rejected if user chooses to Cancel and in those cases jquery error will be called for each request.
Here's a link to a gist with the example code:
https://gist.github.com/kavhad/bb0d8e4a446496a6c05a
Note my code is based on usage of jquery for handling all ajax request. If your ajax request are being handled by vanilla javascript, other libraries or frameworks then you can perhaps find some inspiration in this example. The usage of jquery ui is only because of the dialog and stands for a small portion of the code which could easly be swapped out.
Update
Sorry I changed my github account name and that's why link did not work. It should work now.
First of all you say you are trying to make an ajax call to another website, does your call conforms to same origin policy of web browsers? If it does then you are expecting html as a response from your server, changedatatype of the ajax call to dataType: "html", then insert the form into your DOM.
Perhaps the 2 first posts of this serie will help you. They consider ADFS and AJAX requests
What I think I would try to do is to see why the authentication cookies are not transmitted through ajax, and find a mean to send them with my request. Or wrap the ajax call in a function that pre authenticate by retrieving the html form, appending it hidden to the DOM, submitting it (it will hopefully set the good cookies) then send the appropriate request you wanted to send originally
You can do only this type of datatype
"xml": Treat the response as an XML document that can be processed via jQuery.
"html": Treat the response as HTML (plain text); included script tags are evaluated.
"script": Evaluates the response as JavaScript and evaluates it.
"json": Evaluates the response as JSON and sends a JavaScript Object to the success callback.
If you can see in your fiddler that is returning only html then change your data type to html or if that only a script code then you can use script.
You should create a file anyname like json.php and then put the connection to the relayparty website this should works
$.ajax({
url: "json.php",
data: { foobar },
dataType: "json",
type: "POST",
async: false,
cache: false,
success: function (data) {
// do something here
},
error: function (data, status) {
alert(status);
}
});

JQuery Ajax Post results in 500 Internal Server Error

I am trying to perform this AJAX post but for some reason I am getting a server 500 error. I can see it hit break points in the controller. So the problem seems to be on the callback. Anyone?
$.ajax({
type: "POST",
url: "InlineNotes/Note.ashx?id=" + noteid,
data: "{}",
dataType: "json",
success: function(data) {
alert(data[1]);
},
error: function(data){
alert("fail");
}
});
This is the string that should be returned:
{status:'200', text: 'Something'}
I suspect that the server method is throwing an exception after it passes your breakpoint. Use Firefox/Firebug or the IE8 developer tools to look at the actual response you are getting from the server. If there has been an exception you'll get the YSOD html, which should help you figure out where to look.
One more thing -- your data property should be {} not "{}", the former is an empty object while the latter is a string that is invalid as a query parameter. Better yet, just leave it out if you aren't passing any data.
in case if someone using the codeigniter framework, the problem may be caused by the csrf protection config enabled.
This is Ajax Request Simple Code To Fetch Data Through Ajax Request
$.ajax({
type: "POST",
url: "InlineNotes/Note.ashx",
data: '{"id":"' + noteid+'"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data.d);
},
error: function(data){
alert("fail");
}
});
I just had this problem myself, even though i couldn't find the reason for it in my case, when changing from POST to GET, the problem 500 error disappeared!
type:'POST'
I experienced a similar compound error, which required two solutions. In my case the technology stack was MVC/ ASP.NET / IIS/ JQuery. The server side was failing with a 500 error, and this was occurring before the request was handled by the controller making the debug on the server side difficult.
The following client side debug enabled me to determine the server error
In the $.ajax error call back, display the error detail to the console
error: (error) => {
console.log(JSON.stringify(error));
}
This at least, enabled me to view the initial server error
“The JSON request was too large to be serialized”
This was resolved in the client web.config
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="150000" />
However, the request still failed. But this time with a different error that I was now able to debug on the server side
“Request Entity too large”
This was resolved by adding the following to the service web.config
<configuration>
…
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferPoolSize="524288">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
</binding>
</basicHttpBinding>
</bindings>
The configuration values may require further tuning, but at least it resolved the server errors caused by the ajax post.
You can look up HTTP status codes here (or here), this error is telling you:
"The server encountered an unexpected condition which prevented it from fulfilling the request."
You need to debug your server.
I run into the same thing today. As suggested before get Firebug for Firefox, Enable Console and preview POST response. That helped me to find out how stupid the problem was. My action was expecting value of a type int and I was posting string. (ASP.NET MVC2)
There should be an event logged in the EventVwr (Warning from asp.net), which could provide you more details on where the error could be.
A 500 from ASP.NET probably means an unhandled exception was thrown at some point when serving the request.
I suggest you attach a debugger to the web server process (assuming you have access).
One strange thing: You make a POST request to the server, but you do not pass any data (everything is in the query string). Perhaps it should be a GET request instead?
You should also double check that the URL is correct.
I just face this problem today. with this kind of error, you won't get any responses from server, therefore, it's very hard to locate the problem.
But I can tell you "500 internal server error" is error with server not client, you got an error in server side script. Comment out the code closure by closure and try to run it again, you'll soon find out you miss a character somewhere.
You can also get that error in VB if the function you're calling starts with Public Shared Function rather than Public Function in the webservice. (As might happen if you move or copy the function out of a class). Just another thing to watch for.
Can you post the signature of your method that is supposed to accept this post?
Additionally I get the same error message, possibly for a different reason. My YSOD talked about the dictionary not containing a value for the non-nullable value.
The way I got the YSOD information was to put a breakpoint in the $.ajax function that handled an error return as follows:
<script type="text/javascript" language="javascript">
function SubmitAjax(url, message, successFunc, errorFunc) {
$.ajax({
type:'POST',
url:url,
data:message,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success:successFunc,
error:errorFunc
});
};
Then my errorFunc javascript is like this:
function(request, textStatus, errorThrown) {
$("#install").text("Error doing auto-installer search, proceed with ticket submission\n"
+request.statusText); }
Using IE I went to view menu -> script debugger -> break at next statement.
Then went to trigger the code that would launch my post. This usually took me somewhere deep inside jQuery's library instead of where I wanted, because the select drop down opening triggered jQuery. So I hit StepOver, then the actual next line also would break, which was where I wanted to be. Then VS goes into client side(dynamic) mode for that page, and I put in a break on the $("#install") line so I could see (using mouse over debugging) what was in request, textStatus, errorThrown. request. In request.ResponseText there was an html message where I saw:
<title>The parameters dictionary contains a null entry for parameter 'appId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ContentResult CheckForInstaller(Int32)' in 'HLIT_TicketingMVC.Controllers.TicketController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.<br>Parameter name: parameters</title>
so check all that, and post your controller method signature in case that's part of the issue
I found myself having this error to. I had .htaccess redirect configured in a directory. Well it reroutes ajax calls to ofcourse ($.post(../ajax.php)), so it couldn't find the actual file (resulting in 500 error).
I 'fixed' it by placing the ajax.php in a directory (So .htaccess didn't affect).
I was able to find the solution using the Chrome debugger (I don't have Firebug or other third-party tools installed)
Go to developer tab (CTRL+MAJ+I)
Network > click on the request which failed, in red > Preview
It showed me that I had a problem on the server, when I was returning a value which was self-referencing.
In my case it was simple issue, but hard to find. Page directive had wrong Inherits attributes. It just need to include the top level and it worked.
Wrong code
<%# Page Language="C#" CodeBehind="BusLogic.aspx.cs" Inherits="BusLogic"%>
Correct code
<%# Page Language="C#" CodeBehind="BusLogic.aspx.cs" Inherits="Web.BusLogic" %>
When using the CodeIgniter framework with CSRF protection enabled, load the following script in every page where an ajax POST may happen:
$(function(){
$.ajaxSetup({
data: {
<?php echo $this->config->item('csrf_token_name'); ?>: $.cookie('<?php echo $this->config->item('csrf_cookie_name'); ?>')
}
});
});
Requires: jQuery and jQuery.cookie plugin
Sources: https://stackoverflow.com/a/7154317/2539869 and http://jerel.co/blog/2012/03/a-simple-solution-to-codeigniter-csrf-protection-and-ajax
The JSON data you are passing to the server should have same name as you forming in client side.
Ex:
var obj = { Id: $('#CompanyId').val(),
Name: $("#CompanyName").val()
};
$.Ajax(data: obj,
url: "home/InsertCompany".....
If the name is different, ex:
[HttpPost]
public ActionResult InsertCompany(Int32 Id, string WrongName)
{
}
You will get this error.
If you are not passing the data, remove the data attribute from AJAX request.
I had this issue, and found out that the server side C# method should be static.
Client Side:
$.ajax({
type: "POST",
url: "Default.aspx/ListItem_Selected",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: ListItemElectionSuccess,
error: ListItemElectionError
});
function ListItemElectionSuccess(data) {
alert([data.d]);
}
function ListItemElectionError(data) {
}
Server Side:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static String ListItem_Selected()
{
return "server responce";
}
}
As mentioned I think your return string data is very long. so the JSON format has been corrupted.
There's other way for this problem. You should change the max size for JSON data in this way :
Open the Web.Config file and paste these lines into the configuration section
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
Use a Try Catch block on your server side and in the catch block pass back the exception error to the client. This should give you a helpful error message.
I also faced the same problem. Here are two ways by which I have solved it-
1. If you're using some framework, make sure you are sending a CSRF token with the ajax call as well
Here is how the syntax will look like for laravel -
<meta name="_token" content="{{ csrf_token() }}">
In your js file make sure to call this before sending the ajax call
$.ajaxSetup({
headers: {
'X_CSRF-TOKEN' : $('meta[name="_token"]').attr('content')
}
});
Another way to solve it would be to change method from post to get
For me, the error was in php file to which i was sending request.
Error was in database connectivity. After fixing the php code, error resolved.
Your code contains dataType: json.
In this case jQuery evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner. Any malformed JSON is rejected and a parse error is thrown. An empty response is also rejected.
The server should return a response of null or {} instead.
I found this occurred in chrome when I did two ajax queries in the jquery 'on load' handler,
i.e. like $(function() { $.ajax() ... $.ajax() ... });
I avoided it using:
setTimeout(function_to_do_2nd_ajax_request, 1);
it's presumably a chrome and/or jquery bug
I had this problem because the page I called ajax post from had EnableViewState="false" and EnableViewStateMac="false" but not the page called.
When I put this on both pages everything started to work. I suspected this when I saw MAC address exception.
Your return string data can be very long.
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime maxRequestLength="2147483647" />
</system.web>
For example:
1 Char = 1 Byte
5 Char = 5 Byte
"Hakki" = 5 Byte
I have had similar issues with AJAX code that sporadically returns the "500 internal server error". I resolved the problem by increasing the "fastCGI" RequestTimeout and ActivityTimeout values.
I'm late on this, but I was having this issue and what I've learned was that it was an error on my PHP code (in my case the syntax of a select to the db). Usually this error 500 is something to do using syntax - in my experience. In other word: "peopleware" issue! :D
As an addition to the "malformed JSON" answer, if the query you are running returns an object or anything that prevents the data to be serialised, you will get this error. You should always be sure you have JSON and only JSON at the end of your action method or whatever it is you are getting the data from.
Usually your property is not completely right or something wrong with your server processing.

Categories

Resources