i was reading an article on Query Ajax and REST HTTP Basic and here i got this http://blog.rassemblr.com/2011/05/jquery-ajax-and-rest-http-basic-authentication-done-deal/
just see the code
$.ajax( {
url : '/model/user.json',
dataType : 'json',
beforeSend : function(xhr) {
var bytes = Crypto.charenc.Binary.stringToBytes(username + ":" + password);
var base64 = Crypto.util.bytesToBase64(bytes);
xhr.setRequestHeader("Authorization", "Basic " + base64);
},
error : function(xhr, ajaxOptions, thrownError) {
reset();
onError('Invalid username or password. Please try again.');
$('#loginform #user_login').focus();
},
success : function(model) {
cookies();
...
}
});
i just do not understand what kind of file type is user.json. please anyone who is familiar with .json file type then please tell me what kind of file type it is. thanks
Its not a file in this case. It is RESTful URL, .json part just asks server to return results in JSON format. Probably you can use /model/user.xml to get response in XML format. Twitter and many other services does this the same way.
Another common way to request specific response format is by providing HTTP Accept header.
For further reading I recommend this resource: http://blog.2partsmagic.com/restful-uri-design
Some applications return different data if the user adds a different
extension. e.g. they may ask for contacts.xml or contacts.json. But
different URIs imply different resources. Are the two data formats
really two different resources? Or just two different representations
of the same resource.
Related
I am trying to use the Rally web service API to reorder 2 items.
From looking at the documentation i should be able to do:
$.ajax({
url: https://rally1.rallydev.com/slm/webservice/v2.0/task/12345?rankAbove=/slm/webservice/v2.0/task/56789,
type: 'PUT',
headers: { Authorization: Basic mytoken },
success: function(data) {
//do something
}
});
but i'm getting an error:
Cannot parse input stream due to I/O error as JSON document: Parse error: expected '{' but saw '' [ chars read = \u003E\u003E\u003E\u003C\u003C\u003C ]"
The documentation doesn't seem to reveal what I could be doing wrong.
Cheers for your help
You won't be able to use basic auth to do this because there is an additional CSRF token you need to pass. I think you can make it work with an api key though:
headers: { zsessionid: myToken }
You didn't have any issues with reading data because the CSRF protection only kicks in when attempting to modify data.
For what it's worth, the App SDK generally handles most of this complexity for you. It looks like you're using jquery in your app here instead, which is why you need to do this low level stuff...
I have double, triple, and quadruple checked that I have the right master key that I'm passing. My parameters are taking directly from the UA website also so it can't be that. Anyone see what I'm doing wrong here???
Parse.Cloud.define("sendPush", function(request, response) {
var Buffer = require('buffer').Buffer;
var parameters = {
"audience" : "all",
"device_types" : "all",
"notification" : {
"alert" : "Hello from Urban Airship."
}
};
var params = JSON.stringify(parameters);
Parse.Cloud.httpRequest({
url: "https://go.urbanairship.com/api/push/",
method: 'POST',
headers: {
"Content-Type" : "application/json",
"Authorization" : 'Basic ' + new Buffer('MASTER_KEY').toString('base64'),
"Accept" : "application/vnd.urbanairship+json; version=3;"
},
body: params,
success: function(httpResponse) {
response.error(httpResponse);
},
error: function(httpResponse) {
response.error('Request failed with response code ' + httpResponse.status);
}
});
});
I've also tried adding in APP_SECRET:
"Authorization" : 'Basic ' + new Buffer('APP_SECRET':'MASTER_KEY').toString('base64'),
It's not clear from your code sample if you are including the app key in your request. API requests to Urban Airship use HTTP basic authentication. The username portion is the application key and the password portion in this case is the master secret. The application secret is restricted to lower-security APIs and is for use in the distributed application. The master secret is needed for sending messages and other server API requests.
Urban Airship provides a guide for troubleshooting common API issues.
I had the same problem and tried to figure it out by Network diagnosing tools for more than two days. Because after debugging I checked that I send the right credentials to UA. After all I called the UA and ask them to check the Credentials (in my case was appKey and appToken for streaming with java-connect API) if they are still valid. They checked and approved the validation but just in case sent me a new credentials. And I could connect with the new credentials!
It is for sure a bug by UA because I tested the whole time by another test application, which was a Desktop java application and I could connect to the server (with the same appKey and appToken) and get the events, but I got 401 error in my main Application, which was a Web Application running on TomCat 8.0 . It means It worked in a same time in with the same credential for one application and did not work for another application.
Trying to read cross domain csv file :
remote_url = “http://www.example.com/buglist.cgi?bug_status=NEW&columnlist=bug_id%2Cshort_desc&query_format=advanced&ctype=csv";
$.ajax({
url:remote_url,
type:"get",
cache: false,
dataType: "jsonp",
success:function(data){
console.log(data);
},
error: function(data){
console.log(data);
}
});
Although getting 200 status from server, It always going into error callback handler and logging a JavaScript syntax error:
SyntaxError: missing ; before statement 6230,"this is a ""short description"", blah blah blah..
My CSV file has two columns “bug_id” and “short_desc” with following values:
bug_id = 6230
short_desc = this is a "short description", blah blah blah..
I know the error is because of double quote in description, but I don’t know the solution. I tried “YQL” to convert CSV to JSON but it returned null as a result, may be because of an error.
The JSONP technique expects the response to be JavaScript. This is why you're getting a JavaScript error; it's trying to execute the CSV content as JavaScript.
JSONP works by defining a callback function in the server, adding a script tag with a URL that tells the server what function it will call, then the server responds with JavaScript that calls that function with the data as a parameter.
The destination URL must support this protocol in other words. You can't just use JSONP for any arbitrary request.
You may need to use a different technique to get your data, like a same-domain proxy that does the HTTP request to the server. If you are able to change the code at example.com, you have even more options.
Here is a very simple example of a call to Twitter's search API to get all tweets from a tag known to have tweets, #fml.
I believe I am correctly using the application-only authentication as explained here: https://dev.twitter.com/docs/auth/application-only-auth (see Step 3 for example of a call)
I am being asked for a solution that does not involve any server-side code so I am including the bearer code in the javascript, which isn't good to begin with, but....
I would expect this code to work. Instead it produces the error '400 (Bad Request)'. Any ideas?
$.ajax({
url: "https://api.twitter.com/1.1/search/tweets.json",
dataType: "jsonp",
data: "q=%23fml",
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Bearer XXmyBearerCodeXX");
},
success: function(json){ alert(json); }
});
EDIT 1 - Validated Twitter call
Using hurl.eu I was able to get a successful response from the API with the above query and Authorization header, so I assume this means my Twitter call is correct, just not set up correctly within jQuery.ajax(), but I just don't see what is missing.
You cannot set request headers using AJAX calls with dataType JSONP.
See this question: Set Headers with jQuery.ajax and JSONP?
The best solution is to use a server-side proxy to do the search for you. I know you are looking for a client only solution, but with this restriction, and with no way around CORS, this is how it seems to be done today for the Twitter API.
Edit It may be possible using a proxy like Yahoo's YQL if you don't have access to one.
on your severside create a jsp or servlet and from the client side make a JSON call to the .jsp/servlet and that will return back the json object to the javascript. In serverside use the twitter4j api.
sample code:
`
$.getJSON(http://localhost:8080/test.jsp?callback=?",
{
jspqueryStr : queryStr,
jspgeocodeStr : geocodeStr,
lat:latStr,
lan:lngStr,
radius:radiusStr,
}, displayResult);
//This function returns the data as json object from server.
function displayResult(data) {}
In the jsp the code is like below
<%
String jspqueryStr = request.getParameter("jspqueryStr");
String jspgeocodeStr = request.getParameter("jspgeocodeStr");
String diseasename = request.getParameter("jspqueryStr");
String lat = request.getParameter("lat");
String lan = request.getParameter("lan");
String radius = request.getParameter("radius");
Gson gson = new Gson();
String json = gson.toJson(tweetList);
json = request.getParameter("callback") + "(" + json + ");";
out.println(json);
public List<Status> searchstream(){
//here all the twitter4j api code to get the data
retrun tweetList;
}
%>
`
Hello i've got a problem with ajax json request. Im always getting an error, even if the requests are succeeded. At the moment i have this code:
function sumbitLoginForm(user, pass) {
if (user.trim() == '' || pass.trim() == '') {
alert("You must enter username and password!");
} else {
$.ajax({
type : 'POST',
url : 'https://url.php',
dataType : 'json',
data : {
userlogin : user,
userpass : pass
},
contentType: "application/json;",
success : function(data) {
$("#images").html("uspeshno");
},
error : function(data) {
$("#images").html("greshka");
}
});
}
return false;
}
$(document).ready(function() {
clearPageInputs();
$("#submitButton").click(function() {
sumbitLoginForm($("#username").val(), $("#password").val());
});
});
Im always getting an error , no matter what username and password i type . But the status of request is changing , if i type correct user and pass i get status 302 Moved temporarly , but when i type wrong user or pass i get status 200 OK . What am i doing wrong ?
PRG Pattern and Ajax
It looks like your server returns a HTTP 200 status code when the userid and password will not validate. This is proper behavior, as HTTP error codes not meant for application errors, but for HTTP protocol errors.
When the userid and password are matched succesfully, you are redirected to another page. This is also normal behavior, e.g. to prevent other people to re-use your login credentials using the back key.
This is called the Post/Redirect/Get pattern.
See: http://en.wikipedia.org/wiki/Post/Redirect/Get
The problem is that the PRG pattern does not play nice with Ajax applications. The redirect should be handled by the browser. It is therefore transparent for the jQuery code. The Ajax html response will be the page that is mentioned in the Location header of the 302. Your Ajax application will not be able to see that it is being redirected. So your are stuck.
In one of my projects I solved this on the server side. If I detected an Ajax call, I would not send a redirect but a normal 200 response. This only works if you have access to the server code.
If you cannot change the redirect for your Ajax calls, then you can parse the response headers or the html to see if you were being redirected and act accordingly. Probably the login will set a cookie, so you might try and look for the presence of that cookie.