How to set CRUD working in Kendo? - javascript

How to set CRUD working in Kendo? Update and read is ok, but create not. This is my code for this part:
create: {
url: function (data) {
return $("#gatewayPath").data("value") + "odata/ods/ProcessProductionPerformanceMovements";
},
dataType: "json",
type: "POST",
beforeSend: function (x) {
var auth = $("#authenticationType").data("value") + " " + $("#authenticationToken").data("value");
x.setRequestHeader("Authorization", auth);
}
},
and in parameterMap I have:
if (operation === "create") {
return '{ "_Key": "' + data._Key +
'", "Comment": "' + data.Comment +
'","MovementType": "' + data.MovementType +
((data.Unit) ? '","_UnitKey": "' + data.Unit._Key: "") +
((data.Material) ? '","_MaterialKey": "' + data.Material._Key: "") +
'","MaterialLotID": "' + data.MaterialLotID +
'","Status": "' + data.Status +
'","Quantity": "' + data.Quantity +
'","Description": "' + data.Description +
'","_UnitKey": "' + data._UnitKey +
'","_ProdPerfHeaderKey": "' + data._ProdPerfHeaderKey +
'","StockType": "' + data.StockType +
'","StockIndicator": "' + data.StockIndicator +
'","SAPStorageLocation": "' + data.SAPStorageLocation +
'"}';
}

There is a create example here on telerik.com.
var dataSource = new kendo.data.DataSource({
transport: {
/* the other CRUD settings are ommitted for brevity */
create: function (e) {
// batch is disabled
// generate appropriate data item ID and save the new items to the original datasource
e.data.my_ID_field_name = 123;
// ...
// on success return the new data items with IDs
e.success(e.data);
// on failure
//e.error("XHR response", "status code", "error message");
}
} });

Related

How to create a DataTable responsive filled from $.Ajax

I am developing an app which displays many information from a web-service query, the data-table fills the information correctly and it displays the style correctly too, but when I try to see the information in a mobile device the Data-table is looking very bad.
I am using $.Ajax method to fill the information.
JavaScript:
$.ajax({
type: 'POST',
url: '/enrollment.asmx/Searcher',
data: JSON.stringify(JsonObj),
contentType: "application/json; utf-8",
dataType: "json",
success: function (data) {
$("#loadingDiv").hide();//Show Loader
var html = " <table id=\"db\" class=\"table-hover dt-responsive nowrap table table-bordered\"><thead><tr><th data-priority='1'>Selection</th><th>City</th><th>Zip</th><th>Address</th><th>State</th><th>ESIID</th><th>Utility</th></tr></thead><tbody>";
for (var i = 0; i < data.d.length; i++) {
html = html + "<tr name='userinformation' onclick=\"rowSelected('" + data.d[i].SEnrollCity + data.d[i].SEnrollZip + data.d[i].SEnrollStreet + "');\" id='" + data.d[i].SEnrollCity + data.d[i].SEnrollZip + data.d[i].SEnrollStreet + "'><td><input type='radio' name='userinformation' value='#'></td></td><td id='" + data.d[i].SEnrollCity + data.d[i].SEnrollZip + data.d[i].SEnrollStreet + "/SEnrollCity'>" + data.d[i].SEnrollCity + "</td><td id='" + data.d[i].SEnrollCity + data.d[i].SEnrollZip + data.d[i].SEnrollStreet + "/SEnrollZip'>" + data.d[i].SEnrollZip + "</td><td id='" + data.d[i].SEnrollCity + data.d[i].SEnrollZip + data.d[i].SEnrollStreet + "/SEnrollStreet'>" + data.d[i].SEnrollStreet + "</td><td id='" + data.d[i].SEnrollCity + data.d[i].SEnrollZip + data.d[i].SEnrollStreet + "/SState'>" + data.d[i].SState + "</td><td id='" + data.d[i].SEnrollCity + data.d[i].SEnrollZip + data.d[i].SEnrollStreet + "/SEsiid'>" + data.d[i].SEsiid + "</td><td id='" + data.d[i].SEnrollCity + data.d[i].SEnrollZip + data.d[i].SEnrollStreet + "/SUtility'>" + data.d[i].SUtility + "</td></tr>";
_vDistributionServiceProviderID = data.d[i].SDistributionServiceProviderID;
_vStateCode = data.d[i].SStateCode;
}
console.log("Dis: " + _vDistributionServiceProviderID);
html = html + "</tbody></table>";
$("#dbResultTable").html(html);//We have the Append here
$("#lblCheck").show();
if ($('#db thead').length > 0) {
var table = $("#db").DataTable();
$(table).remove();
var table = $("#db").DataTable();
table.draw();
}
else {
var table = $("#db").DataTable();
table.draw();
}
$("#submit").show();
$("#lblSelection").show();
$("#lblSelectionInfo").show();
if (data.d.SError == "" || data.d.SError == null) {
//Write an error
}
else {
alert("Error 1");
$("#divResult").html(data.d.SError);
alert(JSON.stringify(data.d.SError));
}
},
error: function (e) {
//alert("Error 2");
alert("The error is: " + JSON.stringify(e));
$("#divResult").html(data.d.SError);
alert(JSON.stringify(data.d.SError));
}
});
Initialize the Data-table.
var table = $("#db").DataTable({
responsive: true,
columnDefs: [
{ responsivePriority: 1, targets: 0 },
{ responsivePriority: 2, targets: -1 }
]
});
Unfortunately in the responsive device it look awful. Could somebody please help me this issue?
Thanks in advance.
Your initial stage of data table
var table = $("#db").DataTable({
responsive: true,
columnDefs: [
{ responsivePriority: 1, targets: 0 },
{ responsivePriority: 2, targets: -1 }
]
});
Get the data using ajax:
$.ajax({
type: 'POST',
url: '/enrollment.asmx/Searcher',
data: JSON.stringify(JsonObj),
success:function(data){
var json=JSON.parse(data);
table.fnClearTable();
table.fnAddData(json);
}
});

execute javascript after for loop

I have a for loop that gets data from lists in subsites to build a html list on the page using an async ajax request, this works, but i wish to order the list after it has been generated to show the list in alphabetical order. I am on a learning curve with javascript so any help is appreciated. I need to run the sortProjects function after the onWebsLoaded function is complete.
function onWebsLoaded(sender, args) {
for (var i = 0; i < this.webs.get_count(); i++)
{
client = "";
var title = this.webs.itemAt(i).get_title();
var desc = this.webs.itemAt(i).get_description();
var url = this.webs.itemAt(i).get_serverRelativeUrl();
id = (title).replace(/\ /g, "");
getProjectProperties(url, title, desc, client, id);
}
}
function sortProjects () {
tinysort('ul#projectstable>li');
}
function getProjectProperties (url, title, desc, client, id) {
$.ajax({
url: url + "/_api/web/lists/getbytitle('Project Properties')/items('1')",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
client = data.d.Title;
$('#projectstable').append("<li id='" + id + "' class='ms-ListItem'><a href='" + url + "'><span id='" + id + "Client' class='ms-ListItem-primaryText'>" + title + "</span><span class='ms-ListItem-secondaryText'>" + client + "</span><span class='ms-ListItem-tertiaryText'>" + desc + "</span></a></li>");
},
error: function () {
$('#projectstable').append("<li id='" + id + "' class='ms-ListItem'><a href='" + url + "'><span id='" + id + "Client' class='ms-ListItem-primaryText'>" + title + "</span><span class='ms-ListItem-secondaryText'>" + client + "</span><span class='ms-ListItem-tertiaryText'>" + desc + "</span></a></li>");
}
});
}
You can amend your logic so that you store an array of the promises returned from the $.ajax() calls. You can then apply() that array to $.when and call sortProjects(). Try this:
function onWebsLoaded(sender, args) {
var requests = [];
for (var i = 0; i < this.webs.get_count(); i++) {
client = "";
var title = this.webs.itemAt(i).get_title();
var desc = this.webs.itemAt(i).get_description();
var url = this.webs.itemAt(i).get_serverRelativeUrl();
id = (title).replace(/\ /g, "");
requests.push(getProjectProperties(url, title, desc, client, id));
}
$.when.apply($, requests).done(sortProjects);
}
function sortProjects () {
tinysort('ul#projectstable>li');
}
function getProjectProperties (url, title, desc, client, id) {
// note 'return' below
return $.ajax({
url: url + "/_api/web/lists/getbytitle('Project Properties')/items('1')",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
client = data.d.Title;
$('#projectstable').append("<li id='" + id + "' class='ms-ListItem'><a href='" + url + "'><span id='" + id + "Client' class='ms-ListItem-primaryText'>" + title + "</span><span class='ms-ListItem-secondaryText'>" + client + "</span><span class='ms-ListItem-tertiaryText'>" + desc + "</span></a></li>");
},
error: function () {
$('#projectstable').append("<li id='" + id + "' class='ms-ListItem'><a href='" + url + "'><span id='" + id + "Client' class='ms-ListItem-primaryText'>" + title + "</span><span class='ms-ListItem-secondaryText'>" + client + "</span><span class='ms-ListItem-tertiaryText'>" + desc + "</span></a></li>");
}
});
}

400 bad request on twitter oauth request token

I am trying to send a POST request to https://api.twitter.com/oauth/request_token. The response is 400 Bad Request with no info. Here is my code:
onTwitterRegisterClick: function() {
var callbackURL = 'http://test.loc:1841/',
consumerKey = 'm59nSEhyF3Zp4gVdpDzq6CIPp',
consumerSecret = 'Wou436sq4LUXwO1ajE2egdMdAfV9LtPLkG4JlCF4Yi5YpcrnTF',
requestTokenURL = 'https://api.twitter.com/oauth/request_token';
var time = new Date().valueOf().toString(),
oauth_nonce = makeRandomString(32);
var paramsForSignature = [
encodeURIComponent('oauth_callback') + '=' + encodeURIComponent(callbackURL),
encodeURIComponent('oauth_consumer_key') + '=' + encodeURIComponent(consumerKey),
encodeURIComponent('oauth_nonce') + '=' + encodeURIComponent(oauth_nonce),
encodeURIComponent('oauth_signature_method') + '=' + encodeURIComponent('HMAC-SHA1'),
encodeURIComponent('oauth_timestamp') + '=' + encodeURIComponent(time),
encodeURIComponent('oauth_version') + '=' + encodeURIComponent('1.0')
];
var paramsForSignatureStr = paramsForSignature.join('&');
var signatureBaseString = 'POST&' + encodeURIComponent(requestTokenURL) + '&' + encodeURIComponent(paramsForSignatureStr);
//alert(signatureBaseString);
var signature = btoa(CryptoJS.HmacSHA1(signatureBaseString, consumerSecret + '&'));
//var signature = prompt('hmac-sha1 of signatureBaseString=' + CryptoJS.HmacSHA1(signatureBaseString, consumerSecret + '&'));
//alert(signature);
Ext.Ajax.request({
method: 'POST',
url: requestTokenURL,
async: false,
headers:{
Authorization: 'OAuth oauth_callback="' + encodeURIComponent(callbackURL) + '", ' +
'oauth_consumer_key="' + consumerKey + '", ' +
'oauth_nonce="' + oauth_nonce + '", ' +
'oauth_signature="' + encodeURIComponent(signature) + '", ' +
'oauth_signature_method="HMAC-SHA1", ' +
'oauth_timestamp="' + time + '", ' +
'oauth_version="1.0"'
},
success: function(response, opts) {
alert(response.responseText);
},
failure: function (response, opts) {
alert(response.responseText);
}
})
}
I read the official guide a few times. What am I doing wrong?
I only noticed the value of the variable "signature" is like "YTg5ZmI2ZmEwMWU4MDkzMjlkZmEzMmVmMmVmYzgxMjlmZTJlNDdlZQ==" and is not like "tnnArxj06cWHq44gCs1OSKk/jLY=" (as in the official guide) because the function btoa() work with String and with not Integer.
try changing the async: false to true

Javascript: TypeError: $.chat is not a function

I have the following javascript code snippet, which defines the chat funtion, it should create a chat in a Sharepoint site.
However I get "TypeError: $.chat is not a function", does anyone know how I could fix this?
Edit: I get this error when I try calling this function:
$(document).ready(function() {
$.chat({
listguid: "{3A076D9D-362B-455A-8F19-831F6716B6F0}"
});
});
(function($) {
$.chat = function(options) {
$.chat.settings = $.extend({
listguid: '0',
divid: 'jQueryChatBox',
savecaption: 'Send',
clearcaption: 'Clear',
messagecolumn: 'Message'
},
options || {});
ChatBox = "<input type='text' size='50' id='" + $.chat.settings.divid + "textbox' name='" + $.chat.settings.divid + "textbox'/><br/><input type='submit' id='" + $.chat.settings.divid + "submitbutton' value='" + $.chat.settings.savecaption + "'/><input type='reset' value='" + $.chat.settings.clearcaption + "'/>";
$('#' + $.chat.settings.divid).html(ChatBox);
$('#' + $.chat.settings.divid + 'submitbutton').click(
function() {
if ($.trim($('#' + $.chat.settings.divid + 'textbox').val()) == "")
return false;
var soapEnv = "<?xml version=\"1.0\" encoding=\"utf-8\"?> <soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> <soap:Body> <UpdateListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\"> <listName>" + $.chat.settings.listguid + "</listName> <updates> <Batch OnError=\"Continue\"> <Method ID=\"1\" Cmd=\"New\"> <Field Name=\"" + $.chat.settings.messagecolumn + "\">" + $('#' + $.chat.settings.divid + 'textbox').val() + "</Field> </Method> </Batch> </updates> </UpdateListItems> </soap:Body> </soap:Envelope>";
$.ajax({
url: L_Menu_BaseUrl + "/_vti_bin/lists.asmx",
beforeSend: function(xhr) {
xhr.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems")
},
type: "POST",
dataType: "xml",
data: soapEnv,
contentType: "text/xml; charset=utf-8"
});
$('#' + $.chat.settings.divid + 'textbox').val('');
return false;
})
}
})
(jQuery);
$(document).ready(function() {
$.livelistdata({
prompt: false,
interval: 100,
opacity: '0.5'
})
});

Recieving JSON from AJAX Call with MongoDB

I am getting a users details from a MongoDB database like this:
$user=$collection->findOne(array('_id' => new MongoId($_SESSION['user']['userid'])));
if (!empty($user)){
json_encode($user);
print_r($user);
}
I can get an entire JSON array from the AJAX but not individual elements - I get undefined:
$.ajax({
type: 'json',
url: '../scripts/getUser.php',
method: 'GET',
success: function(msg){
alert(msg);
}
});
The actual JSON is structured like this:
username: john
password: hello
email: me#mailserver.com
I'm stuck.
you returning array object from getUser.php but you display it as a normal variable
$.ajax({
type: 'json',
url: '../scripts/getUser.php',
method: 'GET',
success: function(msg){
$.each(msg,function(key,value){
alert(value.id);
});
}
});
i guess this will work..
You need to get the return value
$encoded = json_encode($user);
print_r($encoded);
The method you are using does not encode in place. It returns a left side value.
success: function (response)
{
if(response != 'error')
{
//parse into JSON
var jsonObj = JSON.parse(response);
var HTML = '';
//extract single value using each
$.each(jsonObj, function(key, val) {
HTML += '<tr><td>' + val.id + '</td><td>' + val.first_name + '</td><td>' + val.last_name + '</td><td>' + val.gender + '</td>'
+'<td>' + dt + '</td><td>' + val.phone + '</td><td>' + val.mobile + '</td><td>' + val.email + '</td>'
+'<td>' + val.address + ',' + val.city + ',' + val.state + '</td><td>' + val.country + '</td>'
+'<td>' + val.zip + '</td><td>' + val.hobbies + '</td><td>' + 'INR ' +val.salary + '</td><td>' + val.countryCode + '</td>'
+'<td>' + val.username + '</td><td>' + val.pwd + '</td></tr>';
});

Categories

Resources