Web Core API Post request get blocked, sometimes - ajax

I have this AJAX call to my Web Core API;
saveProperty = function (url, data, callback, errorCallback) {
$.ajax({
async: true,
type: "Post",
url: url,
data: data,
contentType: "application/json",
dataType: "text"
})
.done(callback)
//.fail(errorCallback);
.fail(function (jqXHR, textStatus, errorThrown) {
alert("Something went wrong: " + textStatus + " " + errorThrown);
errorCallback();
});
}
Sometimes it works, more often it does not.
When I use Fiddler and it works, I see
And when it doesn't I see;
EDIT - I can be more helpful now in describing this problem.
if I have Fiddler up and running before I lanch the aplication in development, I do not get this bug.
Otherwise I do get this bug.
Why is that? I would love to know.
The error is HTTP Error 401.2 - Unauthorized
Why would this happen with the same code?

Related

ajax http get auto change to http post due to set custom header

i have a php API server with below setting :
and i try to consume the API server by below ajax:
$.ajaxSetup({
contentType: "application/json; charset=utf-8",
//contentType: "text/plain",
dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("authorization", "Basic " + oAuthKey);
},
complete: function (xhr, status) {
//
}});
request = $.ajax({
type: "GET",
url: "http://www.example.com/testAPI/users/10004",
async: false,
});
request.done(function (response, textStatus, jqXHR) {
var msg = textStatus;
});
request.fail(function (jqXHR, textStatus, errorThrown) {
var msg = errorThrown;
});
when i watch the activity in Fiddler, the request is using http options instead of http get. i know this is because i am setting xhr.setRequestHeader cause preflight request. Due to the API server required authentication, i have no choice and need to set the customer header.
when i try to run above request inside Fiddler, it manage to return correct json data. But when i run the above java script in my phone gap app, it return error.
*** In fiddler, it will auto use http get, so that is why no error. In my app, it keep using http options.

How do you make an Ajax call to Google Drive API?

My code can get an auth2.0 token...but the examples I've found don't show the final piece of taking a GET, provided here, and turning it into a working request.
Here is the specific URL from that link:
GET https://www.googleapis.com/drive/v3/files/fileId
Here is my AJAX call with the attempt at getting the token (that works) into a hardcoded fileId that I know my Google account has access to.
$.ajax({
type: "GET",
beforeSend: function(request) {
request.setRequestHeader("Authorization", "Bearer" + token);
},
// url: "https://www.googleapis.com/drive/v2/files/18qxc3YgnQ_Yg8n4Q18WCZahE9EPtOZWhoKJuAx6SEHI/permissions",
url: "https://www.googleapis.com/drive/v3/files/18qxc3YgnQ_Yg8n4Q18WCZahE9EPtOZWhoKJuAx6SEHI",
dataType: 'application/json',
processData: true,
success: function(msg) {
console.log('Got File Metadata: ' + msg) + console.log(msg);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('Error: ' + errorThrown + ' / ' + textStatus) + console.log(jqXHR);
}
});
I don't understand how to include the token and the pages and pages of Google documentation do not include any examples of going this route.
I get "invalid credential" errors in the server response.
I don't want to use GAPI because I ran into invalid cookie issues running locally and my code is in a Chrome Extension and it isn't clear whether that approach will work there.
Thank you for any help or direction.
In your code, this line:
request.setRequestHeader("Authorization", "Bearer" + token);
You should have a space after Bearer
request.setRequestHeader("Authorization", "Bearer " + token);

Jquery Ajax request to Asana's oauth2 API

I'm developing an Asana app using Ember.js and I've running into some issue when I need to call the API. The oauth2 sign in/sign up is working great and I receive a working token ( tested it using curl)
I understand that I need to use the "Authorization: Bearer" header to auth with the API and this also work great using curl.
Here's my code:
$.ajax({
url: 'https://app.asana.com/api/1.0/users/me',
type: 'GET',
dataType: "json",
complete: function (resp) { console.log(resp) },
error: function (jqXHR, textStatus, errorThrown) { console.log( textStatus )},
beforeSend: function (xhr) { xhr.setRequestHeader("Authorization: Bearer", "my_access_token") }
});
When I execute this code, I get the following error
Uncaught SyntaxError: Unexpected token : me:1
parsererror
it looks like Asana doesn't reply with a properly encoded JSON file?
this the response that can't be parsed (sorry for the poorly formatted JSON)
{"data":{"id":864403617524,"name":"Sylvain","email":"my#email.com","photo":{"image_21x21":"https://s3.amazonaws.com/profile_photos/864403617524.skysUHPuO07ZftDGJSjY_21x21.png","image_27x27":"https://s3.amazonaws.com/profile_photos/864403617524.skysUHPuO07ZftDGJSjY_27x27.png","image_36x36":"https://s3.amazonaws.com/profile_photos/864403617524.skysUHPuO07ZftDGJSjY_36x36.png","image_60x60":"https://s3.amazonaws.com/profile_photos/864403617524.skysUHPuO07ZftDGJSjY_60x60.png","image_128x128":"https://s3.amazonaws.com/profile_photos/864403617524.skysUHPuO07ZftDGJSjY_huge.jpeg"},"workspaces":[{"id":498346170860,"name":"Personal Projects"},{"id":3958612780941,"name":"insideFPL"},{"id":5502245946578,"name":"Shipping Pixel"}]}}
Any help is much appreciated.
Cheers,
S
The problem seems to be that you have set the Authorization header incorrectly. The following works for me:
$.ajax(
'https://app.asana.com/api/1.0/users/me',
{
type: 'GET',
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer $token")
},
complete: function (resp) {
console.log(resp);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
}
);
Bearer should be at the beginning of the second parameter, and there should be no colon in either string.

JQuery Ajax call often not working on Safari 6

My Ajax call is really simple as below:
function ajax(reqUrl, params , callback) {
console.log("Request URL "+reqUrl);
var cond;
cond = $.ajax({
type: 'post',
url: reqUrl,
data: params,
error:function(){ alert("some error occurred") },
success: callback
});
console.log("Server response "+cond.readyState);
}
// Call it as
var url = "/getResult";
var params = {};
params.param1 = "test1";
params.param2 = "test2";
ajax(url, params, function(returnCallback) {
console.log(returnCallback);
alert("Success");
});
That works fine in most cases. But sometimes (about 1 times in 3) it doesn't return anything to callback.
I found many questions and answers for Not working ajax in Safari but fine in chrome and FireFox. My problem is different from them, because it's fine most of the time (I don't mean it was not fine usually because when I refresh my browser, that may cause my ajax call to work).
My main question is why does my ajax call sometimes fail? I don't get any errors on my JS console. When this situation, I refresh my browser to get my ajax call to. Any Ideas?
Update:
I found that sometimes my ajax call method didn't call out because console.log("Request URL "+reqUrl); did not execute. When I don't want to refresh my browser, I clicked many times on my page's link to produce result. will something late to execute?
Finally, I found error .. Safari doesn't reload my JavaScript files again even disable Cache. So I put all of my JS code into:
$(document).ready(function(){
// start load my js functions
init();
});
to reload my JS files when my page was ready. Cheer !
I also met this problem.
When I moved all code into $(function() {}), it worked.
After that, I found I had defined a variable named key, which caused the problem.
Just rename it, all things will be running.
This seems to be a Safari issue. In this post there is a suggestion to add a beforeSend to your ajax-request.
In your case:
cond = $.ajax({
type: 'post',
url: reqUrl,
data: params,
beforeSend: function (event, files, index, xhr, handler, callBack) {
$.ajax({
async: false,
url: 'closeconnection.php' // add path
});
},
error:function(){ alert("some error occurred") },
success: callback
});
Please Test below Code. it is working fine.
$.ajax({
type: "POST",
url:'#Url.Action("getResult","Controller")',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.toString());
});
This is use for MVC application.
$.ajax({
type: "POST",
url:'getResult',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("here" + data.toString());
});
For Asp.net Application :
$.ajax({
type: "POST",
url:'getResult',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("here" + data.toString());
});
if u have still the issue than please post ur complete code here. i will test and reply soon

Returning Json from controller, never a success

I'm successfully posting to my controller with the following code, however, success is never being hit only error. What am I doing wrong?
JS:
$.ajax({
url: '/Home/Subscribe',
type: 'POST',
dataType: 'json',
data: { email: $('#sube').val() },
success: function (data) {
// get the result and do some magic with it
alert(data.foo);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
Controller:
[HttpPost]
public JsonResult Subscribe(string email)
{
return Json(new { foo = "bar", baz = "Blech" });
}
In IE, press F12 to open developer tools. Go to Network tab and click on Start Profiler. Send a request to your Subscribe action - in a list below you will see details of sent request and returned status code. Double click on request to see details - you can then see body of your response. If the request failed with a server error, you will see that error in a body of your response.
One wrong thing I see with your code is that you have hardcoded the url:
url: '/Home/Subscribe'
You should never do this. You should always use url helpers when generating urls in an ASP.NET MVC application:
url: '#Url.Action("Subscribe", "Home")'
Also you are saying that the error callback is always hit but you didn't say what you observed in FireBug or Chrome Developer toolbar when you tried to analyze the AJAX request. If you had done this you would have seen the exact cause of failure for the request because you would have seen what request is sent to the server and what response does the server sends back to the client.
The following is my jQuery ajax snippet that works. Your controller looks right. I assume you have verified it is actually getting called by using a breakpoint.
var p = {
email: $('#sube').val()
};
$.ajax({
url: '#Url.Action("Subscribe", "Home")'
type: 'POST',
data: JSON.stringify(p),
dataType: "text json",
contentType: "application/json",
success: function (data) {
// get the result and do some magic with it
alert(data.foo);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});

Resources