having some issues with my save function on knockout. I was following the tutorial on the Knockout site http://jsfiddle.net/rniemeyer/bGsRH/. WHen I implement the code to my site I get an error an error 400 Bad request stating that my JSON data is invalid. After debugging a bit more I see that it`s returning [object, object] instead of my modified JSON data.
To give a little context, I basically have a table with my list of data and each row has their edit button. Upon clicking the edit button it opens a modal and shows the data of the selected item. The issue occurs when I try to modify and then save the data.
Here is my javascript code I have so far, would anyone know what im missing?:
<script type="text/javascript">
function EmployeeModal() {
var self = this;
self.Employees = ko.observableArray([]);
//Start of select/edit functions
//This codes allows to pass selected data to the hidden modal
self.currentEmployee = ko.observable(null);
self.showEmployee = function(vm){
self.currentEmployee(vm);
$('#myModal').modal('show');
};
//END of select/edit functions
//Start of the save function
self.save = function() {
var New_Incident_URL = '../../../../_vti_bin/listData.svc/GDI_PROD_Incidents';
var UPDATE_Incident_URL = '../../../../_vti_bin/listData.svc/GDI_PROD_Incidents('+ encodeURIComponent($('#Incident_ID').val())+')';
var createIncidentUrl = $('#Incident_ID').val() != '' ? UPDATE_Incident_URL : New_Incident_URL;
var CREATE_Headers = {"accept": "application/json;odata=verbose"};
var UPDATE_Headers = {"accept" : "application/json;odata=verbose","X-HTTP-Method":"MERGE","If-Match":"*"};
var headertype = $('#Incident_ID').val() != '' ? UPDATE_Headers : CREATE_Headers;
$.ajax(createIncidentUrl, {
data: {
json: ko.toJSON({
Description: this.Description,
Incident: this.Incident
})
},
type: "POST",
processData: false,
contentType: "application/json;odata=verbose",
headers: headertype,
success: function(result) {
alert(ko.toJSON(result));
$('#myModal').modal('hide');
}
});
};
//Start - Go get data from Sharepoint.
$.getJSON("../../../../_vti_bin/listData.svc/GDI_PROD_Incidents?$filter=ÉtatValue%20ne%20%27Fermé%27&$orderby=PrioritéValue desc",
function (data) {
if (data.d.results) {
self.Employees(ko.toJS(data.d.results));
}
}
);
//END - Go get data from Sharepoint.
}
$(document).ready(function () {
ko.applyBindings(new EmployeeModal());
});
</script>
EDIT:
Here is an example of my data from the server.
[{
ID: "123",
Description: "The server x is unavailable",
Incident: "1234"
}, {
ID: "124",
Description: "The router located downtown is down",
Incident: "12345"
}, {
ID: "125",
Description: "Fiber optic cable downtown is flapping",
Incident: "123456"
}, {
ID: "126",
Description: "Network unvailable at the beaver site",
Incident: "1234567",
}];
Related
I have an application that sends a message through JSON via ajax. This is the JS object:
var message = {
"message_by": colmn[0].innerHTML,
"message_date": new Date(),
"message_recipients": [
{
"phone_number": colmn[1].innerHTML,
"recipient_name": colmn[2].innerHTML
}
],
"message_text": colmn[3].innerHTML,
"subscriber_name": "John Doe"
};
Which is then posted like so:
var url = "http://url/api/sendMessage";
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(message),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
console.log(data);
console.log(status);
console.log(jqXHR);
//alert("success..." + data);
alert("Success. Message sent.");
},
error: function (xhr) {
//alert(xhr.responseText);
alert("Error. Try again.");
}
});
The stringified message could look like this for example:
var message = {
"message_by": "Brian",
"message_date": new Date(),
"message_recipients": [{
"phone_number": "0700111222",
"recipient_name": "Timothy"
}, {
"phone_number": "0800222111",
"recipient_name": "Winnie"
}],
"message_text": "Hello! You are invited for a cocktail at our auditorium. ",
"subscriber_name": "John Doe"
}
Now to the problem. The messages are posted to the api just fine but recently noticed some messages failing and discovered the failed messages had 100 message recipients or more. It works fine up to 99. I asked a colleague and he said there weren't any limit restrictions set on the api.
Is there a way I could limit the object size to 99 and push the remainder to a new object but still have it as part of the same ajax post? Is there any other creative way around this?
There is no such limit.
If you want to restrict your message recipients to 99 you can do as follows
validateMessege(message){
var length = message.length;
var messegeRep = message.message_recipients.slice()
for(var i = 0; i < length; i+=99){
message.message_recipients = messageRep.slice(i, i+99)
// Your post request here
}
}
I am using Trello API to create a card. This works fine but while the script runs it prints a ID variable of the newly created card to the console. I'd like to take this variable and pass it back to my python code. Is this possible? I am using Jinja2 to pass variables from Python to HTML, can I use this here?
This is the output to the console in Chrome, I want to grab the first ID variable so I can work with it in my Python code.
{
"id": "5a46fa28620367df83fe08f7",
"badges": {
"votes": 0,
"attachmentsByType": {
"trello": {
"board": 0,
"card": 0
}
},
"viewingMemberVoted": false,
"subscribed": false,
"fogbugz": "",
"checkItems": 0,
"checkItemsChecked": 0,
Here is my Javascript:
var authenticationSuccess = function() {
console.log('Successful authentication');
};
var authenticationFailure = function() {
console.log('Failed authentication');
};
window.Trello.authorize({
type: 'popup',
name: 'Work Requests App',
scope: {
read: 'true',
write: 'true' },
expiration: 'never',
success: authenticationSuccess,
error: authenticationFailure
});
//console.log(trelloTitle);
//console.log(trelloContent);
var myList = '5a3ec86f7920a6e66b28e4bc';
var creationSuccess = function (data) {
console.log('Card created successfully.');
console.log(JSON.stringify(data, null, 2));
};
//var data = $('#resultsdata').data();
//console.log(trelloId);
var newCard = {
name: trelloTitle,
desc: trelloContent,
// Place this card at the top of our list
idList: myList,
idMembers: trelloId,
pos: 'top'
};
window.Trello.post('/cards/', newCard, creationSuccess);
EDIT: I am now using this AJAX method:
var creationSuccess = function (data) {
console.log('Card created successfully.');
console.log(JSON.stringify(data, null, 2));
var url = "/ajaxtest";
$.post(url, {card_id: data.id});
};
I am having difficulty passing card_id into my python method:
class AjaxTest(webapp2.RequestHandler):
def post(self):
data = card_id
I know this is wrong, can anyone help?
Here's the complete answer:
var creationSuccess = function (data) {
console.log('Card created successfully.');
var http = new XMLHttpRequest();
var url = "URL to your server (where you want to send the data)";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send("card_id=" + data.id);
};
This will send the card id as card_id to your server (to the URL you specified) through an AJAX call.
This is assuming that you're only using pure Javascript. If you're using jQuery, then making an AJAX call would be much easier. like:
var creationSuccess = function (data) {
console.log('Card created successfully.');
var url = "URL to your server";
$.post(url, {card_id: data.id});
};
Edit: As for the server code, you could now receive card_id like this:
class AjaxTest(webapp2.RequestHandler):
def post(self):
data = self.request.get('card_id')
Hope that helps.
I'm a newbie when it comes to javascript. I'm using the jsGrid plugin to display a grid in the browser. The grid column headers will have the values "Request Status" and "Request Id". I can make it work with static data.
(function() {
var adminDashboardController = {
loadData: function(filter) {
return $.grep(this.requests, function(request) {
return (!filter.Status || request.Status === filter.Status)
&& (!filter.RequestId || request.RequestId.indexOf(filter.RequestId) > -1)
});
},
insertItem: function(insertingReq) {
},
updateItem: function(updatingReq) {
},
deleteItem: function(deletingReq) {
}
};
window.adminDashboardController = adminDashboardController;
adminDashboardController.status = [
{ Name: ""},
{ Name: "Requested"},
{ Name: "Declined"}
];
//This is the static data
adminDashboardController.requests = [
{ "Status": "Requested", "RequestId": "1"},
{ "Status": "Declined", "RequestId": "2"}
];
}());
But when it comes to fetching the data from an ajax call (using a json file for testing as the data source), the data no longer gets filtered when I choose "Requested" or "Declined" as the filtering criterion. I'm using the format mentioned in the documentation like this -
(function() {
var adminDashboardController = {
loadData: function (filter) {
return $.ajax({
type: "GET",
dataType: "json",
url: "/json/db514.json",
data: filter
});
},
insertItem: function(insertingReq) {
},
updateItem: function(updatingReq) {
},
deleteItem: function(deletingReq) {
}
};
adminDashboardController.status = [
{ Name: ""},
{ Name: "Requested"},
{ Name: "Declined"}
];
}());
I can't understand how to implement the filtering in this case!
The reason is that filtering should be implemented in the code.
In general it can be done:
on the client (just as in your first sample)
on backend, then you have to pass the filter to your endpoint, which will do filtering and return data.
combined approach (partially on backend and after on the client)
In your case you could either add an endpoint on backend, which will load json and filter data, or still do filtering on client-side, for example:
loadData: function (filter) {
return $.ajax({
type: "GET",
dataType: "json",
url: "/json/db514.json"
}).then(function(requests) {
return $.grep(requests, function(request) {
return (!filter.Status || request.Status === filter.Status)
&& (!filter.RequestId || request.RequestId.indexOf(filter.RequestId) > -1)
});
});
}
Checkout this issue on GtiHub https://github.com/tabalinas/jsgrid/issues/32.
I am making a plugin for wordpress. The plugin will add a tinymce on the edit post, and it will send the post_id to the database to do some identification later.
In my case, I am writing a javascript, which directory in wordpress\wp-content\plugins\facebook-api\js\shortcode-tinymce-button.js. And now I have no idea how I can get the post_Id in javascript.
Here is what I am doing:
user click the OK button will send the post_Id and the text box value to the database.
Here is my code:
(function() {
tinymce.PluginManager.add('facebook_api_tinymce', function( editor, url ) {
editor.addButton( 'facebook_api_tinymce',
{
title: 'Set friend condition',
text: 'Condition',
type: 'menubutton',
menu:
[
{
text: 'Friend',
onclick: function() {
editor.windowManager.open( {
body:[
{
type: 'textbox',
name: 'textboxName',
label: 'Set friend',
value: '20'
}
],onsubmit: function( e ) {
var $hi = "php echo get_the_ID();";
alert($hi);
$no_friend_e = parseInt(e.data.textboxName);
//Pass the value the PHP file, which is doing the database update.
jQuery.ajax({
url: 'http://localhost:8080/wordpress/wp-content/plugins/facebook-api/js/databaseConnection.php',
type: 'POST',
data: {functionname: 'updateDatabase', post_id: '1', no_friend: $no_friend_e},
error:function(data){ //When Can't call the PHP function
alert("failed");
console.log(data);
},
success: function(data) { //update data successful
alert("success");
console.log(data); // Inspect this in your console
}
});
}
});
function get_post_content(id){ //Didn't use
return document.getElementById("post-"+id).innerHTML;
}//you should probably use textContent/innerText but I am not going to get into that here
}
}
]
});
});
Thanks,
I have a div which I would like to fill with a jsTree:
I get the "Loading" icon where the tree is meant to display, however, there would seem to be a javascript error, even though one is not thrown.
I load my folder structure from an AJAX Request as follows. The Documents.aspx/GetFolders Web Method returns a List containing FolderId, ParentId & Folder Name. I have debugged the web method and it is passing the correct results to the jsTree "data" function.
$.ajax({
type: "POST",
url: 'Documents.aspx/GetFolders',
contentType: "application/json; charset=utf-8",
success: function (data) {
data = data.d;
$("#tree").jstree({
"core": {
"themes": {
"responsive": true
},
"data": function () {
var items = [];
items.push({ 'id': "jstree_0", 'parent': "#", 'text': "Documents" });
$(data).each(function () {
items.push({ 'id': "jstree_" + this.DocumentFolderId, 'parent': "jstree_" + this.ParentId, 'text': "" + this.Name });
});
return items;
}
},
"types": {
"default": {
"icon": "fa fa-folder icon-lg"
},
},
"plugins": ["contextmenu", "dnd", "state", "types"]
});
},
error: function () {
toastr.error('Error', 'Failed to load folders<span class=\"errorText\"><br/>There was a fatal error. Please contact support</span>');
}
});
After debugging the code, it seems the data is being retrieved correctly and is returning the object array as intended.
Is there are any problem with the above (or is there somewhere else I should be looking)? Or is there a better method of achieving its intended purpose?
I think I have finally found the answer! :)
"core": {
"themes": {
"responsive": true
},
"data": {
type: "POST",
url: "Documents.aspx/GetFolders",
contentType: "application/json; charset=utf-8",
success: function (data) {
data.d;
$(data).each(function () {
return { "id": this.id };
});
}
},
}
Server side, you need to return the data in the array format required, i.e:
[{id = "node0", parent = "#", text = "Documents"},
{id = "node1", parent = "node0", text = "Public"},
{id = "node2", parent = "node0", text = "Restricted"}]
Just in case anyone has the "loading..." issue, this format fixed it for me when returning data.
[{"id":"node0", "parent":"#", "text":"Documents"},
{"id":"node1", "parent":"node0", "text":"Public"},
{"id":"node2", "parent":"node0", "text":"Public"}]