Here I have two for me the same request: jquery ajax and XMLHttpRequest but JQ ajax dont work... SO want to know what is the difference:
JQ ajax:
var urlAjax = "http://www.agroagro.com/v1/register";
$.ajax({
type: "POST",
url: urlAjax,
contentType: "application/x-www-form-urlencoded",
data: {
name: "Mile3",
email: "new1#new.com",
password: "face1book"
},
crossDomain:true,
success: function(data) { console.log(data); },
error: function(data) {console.log(data); },
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
},
headers: {
'Access-Control-Allow-Origin': '*'
}
});
});
});
and this ajax request dont work... give me 404 error...
XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {"done"}
}
xhr.open("POST","http://agroagro.com/v1/register",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("name=Henry&email=Ford#ford.com&password=1234");
This request work fine, but I need to know what is the difference, the both call POST url...
Also what I need to change in my JQ ajax request to work?
Access-Control-Allow-Origin is a response header so it shouldn't be on the list of request headers: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#The_HTTP_response_headers
Remove the following:
beforeSend: function (xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
}
and
headers: {
'Access-Control-Allow-Origin': '*'
}
Related
I have this code and it works as expected when page loads, but when I'm trying to make that call after checking checkbox it will show Request header field x-csrf-token is not allowed by Access-Control-Allow-Headers in preflight response.
$.ajax
({
type: 'POST',
url: "https:/www.bb.com?uId=123&mId=123",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", "Basic dTHIgdfgsjdhgfsgfjhsfghsfkjs879"); },
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
}
});
and for checking:
$("input:checkbox[name=list]").click(function () {
if ($(this).is(':checked')) {
do that call
}
});
any Idea how to sole that?
ok, so that was fixed by a backend code release. Thanks all for help
I want to use jQuery POST method to call an xsjs service that does some modifications in Database.My xsaccess file prevents xsrf, so I need to handle it in my controller method.
Below is my controller code-
var obj= {};
obj.name= "John";
obj.age= "abc#xyz.com";
obj.loc= "Minnesota";
jQuery.ajax({
url: "serviceTest.xsjs",
type: "GET",
data: JSON.stringify(obj),
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", "Fetch");
},
success: function(responseToken, textStatus, XMLHttpRequest) {
var token = XMLHttpRequest.getResponseHeader('X-CSRF-Token');
console.log("token = " +token);
jQuery.ajax({
url: "serviceTest.xsjs",
type: "POST",
data: JSON.stringify(obj),
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", token);
},
success : function(response) {
// will be called once the xsjs file sends a
response
console.log(response);
},
error : function(e) {
// will be called in case of any errors:
var errMsg = e.responseText
console.log(e);
}
});
},
And here is my xsjs code-
var csrf_token = $.request.headers.get("X-CSRF-Token");
if(csrf_token === "Fetch") {
var content = $.request.body.asString();
var args = $.parseJSON(content);
var xsName= args.name;
var xsemail= args.email;
var xsLoc= args.loc;
//then execute DML statement by passing these 3 parameters as arguments.
catch (error) {
$.response.setBody(content);
$.response.status = $.net.http.INTERNAL_SERVER_ERROR;
}
I am not able to do the update and getting error Err 500 - Internal server Error.
Any suggestions would be extremely helpful
Edit:
If I forgot the token then I got a 403 Access denied error ("CSRF token validation failed") and not a 500 internal. So I think something is wrong with your services
You can add your X-CSRF-Token as header of your POST request with setup your ajax requests before your fire your POST.
$.ajaxSetup({
headers: {
'X-CSRF-Token': token
}
});
jQuery.ajax({
url: "serviceTest.xsjs",
type: "POST",
data: JSON.stringify(obj),
beforeSend: function(xhr) {
Otherwise add it to each POST request.
jQuery.ajax({
url: "serviceTest.xsjs",
type: "POST",
data: JSON.stringify(obj),
headers: {
'X-CSRF-Token': token
},
beforeSend: function(xhr) {
Your way with using beforeSend event should work too.
I am trying to complete a GET request using $http instead of ajax. The call works perfectly with ajax, but when I try to do the same thing with $http I get a 400 (Bad Request) error. I believe I am following the Angular documentation correctly. Any ideas? Hopefully this will also be helpful for others experiencing the same issue.
The ajax code that works:
$.ajax({
type: "GET",
accept: 'application/json',
url: myURL,
headers: {"Authorization": "Basic " + basicKey},
dataType: "json",
contentType: 'application/x-www-form-urlencoded',
data: requestPayload,
async: false
}).done(function(serverData) {
console.log(serverData.access_token);
}).fail(function(error) {
console.log(error);
});
The $http code that does not work:
var basicConfig = {
method: 'GET',
url: myURL,
headers: {
'Authorization': 'Basic ' + basicKey,
'Accept': "application/json",
'Content-Type': 'application/x-www-form-urlencoded'
},
data: requestPayload
}
$http(basicConfig).success(function(data, status){
console.log(status);
}).error(function(data, status){
console.log(status);
});
Thanks in advance.
use params instead of data. data is the request body, used for POST requests, whereas params is for query string variables in GET requests.
I'm currently having issues making an external GET request for an API that I need to call and retrieve data from dynamically in JSON. Does anyone know what below may be incorrect? The main issue seems to be that the header information for the Authentication field is not being set correctly and that javaScript can't call out of local domains. I desperately need a work around to this : (error: XMLHttpRequest cannot load http://www.website.com/api.php. Origin http://localhost is not allowed by Access-Control-Allow-Origin.)
function requestDealer(url)
{
alert("looking up dealer");
var request = new XMLHttpRequest();
$.ajax({
url:url,
type: 'GET',
data: null,
Accept : "application/json",
contentType: "application/json",
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
}
function setHeader(xhr) {
xhr.setRequestHeader('Authorization', 'NLAuth nlauth_account=23984390, nlauth_email = email#email.com, nlauth_signature= myPwrd');
xhr.setRequestHeader('Content-Type', 'application/json');
}
I'm trying to make an ajax request to the google contacts API with the following setup:
$.ajax({
url: "https://www-opensocial.googleusercontent.com/api/people/#me/#all",
dataType: 'jsonp',
data: {
alt: 'json-in-script'
},
headers: {
'Authorization': 'Bearer ' + token
},
success: function(data, status) {
return console.log("The returned data", data);
}
});
But the Authentication header doesn't seem to get set. Any ideas?
I had the same problem recently. Try this:
$.ajax({
url: "https://www-opensocial.googleusercontent.com/api/people/#me/#all",
dataType: 'jsonp',
data: {
alt: 'json-in-script'
},
success: function(data, status) {
return console.log("The returned data", data);
},
beforeSend: function(xhr, settings) { xhr.setRequestHeader('Authorization','Bearer ' + token); }
});
EDIT: Looks like it can't be done with JSONP. Modify HTTP Headers for a JSONP request
When authentication is needed in a cross domain request, you must use a proxy server of some sort.
Since using dataType: jsonp results in the HTTP request actually being made from the script that gets added to the DOM, the headers set in the $.ajax will not be used.
Is seems that most of the OAUTH2 REST resources accept the access_token parameter as part of the request url
http://self-issued.info/docs/draft-ietf-oauth-v2-bearer.html#query-param
please, try the following code instead:
$.ajax({
dataType: 'jsonp',
url: url,
data: {
'access_token':token.access_token
},
jsonpCallback: 'thecallback',
success: function(data){
_cb(data);
},
error: function(d){
_cb(d);
}
});
Just do this (jquery 2.0, but should work in previous versions)
$.ajax({
url: "/test",
headers: {"Authorization": "Bearer " + $('#myToken').val()}
})
.done(function (data) {
console.log(data);
})
.fail(function (jqXHR, textStatus) {
alert("error: " + textStatus);
});