I'm using an API for updating profile, by adding nickname, email, phone or password in request parameters each of them will be updated in database.
I want to pass one of these each time depending on user's choice for example when I want to update Nick name:
{
"nickname": "alifa",
"device_id": "chrome",
"device_model": "browser",
"device_os": "angularJS"
}
or for updating email:
{
"email": "info#example.com",
"device_id": "chrome",
"device_model": "browser",
"device_os": "angularJS"
}
I want to do this by passing property name and property value to a function and it will make an object and send http post request:
this.updateDetails = function(dataName, dataValue){
Loader.global.show();
var data = $.param({
device_id: app.device_id,
device_os: app.device_os,
device_model: app.device_model
});
data[dataName] = dataValue;
console.log(data);
return $http.post(app.baseUrl + 'profile/' , data).success(function(){
Loader.global.hide();
}).error(function(){
Loader.global.hide();
})
}
but what it sends to server is just:
Is there any possible way to do this?
You need to modify the object you pass to param. Adding a property to the string you get out of param is pointless.
var data = {
device_id: app.device_id,
device_os: app.device_os,
device_model: app.device_model
};
data[dataName] = dataValue;
var encoded_data = $.param(data);
Related
i dont know if this is a stupid question but ive made a script that is making a api put call using requests in python. The data im trying to send contains a boolean value. So i have my script like this
import requests
data = {
'name': 'John',
'lastname': "Doe",
'email': "jd#gmail.com",
'is_staff' : True
}
url = 'http://api.url/user/'
response = requests.put(
url, data=data, verify=True, allow_redirects=False)
print(response)
But this gives me a 400 request error.
Then i thought that the problem was with the api call but when i remove the is_staff data.
data = {
'name': 'John',
'lastname': "Doe",
'email': "jd#gmail.com",
}
I get a 200 status code. My inutution is telling me that the api doesnt know what the boolean value from python is. But i could be wrong. Any ideas?
You need to JSON encode your string or rather 'serialize'.
Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is false, the result may contain non-ASCII characters and the return value may be a unicode instance.
Source
import requests
import json
data = {
'name': 'John',
'lastname': "Doe",
'email': "jd#gmail.com",
'is_staff' : True
}
url = 'http://api.url/user/'
headers = {'content-type': 'application/json'}
response = requests.put(url, data=json.dumps(data), headers=headers, verify=True, allow_redirects=False)
print(response)
The requests library takes the data dict and turns it into the request body, the request body is not a dict but a string containing the keys and values. In this case it turns it into the key1=value1&key2=value2 form.
You can view the request body the requests library is sending by:
response.request.body
It returns
'name=John&lastname=Doe&email=jd%40gmail.com&is_staff=True'
In this case the boolean you are sending is turned into "True" or "False". The problem could be that the webserver is expecting a "true" or "false" instead but it depends on the server.
Try:
data = {
'name': 'John',
'lastname': "Doe",
'email': "jd#gmail.com",
'is_staff' : "true"
}
Or the dynamic:
is_staff = True
data = {
'name': "John",
'lastname': "Doe",
'email': "jd#gmail.com",
'is_staff' : str(is_staff).lower()
}
I have templates created in SparkPost dashboard. But the problem I face is that I am not able to send "CC" or "BCC" by making the api calls. The code snippet below will help you understand what I am trying to do.
var SPARKPOST_KEY = "KEY"
var sparkpost = require('sparkpost');
var sparkclient = new sparkpost(SPARKPOST_KEY);
var req_opts = {
transmissionBody : {
content: {
template_id: 'order-confirmation',
from: 'support#domain.in',
subject: 'Order confirmation',
headers: {
"CC": "<anon2#gmail.com>"
}
},
substitution_data: {
"CC": "anon2#gmail.com",
"customer": "Aravind",
"order": 123532
},
recipients: [
{address: {email:'anon1#domain1.in'}},
{address: {email: 'anon2#gmail.com'}}
],
"return_path": "support#domain.in",
}
};
sparkclient.transmissions.send(req_opts, function(err, res){
if(err){
console.log("ERROR");
console.log(err)
}else {
console.log(res.body);
console.log("Mail has been successfully sent");
}
});
As mentioned in the reply on your github issue, you must use either inline content or a template. So as the documentation says, use just template_id in your content.
What needs to happen for this to work is that the headers in the template include a CC header, as described here. Currently there is no way to set the headers of a template in the UI -- it must be done using the API.
To do this execute a PUT against the templates endpoint, in your case https://api.sparkpost.com/api/v1/templates/order-confirmation, with a JSON payload containing the following:
{
"content": {
<other content parts>
"headers": {
"CC": "{{CC}}"
}
}
}
Note that you will also need to use the header_to parameter for your CC recipient to prevent their address showing up in the To: header. In your example this means replacing:
{address: {email: 'anon2#gmail.com'}}
with this:
{address: {email: 'anon2#gmail.com', header_to: 'anon1#domain1.in'}}
You also do not need the return_path parameter.
Hope this helps!
When I try to create an envelope from a template I get a response of:
{ errorCode: 'UNSPECIFIED_ERROR',
message: 'Non-static method requires a target.' }
Here's what I'm doing so far:
First I login, which returns
{ loginAccounts:
[ { name: '*****',
accountId: '*****',
baseUrl: 'https://demo.docusign.net/restapi/v2/accounts/******',
isDefault: 'true',
userName: '***** ********',
userId: '*******-*****-*****-*****-*********',
email: '********#*******.com',
siteDescription: '' } ] }
So then I take the baseUrl out of that response and I attempt to create the envelope. I'm using the hapi framework and async.waterfall of the async library, so for anyone unfamiliar with either of these my use of the async library uses the next callback to call the next function which in this case would be to get the url for the iframe, and with our usage of the hapi framework AppServer.Wreck is roughy equivalent to request:
function prepareEnvelope(baseUrl, next) {
var createEntitlementTemplateId = "99C44F50-2C97-4074-896B-2454969CAEF7";
var getEnvelopeUrl = baseUrl + "/envelopes";
var options = {
headers: {
"X-DocuSign-Authentication": JSON.stringify(authHeader),
"Content-Type": "application/json",
"Accept": "application/json",
"Content-Disposition": "form-data"
},
body : JSON.stringify({
status: "sent",
emailSubject: "Test email subject",
emailBlurb: "My email blurb",
templateId: createEntitlementTemplateId,
templateRoles: [
{
email: "anemailaddress#gmail.com",
name: "Recipient Name",
roleName: "Signer1",
clientUserId: "1099", // TODO: replace with the user's id
tabs : {
textTabs : [
{
tabLabel : "acct_nmbr",
value : "123456"
},
{
tabLabel : "hm_phn_nmbr",
value : "8005882300"
},
{
tabLabel : "nm",
value : "Mr Foo Bar"
}
]
}
}
]
})
};
console.log("--------> options: ", options); // REMOVE THIS ====
AppServer.Wreck.post(getEnvelopeUrl, options, function(err, res, body) {
console.log("Request Envelope Result: \r\n", JSON.parse(body));
next(null, body, baseUrl);
});
}
And what I get back is:
{ errorCode: 'UNSPECIFIED_ERROR',
message: 'Non-static method requires a target.' }
From a little googling it look like 'Non-static method requires a target.' is a C# error and doesn't really give me much indication of what part of my configuration object is wrong.
I've tried a simpler version of this call stripping out all of the tabs and clientUserId and I get the same response.
I created my template on the Docusign website and I haven't ruled out that something is set up incorrectly there. I created a template, confirmed that Docusign noticed the named form fields, and created a 'placeholder' templateRole.
Here's the templateRole placeholder:
Here's one of the named fields that I want to populate and corresponding data label:
As a side note, I was able to get the basic vanilla example working without named fields nor using a template using the docusign node package just fine but I didn't see any way to use tabs with named form fields with the library and decided that I'd rather have more fine-grained control over what I'm doing anyway and so I opted for just hitting the APIs.
Surprisingly when I search SO for the errorCode and message I'm getting I could only find one post without a resolution :/
Of course any help will be greatly appreciated. Please don't hesitate to let me know if you need any additional information.
Once I received feedback from Docusign that my api call had an empty body it didn't take but a couple minutes for me to realize that the issue was my options object containing a body property rather than a payload property, as is done in the hapi framework.
hello i am having this code of jquery:
var fbuid = zuck;
var fbjson = $.getJSON("https://graph.facebook.com/"+fbuid);
how to get the id from json directly into var :
{
id: "4",
first_name: "Mark",
gender: "male",
last_name: "Zuckerberg",
link: "https://www.facebook.com/zuck",
locale: "en_US",
name: "Mark Zuckerberg",
username: "zuck"
}
all i would like to get id from json to var as below:
var fbjson.id;
how i do it using jquery?
So you're close but you've got some things you need to adjust. Ajax is async which means that you're waiting on a server response. You need to fill your data once you have that piece of data. Note you will not be able to reference fbjson until AFTER the getJSON has fired and completed.
According to the jQuery documentation for getJSON
you need to have a callback similar to this -
var fbuid = 'zuck';
var fbjson;
$.getJSON( "https://graph.facebook.com/"+fbuid, function( data ) {
fbjson = data;
});
Notice I assign the fbjson in the callback to data which is the server response. now you can reference it as
fbjson.id
I have a REST API, which returns User object, where its roles are specified via link to another object. So at localhost/project/api/users/27/ is JSON object:
{
"id": 42,
"name": "John",
"prijmeni": "Doe",
"login": "johndoe",
"nickname": null,
"grade": 1.3,
"roles": {
"href": "http://localhost/project/api/users/1716/roles/"
}
}
What I'm trying to do is to get roles in controller. My User service looks like this:
projectServices.factory('User', ['$resource', 'UserRoles',
function($resource, UserRoles, Role) {
var User = $resource('http://localhost/project/api/users/:id', {}, {
'query': {
method: 'GET',
isArray: true
}
});
return User;
}
]);
and I tried to add (to that resource code block):
User.prototype.roles= function(){
return UserRoles.get({id:42});
};
this one freezes browser when called in ngRepeat. So I tried
User.prototype.roles = UserRoles.get({id:42});
this works. Then I tried
User.prototype.roles = $resource(this.roles.href, {}, {
'get': {
method: 'GET',
isArray: true
}
});
says, that roles is undefined. I also tried to add transformResponse param to User service GET action, but that function was never called.
The second option works just perfectly fine - except, that I have to hardcode the user ID. Suitable solution would be with somehow getting the user ID for me (i tried this.id, but that didn't work).
Perfect solution would be creating resource from given href, but as I can't access roles in prototype, I don't know how.
Thanks for any advice.
This should do the trick
projectServices.factory('UserRoles', function(){
return $resource('http://localhost/project/api/users/:id', {id: #id},
{'query': {
method: 'GET',
isArray: true
})
}
Now you can call it with
UserRoles.get({id:42})
// this makes the request : http://localhost/project/api/users/42
The #id tells angular to use the id key from the parameter passed.