jQuery Ajax request turn into AngularJS $http request - javascript

I have such jQuery Ajax request. I need to turn it into an AngularJS $http request. How can I do that?
$.ajax({
type: "POST",
dataType: "jsonp",
crossDomain: false,
data:{
user: username,
pass: password
},
beforeSend: function (request){
request.setRequestHeader("Accept-Language", languageCode);
},
url: someUrl
})
.done(function (data, textStatus, jqXHR){
console.log(data);
})
.fail(function (jqXHR, textStatus){
console.log("failed");
});
My Angular Implementations
Response {"data" : "", "status" : "200", "config" : .... } Data is empty
login : function (username, password) {
return $http({
method: 'POST',
url: someUrl,
data: {
user: username,
pass: password
},
headers: {
'Accept-Language': languageCode
}
})
}
I succeeded to get data wrapped in JSON_CALLBACK with next request. But I don't know how to call that callback. It is not done automatically. Response looks like {data:"JSON_CALLBACK({mydata})"...}
login : function (username, password) {
var url = someUrl
+ '?callback=JSON_CALLBACK&user=' + username
+ '&pass=' + password;
return $http.post(url);
},

There is no such thing as a JSONP POST request. When jQuery sees dataType: jsonp, it ignores the method propery and uses a script GET request. The data is added as parameters of the URL.
In AngularJS, JSONP requests are specified with method: 'JSONP. The callback parameter needs to be JSON_CALLBACK and must be capitalized.
login : function (username, password) {
return $http({
//method: 'POST',
method: 'JSONP',
url: someUrl,
//data: {
params: {
user: username,
pass: password,
callback: "JSON_CALLBACK"
},
headers: {
'Accept-Language': languageCode
}
})
}
Be aware that since the data is sent as URL parameters, sensitive information such as passwords are vulnerable to snooping attacks.
To demonstrate on JSFiddle:
var url="//jsfiddle.net/echo/jsonp/";
var params = { user: "myUser",
pass: "123456",
callback: "JSON_CALLBACK"
};
$http.jsonp(url, { params: params} )
.then(function onSuccess(response) {
$scope.response = response;
console.log(response);
})
The DEMO on JSFiddle.

Please refer to $http documentation. but here is somewhat counterpart for that jquery request
$http({
method: 'POST',
url: '/someUrl',
data: {
user: username,
pass: password
},
headers: {
'Accept-Language':languageCode
}
}).then(function successCallback(response) {
//do something
}, function errorCallback(response) {
//do something
});

AngularJS error .success is not a function
Might have something to do with it??
What API are you working with?

Related

how to send json data headers to api

I am trying to send SMS through my web app, I bought bulk SMS from SMS supplier, trying to engage with their api.thanks in advance for your help
I post the data through postman and it works (post method, headers section), when I post data from my webpage to their URL it doesn't work,
$(document).ready(function() {
// Add event listener for opening and closing details
$('#testbut').on('click', function() {
var Username = 'xxxxxx';
var password = 'xxxxx';
var language = '1';
var sender = 'RitaFoods';
var Mobile = '2011xxxxx';
var message = 'hello from the other side';
$.ajax({
url: "https://smsmisr.com/api/webapi/?",
method: "POST",
"headers",
data: {
Username: Username,
password: password,
language: language,
sender: sender,
Mobile: Mobile,
message: message
},
dataType: "JSON",
success: function(data) {
alert("done");
alert(JSON.stringify(data));;
}
})
});
});
when I sending this data to another page on my web site, I received it with no problem , and i response with the parameters and alert it, when I sending to api url it gives no response, maybe because I need to send in headers section but I don't know how to do this.
You can set header with the beforeSend function
$.ajax({
url: "https://smsmisr.com/api/webapi/?",
method: "POST",
data: {
Username: Username,
password: password,
language: language,
sender: sender,
Mobile: Mobile,
message: message
},
beforeSend: function(xhr){xhr.setRequestHeader('My-Custom-Header', 'My-Value');},
dataType: "JSON",
success: function (data) {
alert("done");
alert(JSON.stringify(data));;
}
});
or via the headers field
$.ajax({
url: "https://smsmisr.com/api/webapi/?",
method: "POST", "headers",
data: {
Username: Username,
password: password,
language: language,
sender: sender,
Mobile: Mobile,
message: message
},
headers: {
'My-Custom-Header': 'My-Value',
},
dataType: "JSON",
success: function (data) {
alert("done");
alert(JSON.stringify(data));;
}
});
Look at the API documentation.
It says "Post in header not in body", but as a description of what you need to do, this is wrong.
Look at the examples. They show that the data is encoded in the query string of the URL. In HTTP terms, that means it goes in the start line, not a header.
So you need to do something like:
var url = new URL("https://smsmisr.com/api/webapi/?");
url.searchParams.append("Username", Username);
url.searchParams.append("Password", password);
// etc etc
$.ajax({
url: url,
method: "POST",
dataType: "JSON",
success: function(data) {
alert("done");
alert(JSON.stringify(data));;
}
})
See this answer if you need compatibility with older browsers.
Be warned that you are likely to run into the problem described in this question.
try to add in your ajax
contentType: "application/json"
$.ajax({
type: "POST",
url: **your URL**,
data: **your DATA**,
contentType: "application/json",
});

$.Get() method with authentication 401 response

I have an ajax get method, it needs credentials to work.
I have the credenntials to access the API, i don't know how to pass the credentials through the get method:
$.get(url, function (response) {
$.each(JSON.parse(response).canchas, function (key, bucket) {
}
}
thanks!
edit:
$.ajax({
url: "https://tes.r/links/" + id + "/buckets",
data: {username: "backoffice", password: "111111"},
dataType: "JSON",
type: "GET",
success: function (response)
{
$("#ul_list_view").empty();
$.each(response.buckets, function (key, bucket) {
$("#ul_list_view").append('<li><h2>' + bucket.dayOfWeek + '</h2><p>' + bucket.timeOfDay + '</p></li>');
});
$("#ul_list_view").listview("refresh");
},
error: function (response)
{
$("#div_resultado2").addClass("error");
$("#div_resultado2").html(response.responseText);
}
});
Still returning 401, username and password is correct
Assuming you mean the API uses HTTP Basic authentication, use $.ajax instead and pass the username and password properties ~ http://api.jquery.com/jQuery.ajax/
$.ajax(url, {
username: 'backoffice',
password: '111111',
dataType: 'json' // no need for JSON.parse if you tell jQuery the response type
}).done(response => {
$.each(response.canchas, (key, bucket) => {
// etc
})
})

How to handle X-CSRF-Token for jQuery POST in UI5?

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.

AJAX request doesn't execute fail on 400 bad query

I'm sending this request, and it is perfectly fine as long as it's successful. However, if I try to create a user with existing username or email, I should get 400 bad request and response detailing what's the problem.
Thing is, when I send this request and get 400, nothing gets written to console/console (not even the 'fail!' string), but I can see that response is correct in console/network tab so the problem is probably not in the backend.
$("#registerForm").submit(function(e){
e.preventDefault()
$.ajax({
type: "POST",
url: "./register",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
"username": formcontent['username'],
"email": formcontent['email'],
"password": formcontent['password'],
}),
success: function(e) {
window.location.href = './login'
return false
},
fail: function(e) {
console.log('fail!')
console.log(e)
//react to error
return false
},
})
})
I think 'fail' is a invalid function, Please try with below structure
$.ajax({
type : "POST",
url : "/register",
contentType : "application/json; charset=utf-8",
dataType : "json",
data : JSON.stringify({
"username" : formcontent['username'],
"email" : formcontent['email'],
"password" : formcontent['password'],
}),
success : function(response) {
console.log(response);
},
error : function(response, status, err) {
console.log(response);
console.log(status);
console.log(err);
}
});

jQuery JSONP ajax, authentication header not being set

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

Categories