AngularJS (500 Internal Server Error) for http put - javascript

I want to update the record to the api.
In my firebug it shows:
500 internal server error,
XML Parsing Error: no element found Location: moz-nullprincipal:{f514f16e-f3d3-49f1-99e6-105b2b80f26c} Line Number 1, Column 1:
and also under put it shows:
There are no child objects
Here is my code
$scope.EditUser = function(){
$scope.ApplicationId = '7bg67898ewnbqjq65e';
$http.put("mydomain.com/api/Users/UpdateUser", {}, {
params: { _id: $scope.selectedItem._id, ApplicationId: $scope.ApplicationId, User_Name : $scope.selectedItem.UserName, IsActive: $scope.selectedItem.IsActive }
});

This is solved using this
$scope.EditUser = function(){
$scope.ApplicationId = '7bg67898ewnbqjq65e';
$http.put("mydomain.com/api/Users/UpdateUser", {
_id: $scope.selectedItem._id, ApplicationId: $scope.ApplicationId, User_Name : $scope.selectedItem.UserName, IsActive: $scope.selectedItem.IsActive
});

The shortcut method to perform PUT request is: $http.put(url, data, [config]);
#user3055606 your Answer is correct.

Related

Suitescript RESTlet data get Error Empty JSON string

I have issue using POST Function, I want to transform Transfer Order to Item Receipt, But when I tried to execute the script, it failed with error "org.mozilla.javascript.EcmaError: SyntaxError: Empty JSON string (INVOCATION_WRAPPER$sys#24".
Anyone can help me about my issue ?
Here is my Suitescript Code :
function postData (receiptItem) {
doValidation([receiptItem.recordtype], ['recordtype'], 'POST');
if (receiptItem.recordtype == 'transferorder') {
var recordId = [];
var recStr = [];
var objRecord = record.transform({
fromType: record.Type.TRANSFER_ORDER,
fromId: 131, // transfer Order internalid
toType: record.Type.ITEM_RECEIPT,
defaultValues: {
customform: '433'}
});
var itemReceiptId = objRecord.save({
enableSourcing: false,
ignoreMandatoryField: false
});
recordId.push(itemReceiptId)
log.debug({
"title": "[success] recordId: ",
"details": recordId
});
var recLoad = record.load({
type: receiptItem.recordtype,
id: recordId.getValue('internalid')
});
recStr.push({
use_form: recLoad.getText('customform'),
tran_id: recLoad.getValue('tranid'),
tran_date: recLoad.getValue('trandate'),
tran_from: recLoad.getValue('transferlocation'),
tran_to: recLoad.getValue('location'),
tran_ord_id: recLoad.getvalue('createdfrom'),
tran_memo: recLoad.getValue('memo')
});
log.debug({
"title": "recStr",
"details": recStr
});
return recStr;
}
}
return {
post: postData
};
});
It's a syntax error, very likely some misplaced bracket.
Make sure you are posting valid JSON and that the content type is set on your request
You must send data as JSON. if empty or no data then send {} at least in POST as ContentType is Application/JSON. ECMA Standard. The error message clearly states that "Empty JSON string".
Then try this in Postman tool.

Semantic UI Search Module does not display json response

I am trying to get Semantic UI's Search autocomplete to work. Everything seems to be working, except for the fact that the autocomplete always says no results found.
This is an example search:
This is the case even though the server response seems to work fine.
Here is the server responding with JSON:
Finally, here is my JQuery code:
$(".ui.search").search({
apiSettings: {
url : "/subtopics/search.json?query={query}"
},
fields: {
results : 'subtopics',
title : 'name'
},
minCharacters : 2
})
;
From all the examples I've seen this is the proper way to tell Semantic UI what fields to look at, but it's not working.
Any help with this issue would be greatly appreciated.
It turns out using the onResponse callback included in the Semantic UI documentation (http://semantic-ui.com/behaviors/api.html#response-callbacks) is the solution to this problem.
Here is the code that ended up working:
$(".ui.search").search({
type: 'category',
minCharacters: 3,
apiSettings: {
onResponse: function(serverResponse) {
var
response = {
results: {}
}
;
//translate Server API response to work with search
$.each(serverResponse.subtopics, function(index, subtopic) {
var
topic = subtopic.topic || 'Unknown',
maxResults = 8
;
if(response.results[topic] === undefined) {
response.results[topic] = {
name: topic,
results: []
};
}
//add result to category
response.results[topic].results.push({
title: subtopic.name
});
});
return response;
},
url: "/subtopics/search.json?query={query}"
}
})
;

Creating an envelope from a template returning "UNSPECIFIED_ERROR"

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.

correct way to use Stripe's stripe_account header from oauth with meteor

I'm trying to build a platform based on Meteor that uses Stripe Connect. I want to use the "preferred" authentication method from Stripe (Authentication via the Stripe-Account header, https://stripe.com/docs/connect/authentication) so that I can create plans and subscribe customers on behalf of my users. I cannot get it to work. I tried with a second params object, similar to the exemple in the documentation:
var stripeplancreate = Meteor.wrapAsync(Stripe.plans.create, Stripe.plans);
var plan = stripeplancreate({
amount: prod.price,
interval: prod.interv,
name: prod.name,
currency: prod.curr,
id: prod.id+"-"+prod.price+"-"+prod.curr+"-"+prod.interv,
metadata: { prodId: prod._id, orgId: org._id },
statement_descriptor: prod.descr
},{stripe_account: org.stripe_user_id});
but I get "Exception while invoking method 'createStripeProduct' Error: Stripe: Unknown arguments ([object Object]). Did you mean to pass an options object? See https://github.com/stripe/stripe-node/wiki/Passing-Options." which does not seem to accurately reflect the issue but prompted me to try adding stripe_account in the params object itself:
var stripeplancreate = Meteor.wrapAsync(Stripe.plans.create, Stripe.plans);
var plan = stripeplancreate({
amount: prod.price,
(...)
statement_descriptor: prod.descr,
stripe_account: org.stripe_user_id
});
I then get the following error: "Exception while invoking method 'createStripeProduct' Error: Received unknown parameter: stripe_account"
Any ideas? Has anybody managed to have Stripe Connect stripe_account authentication work with Meteor, especially with Meteor.wrapAsync(...)?
This should work for wrapAsync, HOWEVER check out my answer here for possible issues with wrapAsync - Wrapping Stripe create customer callbacks in Fibers in Meteor:
Here is also a great video on wrapAsync: https://www.eventedmind.com/feed/meteor-meteor-wrapasync
var createStripePlanAsync = function(shoppingCartObject, callback){
stripe.plans.create({
amount: shoppingCartObject.plan.totalPrice,
interval: shoppingCartObject.plan.interval,
name: shoppingCartObject.plan.planName,
currency: "usd",
id: shoppingCartObject.plan.sku //this ID needs to be unique!
}, function(err, plan) {
// asynchronously called
callback(err, plan);
});
};
var createStripePlanSync = Meteor.wrapAsync(createStripePlanAsync);
var myShoppingCart = {
customerInfo: {
name: "Igor Trout"
},
plan: {
totalPrice: 5000,
interval: "month",
name: "Set Sail For Fail Plan",
sku: "062015SSFF"
}
};
// Creates the plan in your Stripe Account
createStripePlanSync(myShoppingCart);
Later when you subscribe a customer to a plan you just refer to the plan via the id that you gave the plan when you first created it.
After much trying multiple things, for now, I just managed to get it working using the stripe-sync package instead of the "normal" one + wrapAsync.
try{
var plan = Stripe.plans.create({
amount: prod.price,
...
},{stripe_account: org.stripe_user_id});
}catch(error){
// ... process error
}

Load data into a Backbone collection from JSON file?

I'm trying to load some data into a Backbone Collection from a local JSON file, using this very basic code:
window.Student = Backbone.Model.extend({
});
window.Students = Backbone.Collection.extend({
model: Student,
});
window.AllStudents = new Students();
AllStudents.fetch({ url: "/init.json"});
console.log('AllStudents', AllStudents);
In the console statement, AllStudents is empty. But init.json is definitely being loaded. It looks like this:
[
{ text: "Amy", grade: 5 },
{ text: "Angeline", grade: 26 },
{ text: "Anna", grade: 55 }
]
What am I doing wrong?
UPDATE: I've also tried adding a reset listener above the .fetch() call, but that's not firing either:
AllStudents.bind("reset", function() {
alert('hello world');
});
AllStudents.fetch({ url: "/init.json"});
No alert appears.
UPDATE 2: Trying this script (reproduced here in full):
$(function(){
window.Student = Backbone.Model.extend({
});
window.Students = Backbone.Collection.extend({
model: Student,
});
window.AllStudents = new Students();
AllStudents.url = "/init.json";
AllStudents.bind('reset', function() {
console.log('hello world');
});
AllStudents.fetch();
AllStudents.fetch({ url: "/init.json", success: function() {
console.log(AllStudents);
}});
AllStudents.fetch({ url: "/init.json" }).complete(function() {
console.log(AllStudents);
});
});
Only one console statement even appears, in the third fetch() call, and it's an empty object.
I'm now absolutely baffled. What am I doing wrong?
The JSON file is being served as application/json, so it's nothing to do with that.
The attribute names and non-numeric attribute values in your JSON file must be double quoted (" ") . Single quotes or no-quotes produces errors and response object is not created that could be used to create the models and populate the collection.
So. If you change the json file content to :
[
{ "text": "Amy", grade: 5 },
{ "text": "Angeline", grade: 26 },
{ "text": "Anna", grade: 55 }
]
you should see the non-empty collection object.
You can change your code to see both success and failure as below:
AllStudents.fetch({
url: "/init.json",
success: function() {
console.log("JSON file load was successful", AllStudents);
},
error: function(){
console.log('There was some error in loading and processing the JSON file');
}
});
For more details, probably it will be a good idea to look in to the way ajax response objects are created.
I/O operations in javascript are almost always asynchronous, and so it is with Backbone as well. That means that just because AllStudents.fetch has returned, it hasn't fetched the data yet. So when you hit your console.log statement, the resources has not yet been fetched. You should pass a callback to fetch:
AllStudents.fetch({ url: "/init.json", success: function() {
console.log(AllStudents);
}});
Or optionally, use the new promise feature in jQuery (fetch will return a promise):
AllStudents.fetch({ url: "/init.json" }).complete(function() {
console.log(AllStudents);
});
fetch() returns a 'success' notification as already stated, but that just means that the server request was successful. fetch() brought back some JSON, but it still needs to stuff it into the collection.
The collection fires a 'reset' event when it's contents have been updated. That is when the collection is ready to use...
AllStudents.bind('reset', function () { alert('AllStudents bind event fired.'); });
It looks like you had this in your first update. The only thing I did differently was to put fetch() in front of the event binding.
I think you need to add {add:true} to the options of fetch,
if you assigned the fetch to a variable, you would get the result as well,
but then its not inside the collection you wanted

Categories

Resources