ClientLogin from Google API doesn't works with AJAX - javascript

I'm trying to login to a Google Account for request Picassa Web photos with AJAX. That's the code:
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","https://www.google.com/accounts/Login",true);
xmlhttp.send("accountType=HOSTED_OR_GOOGLE&Email=...&Passwd=...&service=lh2&source=prova");
document.getElementById('prova').innerHTML=xmlhttp.responseText;
With this firebug shows a 200 OK status in the Net tab but an unexplained error in the Console. Of course nothing appears in the div called "prova" since answer is empty.
I also try to add this header:
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
But then firebug shows a 400 Bad Request in the Net tab. Can you help me? Thank you.

You should be able to view the ajax reponse in firebug and see what is gtting posted back to you - you can get a 200 error but still get an error in the post back. Don't you need to do something with an AuthToken too?

Solved! Firefox and new browsers don't let make AJAX call to third-party applications for security reasons. All is explained here: http://www.xml.com/pub/a/2005/11/09/fixing-ajax-xmlhttprequest-considered-harmful.html

Wasn't sure if we got the authToken or not...
Here's how I've been making xDomain Posts:
It requires having a little library (tiny) called flyJSONP, which uses YQL (Yahoo! Query Language) as a JSONP hack. Works great, but cannot post/get headers. After, I send data to php which then makes a cross-domain post with necessary header.
FlyJSONP also works with get... FlyJSONP.get({...
FlyJSONP.post({
url: "https://www.google.com/accounts/ClientLogin",
parameters: {
name: "value"
},
success: function(data) {
console.log("the response is: " + data);
},
error: function(errorMsg) {
console.log(errorMsg);
},
complete: function(data){
console.log("...completed post!");
}
});

Related

JQuery AJAX request show AJAX and PHP errors

I am using a Jquery $.post request to get a JSON response that is generated by PHP. When the request is complete, a success or error message is displayed. During development however, I sometimes have PHP errors which end up being returned instead of the JSON. When this happens, I just get the error message:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
The code I have now looks like this:
var request = $.post(url, data, null, "json");
request.fail(on_failure);
var on_failure = function(jqXHR, text_status, error_thrown)
{
$("#text_status").empty().append(error_thrown);
};
I would like to be able to show the PHP error if one is returned rather than just indicate that there is a PHP error (just to speed up debugging). Obviously, if a non-JSON parsing error such as HTTP 404 occurs, I still want to display that. I found a method here that indicates that I can detect this error with something like this
$.ajaxSetup({
error: function(jqXHR, exception) {
if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
}
}
});
But it doesn't seem like that helps me because it runs for every request rather than individual requests and (as far as I know) it does not allow access to the error message in the returned data.
No sure what version of jquery are you using. Anyway, did you try to remove the json dataType?
var request = $.post(url, data, null);
Doing this jQuery will guess the dataType for you.
I hate to steal mkross1983's credit, but he has not responded to my request to turn his comment into an answer. mkross1983 said:
Have you tried using Firebug under the "Net" tab to see the results of the requests? Sometimes errors can be seen there that can give some clues to the problem
The Firebug "Net" tab has proved to be a valuable debugging tool. This way I can see exactly what request was made and the response sent to it. It even allows me to see the headers and cookies that were sent with the request.
Thank you mkross1983

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");

How I get respone text in application and bind to the label in cross ajax call

I am calling the web service from other domain using Ajax call and I want to get returned response from server in my application by using following code I get response text in firebug but not in my JavaScript code. Control are not showing success and error response it goes out directly.
I want response in my success or error section but both not handling in this.
I am trying lot but not finding any solution please any one help me.
I am in a trouble. I hope somebody can help me for calling cross domain web service by using Ajax call. I am trying from 1 week but didn't find any solution till. I am getting response on browser but not getting it on my actual code.
My JavaScript code.
crossdomain.async_load_javascript(jquery_path, function () {
$(function () {
crossdomain.ajax({
type: "GET",
url: "http://192.168.15.188/Service/Service.svc/GetMachineInfo?serialNumber="+123,
success: function (txt) {
$('#responseget').html(txt);
alert("hii get");
}
});
crossdomain.ajax({
type: "POST",
url: "http://192.168.15.188/Server/Service.svc/GetEvents/",
// data: "origin=" + escape(origin),
success: function (txt) {
$('#responsepost').html(txt);
alert("hii post");
}
});
});
});
</script>
You can't simply ignore the Same Origin Policy.
There are only three solutions to fetch an answer from a web-service coming from another domain :
do it server-side (on your server)
let the browser think it comes from the same domain by using a proxy on your server
change the web service server, by making it JSONP or (much cleaner today) by adding CORS headers

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.

jQuery Get Request on HTTP URL

i've recently tried to get some Response from an URL using jQuery. Therefore I copied a get request sample of jQuery API Get Request Tutorial into my project and tried to run it, but my debugging messages showed me, that it can't go further. I tried the javascript Ajax Library using a simple request, but it didn't work.
So i'm asking you, if you could help me somehow.
And this is all what i do, but there is no response.
var url = "http://www.google.com";
$.get(url, function(data){
alert("Data Loaded: " + data);
});
Did i probably forgot to include a ajax or jQuery library. For a better understanding, i have c and obj-c experince, this is why i think, that a library is missing.
In each sample there is just a short url like "test.php". Is my complete HTTP url wrong?
Thanks for your answers in advanced.
Br
Nic
I have provided an example scenario to help get you started:
<!-- Include this jQuery library in your HTML somewhere: -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script
This is probably best to include inside of an external JS file:
//Listen when a button, with a class of "myButton", is clicked
//You can use any jQuery/JavaScript event that you'd like to trigger the call
$('.myButton').click(function() {
//Send the AJAX call to the server
$.ajax({
//The URL to process the request
'url' : 'page.php',
//The type of request, also known as the "method" in HTML forms
//Can be 'GET' or 'POST'
'type' : 'GET',
//Any post-data/get-data parameters
//This is optional
'data' : {
'paramater1' : 'value',
'parameter2' : 'another value'
},
//The response from the server
'success' : function(data) {
//You can use any jQuery/JavaScript here!!!
if (data == "success") {
alert('request sent!');
}
}
});
});
You're hitting the Same Origin Policy with regard to ajax requests.
In a nutshell, JS/Ajax is by default only allowed to fire requests on the same domain as where the HTML page is been served from. If you intend to fire requests on other domains, it has to support JSONP and/or to set the Access-Control headers in order to get it to work. If that is not an option, then you have to create some proxy on the server side and use it instead (be careful since you can be banned for leeching too much from other sites using a robot).
As others have said you can't access files on another server. There is a hack tho. If you are using a server side language (as i assume you are) you can simply do something like:
http://myserver.com/google.php:
<?php
echo get_file_contents('http://www.google.com');
?>
http://myserver.com/myscript.js
$.get('google.php',function(data){ console.log(data) });
That should work!
you just can access pages from your domain/server

Categories

Resources