Advice on handling multidimensional array with Codeigniter or possible other solution? - javascript

I have a list of users and checkboxes, I need to get the id's of each check box:checked as well as a subject field and a message field and pass to my controller. The only way I could think to do this was to grab each id and duplicate the subject and message fields and pass to a multidimensional array to my controller. My array looks like this:
[{id: "46", subject: "sample subject1", message: "test message1"}{id: "46", subject: "sample subject1", message: "test message1"}]
This seems really redundant as I only need the list of user ids and 1 copy of the message and subject fields in the array but not sure if there is a better way to do this or not. Is it possible to send two different arrays via ajax to my codeigniter controller? If so how do I access them in the controller?
Here is an example of my code to collect ids and create the array. If this is the best method I am still not sure how to handle a multidimensional array in my controller. Normally I would access the array contents using $this->input->post('key') but, that wont work: I think I would need to loop through the array first in the controller but not sure how to do.
Here is my code:
$(document).on('click', '.send_btn', function(e) {
//get ids of selected users
var subject = 'test subject';
var message = 'test message';
var data = [];
$(':checkbox[name="people_checked[]"]:checked').each (function () {
data.push({
id: this.id,
subject: subject,
message: message
})
});
$.ajax({
url: "/message/send_message",
method: "POST",
success: function (data) {
console.log('Success');
}
})
});
Any help advice is much appreciated.

If you want to DRY up the array, convert it to an object which has the subject and message properties in the root. Then you can provide the ids property as an array. It would look something like this:
$(document).on('click', '.send_btn', function(e) {
var data = {
subject: 'test subject',
message: 'test message',
ids: $(':checkbox[name="people_checked[]"]:checked').map((i, el) => el.id).get()
};
$.ajax({
url: "/message/send_message",
method: "POST",
data: data, // note this was added, you didn't send a body in the original
success: function(data) {
console.log('Success');
}
})
});
The output would be:
{
subject: 'test subject',
message: 'test message',
ids: [ 123, 987 ]
}
You would obviously need to amend your /message/send_message endpoint to work with a request body in that format.

Related

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.

In Select2, how do formatSelection and formatResult work?

I'm using Select2 (http://ivaynberg.github.io/select2/) to have an input field of a form (let's say its id is topics) to be in tagging mode, with the list of existing tags (allowing the user to choose some of these tags, or to create new ones) being provided by an array of remote data.
The array (list.json) is correctly got from my server. It has id and text fields, since Select2 seems to need these fields. It thus looks like this:
[ { id: 'tag1', text: 'tag1' }, { id: 'tag2', text: 'tag2' }, { id: 'tag3', text: 'tag3' } ]
The script in the HTML file looks like this:
$("#topics").select2({
ajax: {
url: "/mypath/list.json",
dataType: 'json',
results: function (data, page) {
return {results: data};
},
}
});
But the input field is showing "searching", which means it's not able to use the array for tagging support.
In the script with Select2, I know I have to define formatSelection and formatInput, but I'm not getting how they should work in my case, although I have read the Select2 documentation... Thank you for your help!
You need to add the function like explained here. In your example:
function format(state) {
return state.text;
}

How to add a new object to an array nested inside an object?

I'm trying to get a handle on using $resource in angularjs and I keep referencing this answer AngularJS $resource RESTful example for good examples. Fetching a record and creating a record work fine, but now i'm trying to add a "section" to an existing mongo record but can't figure it out.
documents collection
{
_id: 'theid',
name: 'My name",
sections: [
{
title: 'First title'
},
{
title: 'Second title'
}
]
}
angular controller snippet
var document = documentService.get({_id: 'theid'});
// TRYING TO ADD $scope.section TO THE SECTIONS ARRAY IN THE VARIABLE document.
//document.sections.push($scope.section); <-- This does NOT work
//document.new_section($scope.section); <-- could do this and then parse it out and insert it in my backend code, but this solution seems hacky and terrible to me.
document.$save(function(section) {
//$scope.document.push(section);
});
documentService
return $resource(SETTINGS.base + '/documents/:id', { id: '#id' },
{
update: { method: 'PUT' }
});
From the link i posted above, If I was just updating the name field, I could just do something like this:
var document = documentService.get({_id: 'theid'});
document.name = "My new name";
document.$save(function(section) {
//$scope.document.push(section);
});
I'm just trying to add an object to a nested array of objects.
Try this:
documentService.get({_id: 'theid'}, function(document) {
document.sections.push($scope.section);
document.$save();
});

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

Facebook requests 2.0 filter

So I hope someone call help me with this issue as I'm not too sure if its javascript, or if its facebook.
Here's my situation. I upgraded to Requests 2.0 on facebook, which no longer gives me the ability to add an exclude_ids field to the form where users will invite their friends to the App. The purpose of this form is not to just invite friends, but to add friends as something in the App.
In short, I have a list of friends that they have already added, and I want to filter that from the master list of their friends so that when they want to use the form, the friends already added do not show up.
Here is my javascript to get the friends:
<script language="Javascript" type="text/javascript">
var friends_filter = '<?=$myClass->getFiltered());?>';
</script>
Will return something like:
999999999,999999999,999999999,999999999,999999999,999999999,999999999
Which is a list of IDs of the users who they have NOT added that are their friends.
Here is my code for the form:
function addUser() {
FB.ui(
{
method: 'apprequests',
display: 'dialog',
title: 'Add friends',
message: 'Hey, I added you as a user/friend on such-and-such App',
data: 'added',
filters: [{name: 'Non-Added', user_ids: [friends_filter]}],
},
function(response) {
if(response && response.request_ids) {
showLoading('Adding Relatives');
var dataString = 'rids='+response.request_ids;
$.ajax({
type: "GET",
url: server_url+"ajax/add_relative.php",
data: dataString,
success: function(data){
window.location.reload();
}
});
}
}
);
}
If you look at the filters: [{name: 'Non-Added', user_ids: [friends_filter]}], line, that is where I include the list of IDS that I only want to see in the selector. The dialog pops up, but then list those ID's in friends_filter and an error message stating "does not resolve to a valid user ID"
This is where I get confused, if I copy and paste what friends_filter outputs and replace it the friends_filter with the list of IDs, i.e. 999999999,999999999,999999999,999999999, exactly as it appears, it works correctly.
I know this is an exhaustive post and I'm sorry, but I'm at my wits end.
The only thing I could think of is that perhaps my javascript variable friends_filter needs to be converted to some type of some sort?
Any ideas?
i was try this code and it is work good with me
FB.ui(
{
method: 'apprequests',
filters: ['app_non_users'],
message: 'msg here!',
title: 'title for box'
},
function(response) {
alert(response.request_ids);//this is return after send invite
}
);
just if you want filter result with list of user use
filters: [{name: 'Invite friends', user_ids: <?php echo json_encode($users_array);?> }],
After much trial and error, I figured out the solution.
in:
<script language="Javascript" type="text/javascript">
var friends_filter = '<?=$myClass->getFiltered());?>';
</script>
I changed to
<script language="Javascript" type="text/javascript">
var friends_filter = [<?=$myClass->getFiltered());?>];
</script>
By replacing the quotes around the php echo with brackets.
Then I changed:
filters: [{name: 'Non-Added', user_ids: [friends_filter]}],
To:
filters: [{name: 'Non-Added', user_ids: friends_filter}],
If you want to exclude those (of your friends) who added the application, you simply use:
filters: ['app_non_users']

Categories

Resources