sending jquery call to external url - javascript

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

Related

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.

Call REST API in Jquery Ajax POST Method return 403 error

This below code is for calling a Login rest api through jquery ajax but it returns 403 error. I want to know if I missed any necessary parameter in ajax call or it's server side error. That source(HTML file) and destination(API) both in same cloud server.
But the api works fine in postman without any error
$.ajax({
type: "POST",
url: 'https://mzzzzcloudx.am.co.in/login',
dataType: 'json',
data: {
"login": "abcd#gmail.com",
"password": "12345"
}, //{"login":$("#login").val(), "password":$("#pass").val()},
contentType: "application/json",
headers: {
"Content-type": "application/json",
"Access-Control-Allow-Origin": "*"
},
success: function(data) {
console.log(data);
},
error: function(err) {
alert(err); //returns 403 error
console.log(err);
}
});
Do you try to remove the quote in the field names (login, password) of the data section?
data: {
login: "abcd#gmail.com",
password: "12345"}
And also, do you confirm that the field names (login, password) are the same in the REST method login()?

How to add extra fields in request JSON sent to DialogFlow former Api.ai

I am trying to append extra information to the jsonrequest that is sent from my application to DialogFlow. I am aware of the possibility to send data calling an intent by triggering its event from Sending Parameters in a Query Request, and I am using that method already for other functionality.
Basically, I am trying to add a value with the userID, and I need to retrieve that value in DialogFlow. I am keepeing track of the session in php, so I am using phpto get ID value. I have tried to do the following in the ajaxrequest:
$.ajax({
type: "POST",
url: baseUrl + "query?v=20150910",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
//This folllowing line is the modified part:
data: JSON.stringify({
query: text,
lang: "en",
sessionId: "somerandomthing",
userId: "100"
}),
success: function(data) {
},
error: function() {
setResponse("Internal Server Error");
}
});
And this one as well:
$.ajax({
type: "POST",
url: baseUrl + "query?v=20150910",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
//This folllowing line is the modified part:
data: JSON.stringify({
query: text,
lang: "en",
sessionId: "somerandomthing",
userId: "100",
parameters: {
userId: "100"
}
}),
success: function(data) {
},
error: function() {
setResponse("Internal Server Error");
}
});
I need that value in the request to process some data in the back-end based on it. If anyone knows how to do it, or has suggestions for a better approach that would be much appreciated.
There are discussion posts related to this in the DialogFlow Forums, but there is still no resolution. The feature might not be available, or it is not documented Link 1, Link 2, Link 3.
I solved this issue with the help of #Svetlana from Dialogflow. The original post is Here, and here is an example from a JavaScript application with back-end in Node.js:
You would format your request like:
$.ajax({
type: "POST",
url: baseUrl + "query?v=20150910",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
data: JSON.stringify({originalRequest: {data: {exampleMessage: 'Test'}}, query: text, lang: 'en', sessionId: 'somerandomthing'}),
success: function (data) {
},
error: function () {
setResponse("Internal Server Error");
}
});
and you would access the value in the webhook with:
var exampleMessage = req.body.originalRequest.data.exampleMessage;
or
var exampleMessage = req.body.originalRequest.data['exampleMessage'];
Hope this helps.

Simple but struggling to convert POST request from using URL params to request body

I was making a POST request in the following manner, using URL params (which worked):
var PAYLOAD = `
<myxmlcontent>
<attribute name="id">1</attribute>
<attribute name="FullName">Joe Bloggs</attribute>
</myxmlcontent>
`
var URL = 'http://www.somewhere.com/integration?apiKey=company&apiToken=123&payload=' + PAYLOAD;
client.request({
url: URL,
type: 'POST',
contentType: 'application/xml'
}).then(
function(data) {
console.log(data);
}
);
But I wish to put the payload data into the request body.
Is this the correct way to do it? I am not sure, but my attempt has proved unsuccessful so far:
var PAYLOAD = `
<myxmlcontent>
<attribute name="id">1</attribute>
<attribute name="FullName">Joe Bloggs</attribute>
</myxmlcontent>
`
client.request({
url: 'http://www.somewhere.com/integration',
type: 'POST',
contentType: 'application/xml',
headers: {
apiKey: 'company',
apiToken: '123'
},
dataType: 'xml',
data: 'data=' + JSON.stringify(PAYLOAD)
}).then(
function(data) {
console.log(data);
}
);
I am currently building a client-side Zendesk app.
First you have to make sure the endpoint accepts data via POST, otherwise it will fail even if you are seding your data correctly, secondly, if you want to send data as an url-encoded form, you need to change the contentType to application/x-www-form-urlencoded and send the body as either an url-encoded string or by using the FormData object (if it's available in your framework), e.g.:
var myData = new FormData();
myData.append("payload", encodeURI(PAYLOAD));
client.request({
url: 'http://www.somewhere.com/integration',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
headers: {
apiKey: 'company',
apiToken: '123'
},
dataType: 'xml',
data: myData
}).then(
function(data) {
console.log(data);
}
);
Don't forget to also encode the content of payload. In case your endpoint only accepts xml-encoded strings then you'd have to send the string as-is, just make sure to specify the correct contentType, in which case would be application/xml or text/xml.
SOLVED. This is what I had to do (thank you):
var PAYLOAD = `
<myxmlcontent>
<attribute name="id">1</attribute>
<attribute name="FullName">Joe Bloggs</attribute>
</myxmlcontent>
`
var URL = 'http://www.somewhere.com/integration';
client.request({
url: URL,
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
dataType: 'xml',
data: {
apiKey: 'company',
apiToken: '123',
payload: PAYLOAD
}
}).then(
function(data) {
console.log(data);
}
);
Helpful article: How are parameters sent in an HTTP POST request?

jQuery - AJAX Request

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

Categories

Resources