jQuery.ajax - Why does it not work? - javascript

I just can't get the ajax service to work. A simple class to $.get("http://google.com") does not work. Also, this code does not work, too:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<script>
$.ajax({
url: "http://google.com",
dataType: "html",
success: function(data, status) {
console.log("Success:");
console.log(" Data: " + data);
console.log(" Status: " + status);
},
error: function(request, status, error) {
console.log("Error:");
console.log(" Request: " + request);
console.log(" Status: " + status);
console.log(" Error: " + error);
},
});
</script>
</body>
</html>
saved in test.html.
This is the output on the console:
Error:
Request: [object Object]
Status: error
Error:
And these are the, I guess, important values of the returned object:
readyState 0
responseText ""
status 0
statusText "error"
Why does the request not work?
Thank you,

You can't use AJAX to access cross-domain scripts like that. This is because of the Same Origin Policy -- something which has been implemented for security reasons:
This mechanism bears a particular significance for modern web
applications that extensively depend on HTTP cookies to maintain
authenticated user sessions, as servers act based on the HTTP cookie
information to reveal sensitive information or take state-changing
actions. A strict separation between content provided by unrelated
sites must be maintained on client side to prevent the loss of data
confidentiality or integrity.
So you have a few options:
Just call scripts on your own server
Call scripts on your server which can communicate with third-party sites/apps/scripts
Use either JSONP or XML as a callback format.

You cannot make a request to another domain due to the same-origin-policy. See http://api.jquery.com/jQuery.ajax/ for more information.

You could use JSONP to achieve cross domain communication.
http://en.wikipedia.org/wiki/JSON#JSONP
But for plain html you have yo be on the same domain.
$.ajax({
url: "http://google.com",
dataType: "jsonp",
success: function(data, status) {
console.log("Success:");
console.log(" Data: " + data);
console.log(" Status: " + status);
},
error: function(request, status, error) {
console.log("Error:");
console.log(" Request: " + request);
console.log(" Status: " + status);
console.log(" Error: " + error);
},
});
EDIT:
But if your URL doesn't return a valid formatted json, your request will fail.
For a working example check:
http://jsfiddle.net/S3tAR/1/

Related

Cross origin POST request not working for Outlook API

I'm using this part of the Outlook API. It says that you should be able to do a post request, however when I try I get the following error:
Failed to load https://login.microsoftonline.com/common/oauth2/v2.0/token: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3003' is therefore not allowed access. The response had HTTP status code 400.
How do I fix this though? I obviously don't have access to Outlook's servers, but surely they would let me do a post request considering that's what it says to do in the documentation!.
Here is my code by the way if that helps:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
let url = new URL(window.location);
let code = url.searchParams.get('code');
let redirect = 'http%3A%2F%2Flocalhost%3A3003%2Fauth-process-token.html';
let clientId = '<MY ID>';
let clientSecret = '<MY KEY>';
var req_string = 'grant_type=authorization_code&code=' + code + '&redirect_uri=' + redirect + '&client_id=' + clientId + '&client_secret=' + clientSecret;
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
crossDomain: true,
data: req_string,
dataType: 'application/x-www-form-urlencoded',
success: function (responseData, textStatus, jqXHR) {
var value = responseData.someKey;
},
error: function (responseData, textStatus, errorThrown) {
console.log('POST failed.', errorThrown);
}
});
</script>
EDIT: I fixed the "bad request" error, but it still gives me the other one.
One workaround for this is by using cors.io
http://cors.io/?http://your_link
so it would be
http://cors.io/?https://login.microsoftonline.com/common/oauth2/v2.0/token

Why am I getting a 400 error?

I am making a post request to add a subscription to a user, but I get this error Result: Request failed with response code 400 https://stripe.com/docs/api/curl#create_subscription
Parse.Cloud.define("Subscription", function(request, response){
Parse.Cloud.httpRequest({
method:"POST",
url: "https://" + 'sk_test_***' + ':#' + 'api.stripe.com/v1' + "/subscriptions/" + 'plan=' + request.params.customerId + 'customer=' + request.params.plan,
success: function(httpResponse){
response.success(httpResponse.data);
},
error: function(httpResponse){
response.error('Request failed with response code ' + httpResponse.status);
}
});
});
First, I'd suggest you go to your Stripe dashboard and review the logs to see what the actual error was - that might help clear this up for you.
I'm not very familiar with Parse Cloud, but just wandering around the code I see that's based on the request module so based on how that library handles POSTing forms, I think it should probably look like this:
Parse.Cloud.define("Subscription", function(request, response) {
Parse.Cloud.httpRequest({
method: "POST",
url: "https://" + 'sk_test_***' + ':#' + 'api.stripe.com/v1/subscriptions/',
form: {
plan: request.params.customerId,
customer: request.params.plan
},
success: function(httpResponse) {
response.success(httpResponse.data);
},
error: function(httpResponse) {
response.error('Request failed with response code ' + httpResponse.status);
}
});
});
You can do something like this just to check. Furthermore your url is wrong
Parse.Cloud.define("Subscription", function(request, response) {
Parse.Cloud.httpRequest({
method: "GET",
url: "https://api.stripe.com/v1/subscriptions -u sk_test_"+ 'User_id'+ '-d plan=' + request.params.customerId+ '-d customer='request.params.plan",
success: function(httpResponse) {
response.success(httpResponse.data);
},
error: function(httpResponse) {
response.error('Request failed with response code ' + httpResponse.status);
}
});
});
Replace your url in the correct format. I hope it helps.

recpatcha returns 200, still get error with jQuery ajax

All of my other searches yield responses about cross-domain requests. It appears that I'm not having a problem with that. I'm getting a response from the recaptcha server, but it's not being interpreted correctly.
<script>
function verifyCaptcha() {
jQuery.ajax({
method: "POST" ,
url: "https://www.google.com/recaptcha/api/siteverify",
data: { secret: "xxxxxxxxxxxxxxxxxxx" , response: "<% $recaptcha_response %>" },
dataType: 'jsonp' ,
success: function( result ) {
alert( result.success ) ;
},
error: function( xhr ) {
alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' Response Text: ' + xhr.responseText);
}
})
}
onload=verifyCaptcha ;
</script>
This function lives in a page that's the target of a submitted form. When I check fireBug for the results, I get this in my alert message:
Request Status: 200 Status Text: success Response Text: undefined
And the response captured by FireBug is
{
"success": true
}
It seems that it gets mad without the parens wrapped around the returned JSON which I thought were supposed to come free with dataType: 'jsonp'
How do I resolve the success of this?
UPDATE
Adding additional return parameters to the error funcion: ( xhr , message , errorThrown ) produced the following:
Request Status: 200
Status Text: success
Response Text: undefined
Message: parsererror
ErrorThrown: Error: jQuery1120043068059910713263_1455115913634 was not called
I'm guessing that the jQuery1120043068059910713263_1455115913634 was not called message is the callback function randomly named by jQuery. Does this mean that I need to add something to my logic, or that the reCaptcha server does not indeed support jsonp ?
Setting the dataType to "json" gives me a request status of 0.
UPDATE 2
I added this to my function:
jsonp: false,
jsonpCallback: 'onJSONPLoad',
and my errorThrown text changed to:
Error: onJSONPLoad was not called which leads me to conclude that reCaptcha does not support jsonp. Can anyone confirm this?
I guess the Answer is:
The POST method is not available for jsonp, only GET
update:
As well as in the comment stated setting the dataType to"json" and it will automatically converted to jsonp, maybe try that
also you can add a third argument to the error function
error: function( xhr, message, errorThrown ) {
and errorThrown maybe is more explicit

AJAX request not working on remote host

I've got an AJAX request which pulls the data from the form and POSTs it to an API. The weird thing is it works perfectly fine on localhost but fails silently when I upload to remote server. And I mean silently: the response code is blank, there's nothing in the logs. I've checked on Firefox and Chrome. jQuery is loaded, function is firing properly. The code is below:
function send() {
console.log("preparing");
var beacon = {
beaconID: $("#beaconID").val(),
name:$("#beaconName").val(),
campaignID:$("#campaignID").val(),
clientID:$("#clientID").val()
}
console.log("payload:");
console.log(beacon);
$.ajax({
type: 'POST',
url: '../beaconAPI/index.php/createBeacon',
data: JSON.stringify(beacon),
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (response) {
console.log("done:");
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
From the comments you posted
10:33:21.046 "{"readyState":0,"responseText":"","status":0,
"statusText":"error"}" addBeacon.html:34 10:33:21.046 "AJAX error: error : "
A status code of zero means one of two things:
You are running off file protocol
The page refreshed as Ajax call is made
Since you said this is on production, sounds like it is a case of #2.
So you need to cancel the action that is causing the page to refresh. Since you do not show how you call send, here is some basic ways of cancelling the action.
onclick="send(); return false"
onsubmit="send(); return false"
$("#foo").on("click", function(e) {
send();
e.preventDefault();
});

How can I catch jQuery AJAX errors?

When an AJAX request is submitted to a site, server-side errors are easily handled with the jQuery promise approach. .done(), .fail(), etc. However for some requests (e.g. to an invalid site or one that doesn't accept cross-origin requests), an exception occurs immediately as the call is made. Here's an example of one error in the console:
XMLHttpRequest cannot load http://someotherserver/api/blahblah. Origin
http://localhost:52625 is not allowed by Access-Control-Allow-Origin.
Yes, I know about CORS...that's not the issue. What I'm actually doing is trying a web api call to test if the server IP/name is correct
I'm aware of the error option in the jQuery request syntax:
$.ajax({
url: remoteURL,
type: 'GET',
error: function (err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
}).etc.etc.
The error is handled here, but exceptions are still logged in the console. It seemed reasonable to wrap the above in a try-catch block, but that doesn't seem to help.
I've found this question, but the solution involves hacking the jQuery code. Surely there's a better way to catch these errors and not clog up the console logs??
try this:
$.ajax({
url: remoteURL,
type: 'GET',
error: function (err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
}).always(function(jqXHR, textStatus) {
if (textStatus != "success") {
alert("Error: " + jqXHR.statusText);
}
});
XHR Listener:
$.ajax({
url: remoteURL,
type: 'GET',
xhr: function(){
var xhr = new window.XMLHttpRequest();
xhr.addEventListener("error", function(evt){
alert("an error occured");
}, false);
xhr.addEventListener("abort", function(){
alert("cancelled");
}, false);
return xhr;
},
error: function (err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
});
You can use web developer console in google chrome. Press F12. And use Networks tab for checking response, And for JavaSvript and jQuery and Ajax errors you can use Console tab. :)
Try this by adding to your ajax function :
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);

Categories

Resources