iron-ajax ignores duplicate params - javascript

So I am using iron-ajax's params to send queries to my api; the params field of the ajax calls this function params="ajaxParams". The problem i've ran into is that when I call amount: ... more than once the second one replaces it in the query.
//enters praramaters into the iron-ajax params, this automatically
// gets added onto the ajax link, and will generate a new request when a change happens.
_getParams: function(searchQuery, amountMin, amountMax){
return{
name: searchQuery,
amount: '>=' + amountMin,
amount: '<=' + amountMax
}
},
This is what the encoded query string looks like in the xhr request:
path/to/api/data?name=bob&amount=%3C%3D50000
And the query for this was:
name: 'bob',
amount: '>=' + 5000,
amount: '<=' + 50000
Additionally Ive tried:
return{
name: searchQuery,
amount: '>' + amountMin + '&amount<' + amountMax
}
but the out put just gets encoded into:
path/to/api/data?name=bob&amount=%3E5000%26amount%3C50000
To summarise I am trying to get the following query from iron-ajax params, but it seems that the params argument wont accept having duplicate parameters:
path/to/api/data?name=bob&amount=%3E5000&amount=%3E50000
Edit:
as Gar pointed out this seems to be a js issue where 2 object properties are bieng returned, as a work around to this I tried to get rid of the params and just add the variables to the api url:
<iron-ajax auto
url="path/to/api/data?name={{searchQuery}}
&amount=>={{amountMin}}
&amount=<={{amountMax}}"
handle-as="json"
method="GET"></iron-ajax>
this will break the url into this though
path/to/api/data?name=%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&amount=%3E=5000%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20&amount=%3C=50000

Related

Refresh data in table after creating a record

In my Ui5 app I have added CREATE operation using oData. But when i am trying to create entry it is getting added in backend but in table it is showing NO DATA (refer image 1). but when I refresh the same page it is there (refer image 2). With single entry ,it is automatically getting refreshed 
problem is with Multiple entries.
Please refer the screenshot and code for clear view.
After Clicking CREATE button:
After Refreshing WebPage:
onCreate: function() {
var oModel = this.getView().getModel();
var contactEntry1 = {
ProductID: 'KT-1960',
TypeCode: 'AD',
SupplierID: '0100000001',
TaxTarifCode: 1,
Category: 'Notebooks',
MeasureUnit: 'EA',
CurrencyCode: 'EUR',
Name: 'Urvish',
Description: 'First batch entry',
},
contactEntry2 = {
ProductID: 'KT-1982',
TypeCode: 'AD',
SupplierID: '0100000001',
TaxTarifCode: 1,
Category: 'Notebooks',
MeasureUnit: 'EA',
CurrencyCode: 'EUR',
Name: 'Urvish',
Description: 'Second batch entry',
};
oModel.setUseBatch(true);
oModel.create('/ProductSet', contactEntry1);
oModel.create('/ProductSet', contactEntry2);
oModel.refresh(true);
},
Looks like that you use the asynchronous operation for create but think that they are synchronous.
In order to fix this out, you can send these 2 create in one $batch request, but use the createEntry method of ODataModel, in order to use the submitChanges method, the callback of which, will be called once two of items are successfully created on the backend side (the below code example should be relevant for v2.ODataModel):
var oTableItemsBinding = oTable.getBinding("items");
// define the group ID, which will be used later on
var aCurrentDeferredGroups = oModel.getDeferredGroups();
oModel.setDeferredGroups(aCurrentDeferredGroups.concat("createProductGroup"));
// create two entries one by one, specifying the 'groupId' parameter
oModel.createEntry("/ProductSet", {
properties: contactEntry1,
groupId: "createProductGroup"
});
oModel.createEntry("/ProductSet", {
properties: contactEntry2,
groupId: "createProductGroup"
});
// send 2 requests in one $batch, passing the name of the 'groupId'
oModel.submitChanges({
groupId: "createProductGroup",
success: function() {
// no need to call refresh() as the model already does it by default (See "refreshAfterChange")
}.bind(this)
});
If your service does not support $batch requests, then you can still use the create method, but make use of it's success callback to be sure that the entry has been persisted in the backend.

AngularJS (500 Internal Server Error) for http put

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.

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.

How to post JSON array of objects using JQuery

I am using Javascript/jQuery in the Chrome browser console to post data to a page. (I'm doing this in Shopify admin, because it doesn't have the capability to bulk import shipping rates).
This is the code I am using:
make_weight_based_shipping_rate(8267845, 98, 99, 'Test Shipping Rate', 59);
function make_weight_based_shipping_rate(cid, minWeight, maxWeight, name, price) {
$.post('/admin/weight_based_shipping_rates.json', {
weight_based_shipping_rate: {
country_id: cid,
name: name,
offsets: [{disabled:true, offset:0, province_id:145570341}, {disabled:true, offset:0, province_id:145570345}],
weight_high: maxWeight,
weight_low: minWeight,
price: price
}
});
}
It works well, except for one line of my request which has an array of objects - the line that begins with 'offsets'.
If I only have one JSON object on this line, and not in an array (by excluding the square brackets), this code works. However, as an array, Shopify comes back with the error '422 (Unprocessable Entity)' and in the body of the response it says '{"errors":{"shipping_rate_offsets":["is invalid"]}}'.
Am I formatting this JSON object incorrectly? If not, is there some other way I can achieve this rather than use the JQuery Post method?
I eventually figured it out. By default, JQuery POST and AJAX requests are encoded as "application/x-www-form-urlencoded". This works most of the time, but it seems to fail when it gets an array such as 'offsets'.
To get around this, first I had to use the JSON.stringify() function on the data being submitted. Then prior to making the POST, I used the ajaxSetup() function to set the content-type to "application/json". My modified code is now:
make_weight_based_shipping_rate(8267845, 98, 99, 'Test Shipping Rate', 59);
function make_weight_based_shipping_rate(cid, minWeight, maxWeight, name, price) {
$.ajaxSetup({
contentType: "application/json; charset=utf-8"
});
$.post('/admin/weight_based_shipping_rates.json', JSON.stringify({
weight_based_shipping_rate: {
country_id: cid,
name: name,
offsets: [{disabled:true, offset:0, province_id:145570341}, {disabled:true, offset:0.00, province_id:145570345}],
weight_high: maxWeight,
weight_low: minWeight,
price: price
}
}));
}
I hope this helps others.

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