jQuery - AJAX Request - javascript

I am working on an app that sends a POST request to a web service. My POST request looks like this:
$.ajax({
type: 'POST', url: getEntityUrl(), cache: 'false',
contentType:'application/json',
headers: {
'api-key':'myKeyHere',
'Content-Type':'application/json'
},
data: {
firstName:'Jon',
lastName:'Smith'
},
success: function() { alert('good job'); },
error: function() { alert('oops'); }
});
When I execute this, I'm getting a 400 Bad Request. I watched the request in Fiddler. I noticed that the parameters I sent are being sent as "firstName=Jon&lastName=Smith". However, they need to be sent across as JSON like I have them defined in the data parameter. I confirmed this is the problem by modifying the request in the composer in Fiddler. What am I doing wrong?
Thanks

If you pass jQuery a plain object through the data parameter (as you do here) then it will encode the data as application/x-www-form-urlencoded.
Just setting the contentType is insufficient.
If you want to send JSON then you must encode it yourself. You can use JSON.stringify for that.
data: JSON.stringify({
firstName:'Jon',
lastName:'Smith'
}),

You need to stringify the data like following.
$.ajax({
type: 'POST',
url: getEntityUrl(),
contentType: 'application/json',
headers: {
'api-key': 'myKeyHere',
'Content-Type': 'application/json'
},
data: JSON.stringify({ firstName: 'Jon', lastName: 'Smith' }), //change here
success: function () { alert('good job'); },
error: function () { alert('oops'); }
});

Related

Python request works, ajax not

I have working requests code in python and need it in ajax
var jsonData = {"x":"y"};
$.ajax({
url: url,
type: 'POST',
data: jsonData,
//dataType: "JSON",
error: function(e) {
console.log(e);
}
});
json: jsonData, JSON.stringify, 'Content-Type': 'application/json' and changing names doesn't work, I tried a lot of things, but everytime error 400
this python code works fine
payload = {
'a':'b',
'a': 'b'
}
#but it doesn't work with field 'data' or 'params', must be named 'json'
r = requests.post(url, json=payload) #data=payload won't work, otherwise error 400
print(r.text)
try setting contentType: "application/json" on ajax

How to convert a Raw body data request for an API to ajax request

I am currently using postman to make an API request that pushes body data. I can get this to work either using "x-www-form-urlencoded" or "raw". See examples below:
I'm trying to convert this to an ajax javascript request but unsure on how to format the body/data text. Here is my script:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
headers: {
"Content-Type": "application/json"
},
data: {
" grant_type=client_credentials
&client_id=***
&client_secret=***
&resource=https://analysis.windows.net/powerbi/api "
},
success: (data) => {
console.log(data.token)
},
error: (data) => {
console.log('rr', data)
}
});
Any help would be appreciated
There's a mismatch here as you're setting the Content-Type header to JSON, yet you're sending form-urlencoded. You need to use one or the other consistently.
If you want to explicitly use JSON, do this:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
contentType: 'application/json', // shorter than setting the headers directly, but does the same thing
data: JSON.stringify({
grant_type: 'client_credentials',
client_id: '***',
client_secret: '***'
resource: 'https://analysis.windows.net/powerbi/api'
}),
success: data => {
console.log(data.token)
},
error: (xhr, textStatus, error) => {
console.log('rr', error)
}
});
If you want to use a form-urlencoded string, do this:
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/***/oauth2/token',
data: 'grant_type=client_credentials&client_id=***&client_secret=***&resource=https://analysis.windows.net/powerbi/api',
success: data => {
console.log(data.token)
},
error: (xhr, textStatus, error) => {
console.log('rr', error)
}
});
Note in the above examples that the first argument to the error handler is not the request or response data as your example seems to expect. I've amended that part to accept the correct arguments.

Access Django Rest Framework API using Javascript - getting a Token

I have an API setup using Django Rest Framework. It works fine when accessing via cURL or HTTPie or even the browsable API. The API has token authentication so initially you have to supply credentials which will return a token. Using HTTPie (or even curl) you would do this:
http POST http://127.0.0.1:8000/api/v1/api-token-auth/ username="user1" password="testpassword"
This would return a response e.g.:
HTTP/1.0 200 OK
Allow: POST, OPTIONS
Content-Type: application/json
Date: Sun, 03 Sep 2017 16:57:38 GMT
Server: WSGIServer/0.2 CPython/3.6.1
X-Frame-Options: SAMEORIGIN
{
"token": "fgfdgfdgfdgfdgd45345345lkjlj"
}
You would then take the token and perform a GET/PUSH/etc like so:
http --json POST http://127.0.0.1:8000/api/v1/test/ test_text="Testing" 'Authorization: Token fgfdgfdgfdgfdgd45345345lkjlj'
I have been Google searching for a while now and cannot find any clear answers as to how the above two lines would translate into Javascript? How do I (1) Pass through credentials to get a token; (2) Retrieve the Token; (3) Use the token to make a GET and PUSH request?
I agree you should use Ajax.
You need an ajax call in the very beginning of you app:
var data = {username:'user',password:'password'}
$.ajax({
type: 'POST',
data: data,
url: 'http://your_url',
success: function(res){
console.log(res)
$.ajaxSetup({
headers: {
"token": res.token
}
});
},
error: function(error) {
callbackErr(error,self)
}
})
Haven`t tested, but idea is use an Ajax call to get the token and use .ajaxSetup to save the token to a header for all following ajax requests.
The you can do this:
var data = {test_text="Testing"}
$.ajax({
type: 'POST',
data: data,
url: 'http://127.0.0.1:8000/api/v1/test/',
success: function(res){
console.log(res) //answer of api call.
});
},
error: function(error) {
callbackErr(error,self)
}
})
Or this:
$.ajax({
type: 'GET',
url: 'http://127.0.0.1:8000/api/v1/ANOTHER_TES/',
success: function(res){
console.log(res) //answer of api call.
});
},
error: function(error) {
callbackErr(error,self)
}
})
Change type parameter of the call to change your request.
See #Tico's answer.
How do I (1) Pass through credentials to get a token; (2) Retrieve the Token; (3) Use the token to make a GET and PUSH request?
$.ajax({
type: 'POST',
data: {
username: "user1",
password: "testpassword"
},
url: 'http://127.0.0.1:8000/api/v1/api-token-auth/',
success: function(res){
$.ajaxSetup({
headers: {
"token": res.token
}});
$.ajax({
type: 'POST',
data: {
test_text: "Testing"
},
url: 'http://127.0.0.1:8000/api/v1/test/',
success: function(res){
alert(res);
}});
}
});
as post, get or any other url calls are asynchronous calls. So in order to maintain the program flow and make the post request you need to use promise feature of js, which will make your post call synchronous.
js promise description
var data = {username:'user',password:'password'}
$.ajax({
type: 'POST',
data: data,
url: 'http://your_url',
success: function(res){
console.log(res)
$.ajaxSetup({
headers: {
"token": res.token
}
});
},
error: function(error) {
callbackErr(error,self)
}
})
this code will work fine if you use this at the starting of your program, but this is asynchronous, to make it synchronous with your program you need to use promise.
And for the third part of your question you need to do this...
$.ajax({
type: 'GET',
url: 'http://your_url' + "/token=" + your_token,
success: function(res){
console.log(res)
},
error: function(error) {
callbackErr(error,self)
}
})

how to covert the jquery ajax reques to angular http request

I am trying to convert old javascript ajax call to angular by using $http method in Angular.
My old one is like
var payload ={'id':'id-abc'}
$.ajax({
type: 'post',
url: 'myurl/com',
dataType: 'json',
data: payload,
success: function (returndata) {
//parse returndata
});
});
in Angular way,
$http({
method: 'post',
url: ‘myurl/com’,
dataType: 'json',
data: payload
}).then(function(returndata) {
console.log(returndata);
})
The angular way gave me
Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response. Issue.
If I mimic the old way and setup the content-type header like
$http({
method: 'post',
url: ‘myurl/com’,
dataType: 'json',
data: payload,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(returndata) {
console.log(returndata);
})
The server response is saying I am missing a params (it doesn’t).
I don’t have the control on the server side so I am not sure how to covert the old $ajax request to the new Angular one. Any ideas? Thanks a lot!
$http default is to serialze data as json
To send form encoded you need to use $httpParamSerializerJQLike which also needs to be injected wherever you use it
$http({
url: myUrl,
method: 'POST',
data: $httpParamSerializerJQLike(myData),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
You could also set up global defaults for the header and a $httpInterceptor to do this transform instead of putting in each individual request

sending jquery call to external url

Here's my call to external api in angular js
$http.post('http://api.quickblox.com/users.json', {
token: quickbloxapitoken,
user: {
email: email,
login: firstname,
password: password
}
}, {
'Content-Type': 'application/x-www-form-urlencoded'
})
.then(function(results) {
var apiid = results.data.user.id;
}
Here my data is sent in two json array like this
And when i try to do the same in jquery i have my call like this
$.ajax({
url: 'http://api.quickblox.com/users.json',
type : 'POST',
data: { token: quickbloxapitoken, login: fbname, password: 'fbuserfbuser', email: fbmail},
success: function(message)
{
console.log(message);
}
})
The datas was sent like this
How can i make my jquery datas sent like the angularjs one ?
I mean like this ?
You need to specify the request contentType as application/json.
Also, if you expect JSON in return, you'd better include the dataType as well (although it's probably automatically guessed):
$.ajax({
url: 'http://api.quickblox.com/users.json',
type : 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({
token: quickbloxapitoken,
user: {
login: fbname,
password: 'fbuserfbuser',
email: fbmail
}
})
});
See Documentation

Categories

Resources