CouchDB document attachments via html form and jquery - javascript

I'm trying to create web form that, when submitted will create a couchdb document and add attachment(s) to the doc. I've seen from tutorials/other forums that it's necessary to do this with a two stage process (as futon does). I can get the document to upload, but can't seem to get the attachment to upload. I've tried a number of ways, currently I do something like:
html file with:
<!DOCTYPE HTML>
<html>
<head>
<title>Document submission</title>
<style type="TEXT/CSS" media="all">
</style>
</head>
<body>
<table>
<form id="form" name="form" action="">
<tr>
<td>Field</td>
<td><input type="text" required="required" name="field">
<span id="required">*</span></td>
</tr><tr>
</tr><tr>
<td></td><td><button type="button" id="submit">Select Attachment</button><td>
</tr>
</form>
</table>
</body>
<script src="/_utils/script/json2.js"></script>
<script src="/_utils/script/jquery.js"></script>
<script src="/_utils/script/jquery.couch.js"></script>
<script src="/_utils/script/jquery.form.js"></script>
<script src="/_utils/script/jquery.dialog.js"></script>
<script type="text/javascript" src="basic.js"></script>
</html>
and then a file called basic.js with:
function create_document(){
var db_name = 'uploader';
var db = $.couch.db(db_name);
var data={}
data['fname']=document.form.field.value;
db.saveDoc(data, {
success: function (data) {
add_attachment(db,data);
},
error: function () {
alert("Cannot save the thread.");
}
});
}
function add_attachment(db,data){
var docID = data.id;
var dbName = db.name;
var form = $("#upload-form");
$.showDialog("dialogue.html", {
load: function(elem) {
$("input[name='_rev']", elem).val(data._rev);
},
submit: function(data, callback) {
if (!data._attachments || data._attachments.length == 0) {
callback({_attachments: "Please select a file to upload."});
return;
}
var form = $("#upload-form");
form.find("#progress").css("visibility", "visible");
form.ajaxSubmit({
url: db.uri + $.couch.encodeDocId(docID),
success: function(resp) {
form.find("#progress").css("visibility", "hidden");
location.href = "?" + encodeURIComponent(dbName) +
"/" + $.couch.encodeDocId(docID);
}
});
}
});
}
$(document).ready(function() {
$("button#submit").click(function(event) {
create_document();
});
});
This javascript is pretty much taken from the futon.browse.js uploadAttachment segment. The dialogue.html file is also just straight copy of couchdb's www/dialog/_upload_attachment.html. All files (the main html, basic.js and dialogue.html) are then uploaded to a CouchDB design document (in a database called uploader).
The document is created fine, but no matter what I do, the attachment is never saved. The various methods I've tried either result in an error about multi-part forms or, in this case, no discernible error at all.
Does anyone know what I'm doing wrong?

I inherited this code, so I don't know if it's optimal or not. But it does work:
jQuery.fn.sendForm = function(itemID, itemType) {
// Get all of the values from the form fields
var itemTitle = $('.settingsForm input#title').val(),
itemAuthor = $('.settingsForm input#author').val(),
itemDescription = $('.settingsForm textarea#description').val(),
itemDate = $('.settingsForm input#date').val(),
itemRev = $('.settingsForm input#_rev').val(),
itemDelete = $('.settingsForm input#delete:checked').val(),
itemType = $('.settingsForm select').val(),
itemFilename = $('.settingsForm input:file').val();
// Check for new uploaded file
if (itemFilename == undefined || itemFilename == ""){
$('.settingsForm input:file').remove();
itemFilename = "";
}
else {
itemFilename = itemFilename.replace(/^C:\\fakepath\\/i, '');
}
// If no new file, then fall back on the old filename
if (!itemFilename || itemFilename.length == 0) {
itemFilename = $('.settingsForm input#filename').val();
}
// Force to add a title (the only required field)
if (!itemTitle || itemTitle.length == 0) {
alert(libLang.addTitle); // Get text for language
return;
}
// Check if size of db is above the limit
dbSize = maxDBSize;
$.ajax({
url: "/"+ homeURL,
dataType: 'json',
async: false,
success: function(dbInfo){
dbSize = dbInfo.data_size;
}
});
if (itemDelete != 'Yes' && dbSize >= maxDBSize){
alert(libLang.noSpace);
return;
}
if (itemDelete != 'Yes'){
if (itemID != 'add'){
// Update existing record
$(this).ajaxSubmit({
url: "/"+ homeURL +"/"+ itemID,
data: {"filename":itemFilename},
success: function(resp) {
$.getJSON("/"+ homeURL +"/"+ itemID, function(revData) {
itemRev = revData._rev;
itemAttachment = revData._attachments;
user = revData.user;
if (!revData._attachments || revData._attachments.length == 0) {
$.couch.db(homeURL).saveDoc({
"_id": itemID,
"_rev": itemRev,
"filename":itemFilename,
"title":itemTitle,
"author":itemAuthor,
"type":itemType,
"description":itemDescription,
"date":itemDate,
"user":user
}, {
success: function() {
alert(libLang.saved); // Get text for language
window.location.replace("index.html");
}
});
}
else {
$.couch.db(homeURL).saveDoc({
"_id": itemID,
"_rev": itemRev,
"filename":itemFilename,
"title":itemTitle,
"author":itemAuthor,
"type":itemType,
"description":itemDescription,
"date":itemDate,
"user":user,
"_attachments":itemAttachment
}, {
success: function() {
alert(libLang.saved); // Get text for language
window.location.replace("index.html");
}
});
};
});
}
});
}
else {
// Add new record
uniqueID = $.couch.newUUID();
itemID = itemTitle.replace(/[\s]/g,'_');
itemID = homeUser +'-'+ itemType.charAt(0).toUpperCase() + itemType.slice(1) +'-'+ encodeURI(itemID) +'-'+ uniqueID;
itemID = itemID.replace(/[^a-z 0-9 _ -]+/gi,'');
$('form .settingsForm').attr({"action":"/"+ homeURL +"/"+ itemID});
// Save information
$.couch.db(homeURL).saveDoc({
"_id": itemID,
"filename":itemFilename,
"title":itemTitle,
"author":itemAuthor,
"type":itemType,
"description":itemDescription,
"date":itemDate,
"user":homeUser
}, {
success: function(){
// Get saved info, then add attachment to item
$.getJSON("/"+ homeURL +"/"+ itemID, function(revData) {
$('.settingsForm input#_rev').val(revData._rev);
var data = {};
$.each($("form :input").serializeArray(), function(i, field) {
data[field.name] = field.value;
});
$("form :file").each(function() {
data[this.name] = this.value.replace(/^C:\\fakepath\\/g, ''); // file inputs need special handling
});
itemFilename = data._attachments;
$('form.settingsForm').ajaxSubmit({
url: "/"+ homeURL +"/"+ itemID,
success: function(resp) {
$.getJSON("/"+ homeURL +"/"+ itemID, function(saveData) {
itemRev = saveData._rev;
itemAttachment = saveData._attachments;
// Resave all information
$.couch.db(homeURL).saveDoc({
"_id": itemID,
"_rev": itemRev,
"filename":itemFilename,
"title":itemTitle,
"author":itemAuthor,
"type":itemType,
"description":itemDescription,
"date":itemDate,
"user":homeUser,
"_attachments":itemAttachment
}, {
success: function() {
alert(libLang.saved); // Get text for language
window.location.replace("index.html");
}
});
});
}
});
});
}
});
};
} else {
// Delete the item from the library
$.couch.db(homeURL).removeDoc({'_id': itemID, "_rev": itemRev});
window.location.replace("index.html");
}
};

Related

A script for upadate textbox's value in asp.net mvc didn' work

I want to update textbox's value(that contains cookie's value) using Ajax in asp.net MVC5 . I'm very new in JavaScript and I wrote these codes , but my code didn't work . I didn't get any error but it's not working. I wrote JavaScript in foreign file 'UpdateTxtBox.js' and I added <script src="~/Scripts/UpdateTxtBox.js"></script> to Layout .
Could anyone tell me what's the problem ?
$(function () {
$("textCountProduct").change(function () {
var count = $(this).val();
var id = $(this).attr("productid");
$.ajax({
url: "/Goods/AddToCart",
data: { Id: id, Count: count },
type: "Post",
dataType: "Json",
success: function (result) {
if (result.Success) {
alert(result.Html);
$("#CartItems").html(result.Html);
}
eval(result.Script);
},
error: function () {
alert("error....");
}
});
});
});
a part of Basket.cshtml
#using (Html.BeginForm("AddToCart", "Goods", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.TextBoxFor(modelItem => item.Count, new { #class="text textCountProduct" , style="width:40px;" , productid=item.GoodDetails.DetailsGoodID})
}
Good controller
public ActionResult AddToCart (int Id , int Count)
{
try
{
if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
{
//Edit cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), (Convert.ToInt32(Request.Cookies["NishtmanCart_" + Id.ToString()].Value) + 1).ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Set(cookie);
}
else
{
//Add new cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), Count.ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
}
List<HttpCookie> lst = new List<HttpCookie>();
for (int i = 0; i < Request.Cookies.Count; i++ )
{
lst.Add(Request.Cookies[i]);
}
bool isGet = Request.HttpMethod == "GET";
int CartCount = lst.Where(p => p.Name.StartsWith("NishtmanCart_") && p.HttpOnly != isGet).Count();
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("Good added successfully", MessageType.Success).Script,
//Script = "alert('Good added successfully');",
Html = "cart items (" + CartCount.ToString() + ")"
}
);
}
Update post :
I added [HttpPost] to controller action result and add some alert to javascript
$(function () {
alert("aleeeert");
$(".textCountProduct").change(function () {
var count = $(this).val();
var id = $(this).attr("productid");
alert(count);
alert(id);
$.ajax({
url: "/Goods/AddToCart",
data: { Id: id, Count: count },
type: "Post",
dataType: "Json",
success: function (result) {
if (result.Success) {
alert(result.Html);
$("#CartItems").html(result.Html);
}
eval(result.Script);
},
error: function () {
alert("error....");
}
});
});
});
it's working fine but when I refresh page , data didn't saved
Since you have specified textCountProduct as CSS class, you need to prefix it with . to use Class Selector (“.class”), As of now its looking for Element textCountProduct which obviously doesn't exists.
Use
$(".textCountProduct").change(
You have made mistake here $("textCountProduct") use . as selector.
It should be $(".textCountProduct")
and
Check path of your script included
<script src="~/Scripts/UpdateTxtBox.js"></script>

HTML table not updating, after pushing new item to knockout observableArray

I am having trouble updating my HTML UI.
When the document load and calls "getAllProducts()", the HTML UI displays all my items and with the right css class for 'styleStatusCss', and the right 'displayName', the problem is that when I try to update my observableArray with a newly updated product (product name or status has changed), the html UI does not update and remains the same
So here is a quick list of what is happening:
getUpdatedProducts() is called every 25 sec, and returns, any product
that has been updated
I check how many products my observable array has: appVM.itemList.length and it does have 100 (as expected!), I also check that the json product that has been sent back has some modified data, and indeed it has changed!
I then create the javascrip obj MyProduct using that product json object
Now I add my newly created javascript obj MyProduct to the observablearray: appVM.itemList.push(newUpdatedProduct);
And finally I check how many items my observablearray has, after doing the push, (and since I cannot see any changes on the HTML UI), and appVM.itemList.length now says 101 !!! How can that be? the HTML UI still displays the data as it was after the initial load
Please see below most of the code
HTML
<table >
<tbody data-bind="foreach: itemList">
<tr>
<td>
<div data-bind="css: styleStatusCss"></div>
</td>
<td>
<div data-bind="text: displayName"></div>
</td>
</tr>
</tbody></table>
And here is the javascript:
<script type="text/javascript">
var appVM;
var initializeItems = false;
$.ajaxSetup({
// Disable caching of AJAX responses
cache: false
});
$(document).ready(function () {
getAllProducts();
});
setInterval(function () {
if (initializeItems) {
getUpdatedProducts();
}
}, 25000);
function getAllProducts() {
var url = '#Url.Action("_AllProducts", "Home")';
$.ajax({
url: url,
type: 'GET',
dataType: 'JSON',
})
.success(function (result) {
initializeItems = true;
appVM = new AppViewModel();
var mappedProducts = ko.utils.arrayMap(result.ItemList, function (item) {
var con = new MyProduct(item);
return con;
});
appVM.itemList = mappedProducts;
ko.applyBindings(appVM);
})
.error(function (xhr, status, error) {
alert("FATAL ERROR");
})
}
function getUpdatedProducts() {
var url = '#Url.Action("_UpdateProducts", "Home")';
$.ajax({
url: url,
type: 'GET',
dataType: 'JSON',
})
.success(function (result) {
if (result.HasNewData) {
alert("we have some data");
alert("START COUNT: " + appVM.itemList.length); //this shows all my 100 products -> START COUNT: 100
alert("Number of new items: " + result.ItemList.length); // i only get one product back for easy debugging
for (index = 0; index < result.ItemList.length; ++index) {
var updatedProdJson = result.ItemList[index]; //get the json for the product
alert("New prod json: " + objToString(updatedProdJson)); //just for debugging print out in a readable format
var newUpdatedProduct = new MyProduct(updatedProdJson);//create our MyProduct object (which has all properties as observable)
appVM.itemList.push(newUpdatedProduct); //add our new MyProduct to the list
alert("FINAL COUNT: " + appVM.itemList.length); // --> FINAL COUNT: 101
}
}
})
.error(function (xhr, status, error) {
alert("Error: " + status);
})
}
function AppViewModel() {
var self = this; //so it references the viewModel object
self.itemList = ko.observableArray([]);
self.doAlert = function () {
alert("HERE");
}
}
function MyProduct(data) {
//alert("DATA: " + objToString(data));
this.Id = ko.observable( data.Id);
this.Name = ko.observable(data.Name);
this.status = ko.observable(data.Status);
this.displayName = ko.computed(function () {
var fullnmae = this.Id() + " " + this.Name();
return fullnmae;
}, this);
this.styleStatusCss = ko.computed(function () {
var pStatus = 'divstatusnone';
if (this.status() === 'H')
pStatus = 'divlowstatus';
if (this.status() === 'D')
pStatus = 'divhighstatus';
return pStatus;
},this);
}
function objToString (obj) {
var str = '';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str += p + '::' + obj[p] + '\n';
}
}
return str;
}
Hope somebody can tell me where i went wrong.
Many thanks,
in getAllProducts, you're assigning the results to itemList, losing your observable array:
appVM.itemList = mappedProducts;
you need to do this instead:
appVM.itemList(mappedProducts);

CRM 2011: javascript webresource linked to html page is only loaded for a few seconds in IE11

acm_/membership_generator_html.htm code:
<!DOCTYPE html>
<html>
<head>
<title>lidmaatschapgenerator</title>
<script src="../ClientGlobalContext.js.aspx"></script>
<script type="text/javascript" src="Scripts/jquery_1.11.1.js"></script>
<script type="text/javascript" src="Scripts/membership_generation_js.js"></script>
<link type="text/css" rel="stylesheet" href="Styles/membership_css.css" />
</head>
<body>
<div id="container">
<div class="ms-crm-Dialog-Header">
<div class="ms-crm-Dialog-Header-Title" id="DlgHdTitle">Lidmaatschappen aanmaken</div>
<div class="ms-crm-Dialog-Header-Desc" id="DlgHdDesc">Maak de persoonlijke lidmaatschappen aan van dit bedrijfslidmaatschap.</div>
</div>
<div id="buttons">
<input type="button" class="ms-crm-Button" id="btnGenerateControls" value="Haal contacten op" />
<input type="button" class="ms-crm-Button" id="btnCreateMemberships" value="Maak lidmaatschappen aan" />
</div>
<div id="ProgressContainer">
<progress id="barProgress" value="0">
<label id="ProgressReplacer"></label>
</progress>
</div>
<div id="divCreated"></div>
<div id="ContactList">
<div class="ms-crm-FieldLabel-LeftAlign">
<label>Contacten</label>
</div>
</div>
</div>
</body>
</html>
Scripts/membership_generation_js.js code:
//CRM entities and records
debugger;
var ODataPath;
var serverUrl;
var EntityId;
var accountId;
var AccountPersonalMembershipList = [];
var AccountContactsList = [];
var CompanyMembershipType = {};
var CompanyMembershipTypeId;
//html controls
var btnCreateMemberships;
var divCreated;
var btnGenerateControls;
var progressBarControl;
var progressBarReplacer;
//binding
var membershipCount = 0;
var MembershipsCreated = false;
var CheckedBoxesCount = 0;
var ProgressCount = 0;
$(document).ready(function () {
getDataParam();
//get context, serverURL and relevant IDs
var context = GetGlobalContext();
serverUrl = context.getServerUrl();
//the CRM 2013 string ends with a slash, we need to trim this;
serverUrl = serverUrl.replace(/\/$/, "");
ODataPath = serverUrl + "/XrmServices/2011/OrganizationData.svc";
//use JQuery to get the relevant controls
btnCreateMemberships = $("#btnCreateMemberships");
divCreated = $("#divCreated");
btnGenerateControls = $("#btnGenerateControls");
progressBarControl = $("#barProgress");
progressBarReplacer = $("#ProgressReplacer");
//get the membership type for the company membership.
$.when(GetCurrentMemberships(), GetMembershipType(), GetContacts()).done(function () {
CheckMembershipCount();
});
btnGenerateControls.click(function () {
ProcessContacts(AccountContactsList);
btnGenerateControls.prop("disabled", true);
btnGenerateControls.off("click");
});
btnCreateMemberships.click(function () {
CreateMemberships();
});
});
function getDataParam() {
//Get the any query string parameters and load them
//into the vals array
var vals;
if (location.search != "") {
vals = location.search.substr(1).split("&");
for (var i in vals) {
vals[i] = vals[i].replace(/\+/g, " ").split("=");
}
//look for the parameter named 'data'
for (var i in vals) {
if (vals[i][0].toLowerCase() == "data") {
parseDataValue(vals[i][1]);
return;
}
}
}
}
function parseDataValue(datavalue) {
if (datavalue != "") {
var vals = decodeURIComponent(datavalue).split("&");
for (var i in vals) {
vals[i] = vals[i].replace(/\+/g, " ").split("=");
}
EntityId = vals[0][1];
accountId = vals[1][1];
CompanyMembershipTypeId = vals[2][1];
return;
}
}
//Retrieve the personal memberships linked to the current company membership;
function GetCurrentMemberships() {
return $.ajax({
type: "GET",
contentType: "application/json; charset=uft-8",
datatype: "json",
url: ODataPath + "/acm_lidmaatschappersoonlijkSet?$filter=acm_bedrijfslidmaatschap/Id eq guid'" + EntityId + "'",
beforeSend: function (xmlHttpRequest) {
xmlHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data) {
AccountPersonalMembershipList = data.d.results;
},
error: function () {
error();
}
});
}
//helperfunction to adjust the progress bar
//progress bar is adjusted twice per ajax call.
function add1ToProgress() {
ProgressCount++;
progressBarControl.prop("value", ProgressCount);
}
//haal het type bedrijfslidmaatschap op, enkel de velden voor het aantal en soort onderliggende lidmaatschappen.
function GetMembershipType() {
return $.ajax({
type: "GET",
contentType: "application/json; charset=uft-8",
datatype: "json",
url: ODataPath + "/acm_lidmaatschapSet(guid'" + CompanyMembershipTypeId + "')?$select=acm_soortonderliggendelidmaatschappen,acm_aantallidmaatschappen",
beforeSend: function (xmlHttpRequest) {
xmlHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data) {
CompanyMembershipType = data.d;
},
error: function () {
error();
}
});
}
//Retrieve all customers linked to the company linked to this membership.
function GetContacts() {
return $.ajax({
type: "GET",
contentType: "application/json; charset=uft-8",
datatype: "json",
url: ODataPath + "/ContactSet?$filter=ParentCustomerId/Id eq guid'" + accountId + "'",
beforeSend: function (xmlHttpRequest) {
xmlHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data) {
AccountContactsList = data.d.results;
},
error: function () {
error();
}
});
}
//happens after the above 3 ajax calls are finished;
//checks if the company can make additional memberships
//disables the buttons if this is the case and shows the reason.
function CheckMembershipCount() {
//check if the company already has the max amount of memberships;
if (AccountPersonalMembershipList.length >= CompanyMembershipType.acm_aantallidmaatschappen) {
$("input:button").prop("disabled", true);
divCreated.append("Dit bedrijf kan geen extra lidmaatschappen meer krijgen omdat het al aan het maximum zit.");
$("#ProgressContainer").empty();
} else {
//check if the company has any contacts that aren't yet members for this company;
//ContactIsValid returns true if there is any contact that can be made member;
for (var i in AccountContactsList) {
if (ContactIsValid(AccountContactsList[i])) {
return;
}
}
$("input:button").prop("disabled", true);
divCreated.append("Dit bedrijf heeft geen contacten, of alle gekoppelde contacten hebben reeds een lidmaatschap van dit bedrijf.");
$("#ProgressContainer").empty();
}
}
//creates the memberships for the company;
function CreateMemberships() {
//disable the button so we don't have accidental double commits
btnCreateMemberships.off("click");
btnCreateMemberships.prop("disabled", true);
var createArray = [];
//get all the checked boxes;
var checkedBoxes = $(".contactChecks:checked");
//calculate the amount of checked boxes;
CheckedBoxesCount = checkedBoxes.size();
//we want the progress bar to increment once before we start ajaxing and then twice for each ajax (before and after)
progressBarControl.prop("max", (CheckedBoxesCount * 2) + 1);
progressBarReplacer.text("0 van " + CheckedBoxesCount);
//disable the checkboxes so we don't have accidental triggers;
$(".contactChecks").prop("disabled", true);
//We want to notify how many memberships have been made after they're all made. since they're async, we'll need to use promises
//however, because we repeat the same ajax call with different parameters, we need to push them to an array and then apply() them.
checkedBoxes.each(function () {
createArray.push(CreateMembershipsAjax(this));
});
//we did the work before we start creating them, so show some progress;
add1ToProgress();
$.when.apply(null, createArray).done(function () {
//this function will only start once all ajax calls have been successfull.
divCreated.append(membershipCount + " lidmaatschappen aangemaakt:");
MembershipsCreated = true;
});
}
//if something goes wrong, alert the user;
function error() {
alert("Er is een fout gebeurd bij het uitvoeren van deze actie. info: ");
}
//add checkboxes for each contact;
function ProcessContacts(result) {
for (var i in result) {
var contact = result[i];
//Check if the contact already exists as a membership for this company.
if (ContactIsValid(contact)) {
addCheckBox(contact);
}
}
}
function addCheckBox(contact) {
//get the container to use;
var container = $("#ContactList");
//get the contactId;
var id = contact["ContactId"].toString();
//create a checkbox
var checkBox = $(document.createElement('input')).attr({
id: "cb" + id,
value: id,
"class": "contactChecks",
type: "checkbox",
});
//add the onchange to the textbox;
checkBox.on("change", CheckContactCount);
//add the container to the checkbox;
container.append(checkBox);
//show the name for the contact;
container.append(contact["FirstName"] + " " + contact["LastName"]);
//whitespace;
container.append(
$(document.createElement("br"))
);
}
//notifies the user if he tries to select more contacts than can be turned to users;
function CheckContactCount() {
//calculate the potential memberships, the current memberships and the sum of these 2;
var checkedCount = $(".contactChecks:checked").size();
var bestaandLidmaatschapCount = AccountPersonalMembershipList.length;
var totalCount = checkedCount + bestaandLidmaatschapCount;
//if the sum is greater than allowed;
if (totalCount > CompanyMembershipType.acm_aantallidmaatschappen) {
//show a message to inform
divCreated.empty();
divCreated.append("U kunt maximum " + (CompanyMembershipType["acm_aantallidmaatschappen"] - bestaandLidmaatschapCount) + " nieuwe lidmaatschappen maken.");
divCreated.append(
$(document.createElement("br"))
);
divCreated.append("U heeft nu " + checkedCount + " contacten geselecteerd.");
//disable the create button;
btnCreateMemberships.off("click");
btnCreateMemberships.prop("disabled", true);
} else {
//if the sum not greater;
//empty the creation message;
divCreated.empty();
//rebind the button, unbinding previous ones in the process;
//We don't need to worry about accidentally rebinding the button when it's disabled:
//Either we disabled through this function, so it's reversing itself;
//or it was disabled through clicking the button, which disables these checkboxes anyway.
btnCreateMemberships.off("click");
btnCreateMemberships.click(function () {
CreateMemberships();
});
btnCreateMemberships.prop("disabled", false);
}
}
function ContactIsValid(contact) {
for (var i in AccountPersonalMembershipList) {
//localeCompare returns 0 if the strings are equal, so need to invert for a boolean
if (!AccountPersonalMembershipList[i]["acm_contactpersoon"].Id.localeCompare(contact["ContactId"])) {
//if it's equal, it returns false because the contact already has a membership with this company
return false;
}
}
//if no memberships with this name are found, it should return true so the Contact is valid for showing.
//still need to check if there's not yet a control with with that id as a value.
//get all checkboxes with this ContactId
var checkboxes = $(":checkbox[value=" + contact["ContactId"] + "]");
//if any exist
if (checkboxes.length > 0) {
//return false
return false;
}
return true;
}
function CreateMembershipsAjax(element) {
var contactId = element.defaultValue;
//create the membership
var persoonlijkLidmaatschap = new Object();
persoonlijkLidmaatschap.acm_contactpersoon = { Id: contactId.replace(/[{}]/g, "") };
persoonlijkLidmaatschap.acm_bedrijfslidmaatschap = { Id: EntityId.replace(/[{}]/g, "") };
persoonlijkLidmaatschap.acm_lidmaatschap = { Id: CompanyMembershipType.acm_soortonderliggendelidmaatschappen.Id.replace(/[{}]/g, "") };
//turn the json into a string using default browser set;
var lidmaatschapJson = JSON.stringify(persoonlijkLidmaatschap);
//increment the counter once before the ajax call;
add1ToProgress();
return $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataPath + "/acm_lidmaatschappersoonlijkSet",
data: lidmaatschapJson,
beforeSend: function (xmlHttpRequest) {
xmlHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function () {
//increment the counter again after the ajax call;
membershipCount++;
add1ToProgress();
progressBarReplacer.text(membershipCount + " van " + CheckedBoxesCount + "memberships aangemaakt.");
},
error: function () {
error();
}
});
}
Method for loading the html page (added as a javascript action on a ribbon button):
function acm_mscrm2011_openModalDialog() {
var entityId = Xrm.Page.data.entity.getId();
var accountId = Xrm.Page.getAttribute("acm_account").getValue()[0].id;
var companyMembershipTypeId = Xrm.Page.getAttribute("acm_typelidmaatschap").getValue()[0].id;
var parameters = encodeURIComponent("entityId=" + entityId + "&accountId=" + accountId + "&membershiptype=" + companyMembershipTypeId);
Xrm.Utility.openWebResource("acm_/membership_generator_html.htm", parameters);
}
this code works fine in Chrome. However, in IE11, the html webresource is opened, Jquery is loaded, the CSS and ClientContext is loaded, but the javascript code above loads for a few seconds (checked using the F12 tools), but after a few seconds, it disappears from my resource list in the tools. I also get a message in my error log: "Id, something, or something else is expected" (not too sure about those other 2) on:
var checkBox = $(document.createElement('input')).attr({
id: "cb" + id,
value: id,
"class": "contactChecks",
type: "checkbox",
});
I don't know what causes this. it works fine in Chrome, but not in IE11. This is just some code to dynamically generate controls based on some CRM data, I don't know why it fails in one browser, but not the other.
I found out what caused this and as always, it's something really small.
IE11 complains about the comma at the end of my attribute array. I removed that and it worked.

Facebook API disrupting rest of page until it loads data

I'm using the Facebook Javascript SDK to provide some features, but it's making the functionality of the rest of the page lag out/not work until it's done loading. To experience this, please go on http://beta.speedsums.com and click the (poorly placed) Facebook login button and then try to click inside the answer box. Alternatively, you may be able to spot something from the code here:
<!DOCTYPE HTML>
<html>
<head>
<title>Speedsums - do maths fast</title>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-46469577-1', 'speedsums.com');
ga('send', 'pageview');
</script>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Lato:100,300,400,700,900,100italic,300italic,400italic,700italic,900italic' rel='stylesheet' type='text/css'>
<style type="text/css">
css stuff
</style>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="jquery.runner-min.js" type="text/javascript"></script>
<script src="chart.js" type="text/javascript"></script>
<script src="jquery.animate-colors-min.js" type="text/javascript"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var data2;
var jsonn;
var myLine;
</script>
<script type="text/javascript">
var fbid;var fbid = 0;
var operators = ['+','-','x','\xF7'];
var properties = {
borderColor: 'green',
borderWidth: '3px',
height: '37px'
};
var user = {};
var friends = [];
var friendscores = [];
var friendpics = [];
var fbconnect;
var operand1;
var operand2;
var operator;
var answers;
var time;
var name;
var one;
var two;
var iteration = 0;
var unique;
var times = [];
var start;
var finish;
function drawuserchart(id){
console.log('drawuserchart() initialised');
$.ajax({
url: 'userchart.php',
data: {id: id},
type: 'post',
dataType:"json",
success: function(data22){
console.log(data22);
var labelarray = new Array();
for (var i=0;i<data22.length;i++) {
labelarray.push("");
}
data2 = {
labels : labelarray,
datasets : [
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(131,167,185,1)",
data : data22
}
]
}
var options = {
//Boolean - If we show the scale above the chart data
scaleOverlay : false,
}
myLine2 = new Chart(document.getElementById("userchart").getContext("2d")).Line(data2,options);
}, error: function(xhr,err){
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
}
function generateproblems(number){
operand1 = []; operand2 = []; operator = []; answers = [];
for (var i=0; i < number; i++){
//generating questions
operator.push(operators[Math.floor(Math.random() * 4)]);
if (operator[i] == '\xF7'){
denominator = Math.floor((Math.random()*12)+1);
numerator = denominator * Math.floor((Math.random()*12)+1);
operand1.push(numerator);
operand2.push(denominator);
} else if (operator[i] == '-'){
one = Math.floor((Math.random()*12)+1);
two = Math.floor((Math.random()*12)+1);
operand1.push(Math.max(one,two));
operand2.push(Math.min(one,two));
} else {
operand1.push(Math.floor((Math.random()*12)+1));
operand2.push(Math.floor((Math.random()*12)+1));
}
//calculating answers
if (operator[i] == '+'){
answers.push(operand1[i] + operand2[i]);
} else if (operator[i] == '-'){
answers.push(operand1[i] - operand2[i]);
} else if (operator[i] == 'x'){
answers.push(operand1[i] * operand2[i]);
} else if (operator[i] == '\xF7'){
answers.push(operand1[i] / operand2[i]);
}
}
}
function runtest(number){
$('#question').append('' + operand1[iteration] + ' ' + operator[iteration] + ' ' + operand2[iteration] + ' = ');
$('#answer').keyup(function() {
if ($('#answer').val() == answers[iteration]){
finish = Date.now();
times.push(finish-start);
console.log(finish-start)
if(iteration == 0){
start = Date.now();
$('#runner').runner('start');
$('#counter').html(iteration);
};
iteration++;
correct(number);
}
});
}
function percentile(score){
$.ajax({
url: 'percentile.php',
data: {score: score},
type: 'post',
success: function(data){
$('#percentile').html('You beat <b>'+ data +'% </b>of people.');
}
});
}
function correct(number){
if(iteration == number){
$('#runner').runner('stop');
$('#runner').append('s');
time = parseInt($('#runner').html()) / (number - 1);
$('#runner').prepend('Total time: ');
$('body').append('Time per question: ' + time + 's');
stoptest();
} else {
$('#question').empty();
$('#counter').html(iteration);
$('#answer').val('');
$('#question').append('' + operand1[iteration] + ' ' + operator[iteration] + ' ' + operand2[iteration] + ' = ');
start = Date.now();
}
}
function stoptest(){
operand1 = [];
operand2 = [];
answers = [];
operator = [];
$('#question').remove();
$('#answer').remove();
console.log(times);
}
function gethighscore(id){
$.ajax({
async: false,
url: 'gethighscore.php',
data: {id: id},
type: 'post',
success: function(data){
friendscores.push(data);
console.log(data);
}
});
}
function getuserhighscore(id){
$.ajax({
async: false,
url: 'gethighscore.php',
data: {id: id},
type: 'post',
success: function(data){
user['highscore'] = data;
}
});
}
function userpercentile(score){
$.ajax({
url: 'percentile.php',
async: false,
data: {score: score},
type: 'post',
success: function(data){
user['percentile'] = data;
}
});
}
function post(name,score,unique){
$.ajax({
url: 'post.php',
data: {name: name, score: score, unique: unique},
type: 'post',
success: function(data){
$('#main').html('');
$('#main').append('<br><br><br><br><span id="message">Submitted! ok now try again</span><br><br>');
$('#main').append('<div id="restart">restart</div>');
}
});
}
function logg(score,unique,fb){
console.log('attempting to log');
$.ajax({
url: 'log.php',
data: {score: score, unique: unique, fb: fb},
type: 'post',
success: function(data){
console.log(data);
}
});
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function portrait(){
console.log('success');
}
$(document).ready(function(){
$.ajax({
url: 'total.php',
data: {},
type: 'post',
dataType: 'html',
success: function(data){
console.log(data);
$('.total').append('<b>'+numberWithCommas(data)+'</b>');
}
});
$('#form').hide();
$('#runner').runner({
countdown: true,
startAt: 30 * 1000,
stopAt: 0
}).on('runnerFinish', function(eventObject, info) {
times[0] = 0;
times[times.length - 1] = 0;
if(times[2] == times[3] == times[4] == times[5]){
window.location.replace("http://en.wikipedia.org/wiki/Hacker_(computer_security)");
}
unique = 15*iteration + 4;
percentile(iteration);
logg(iteration,unique,fbid);
var slowesttime = Math.max.apply(Math,times);
var position = times.indexOf(slowesttime);
var slowestq = '' + operand1[position] + ' ' + operator[position] + ' ' + operand2[position] + '';
var slowesta = answers[position];
$('#counter, #solidus, #runner').remove();
$('body').animate({backgroundColor: '#f0f0f0'});
$('#wrapper').fadeIn("fast");
if(fbconnect == true){
$('#sidebar').fadeIn("fast");
}
$('#score').append('<div id="results1">Total: <b>' + iteration + '</b></div>');
$('#score').append('<div id="percentile"></div>');
$('#score').append('<div id="other">Time per question: <b>' + (30/iteration).toFixed(2) + 's</b></div>');
$('#score').append('<div id="other">For future reference, <b>' + slowestq + ' = ' + slowesta + '</b>. It should not take <b>' + (slowesttime/1000).toFixed(2) + 's</b> to solve that next time. </div>');
$('#form').show();
$('#tweet').click(function(){
window.open('https://twitter.com/intent/tweet?text=omg+i+just+did+'+iteration+'+maths+problems+in+30s!+try+and+beat+me!&hashtags=speedsums&url=http%3A%2F%2Fwww.speedsums.com', 'Tweet', "height=300,width=500");
});
stoptest();
});
generateproblems(120);
runtest(120);
$('#answer').focus(function(){
$('body').animate({backgroundColor: '#BDC3C7'});
$('#wrapper').fadeOut("fast");
$('#instructions').fadeOut("fast");
$('#sidebar').fadeOut("fast");
});
$('#answer').blur(function(){
$('#wrapper').fadeIn("fast");
$('#instructions').fadeIn("fast");
if(fbconnect == true){
$('#sidebar').fadeIn("fast");
}
$('body').animate({backgroundColor: '#f0f0f0'});
});
$('#post').click(function(){
name = $('#name').val();
unique = 15*iteration + 4;
post(name,iteration,unique);
});
$('body').on('click','#restart, #retry', function() {
window.location.href = "index.html";
});
//Get context with jQuery - using jQuery's .get() method.
var ctx = $("#myChart").get(0).getContext("2d");
//This will get the first returned node in the jQuery collection.
var myNewChart = new Chart(ctx);
var ctx2 = $("#userchart").get(0).getContext("2d");
//This will get the first returned node in the jQuery collection.
var userchart = new Chart(ctx2);
$.ajax({
url: 'distribution.php',
data: {},
type: 'get',
dataType:"json",
success: function(data22){
var dataarray = new Array();
for (var i=0;i<46;i++) {
dataarray.push(data22[i]);
}
data2 = {
labels : ["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42"],
datasets : [
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
data : dataarray
}
]
}
var options = {
//Boolean - If we show the scale above the chart data
scaleOverlay : false,
}
myLine = new Chart(document.getElementById("myChart").getContext("2d")).Bar(data2,options);
}
});
});
</script>
</head>
<body>
<div id="fb-root"></div>
<!--
Below we include the Login Button social plugin. This button uses the JavaScript SDK to
present a graphical Login button that triggers the FB.login() function when clicked.<span class="total">Total sums done: </span> -->
<div id="header"><div class="page"><a class="nav1">TEST</a><div id="logo"></div><a class="nav2">PRACTICE</a><div id="thumbnail"><div class="fb-login-button" id="fbloginbutton" data-max-rows="1" data-size="medium" data-show-faces="false" data-auto-logout-link="false"></div></div></div></div><div id="sidebar" style="display:none"><h2>FRIENDS</h2><div id="friendcontainer"></div><div id="statscontainer"><h2>YOUR STATS</h2></div><canvas id="userchart" width="250" height="200"></canvas></div>
<div id="notice">Speedsums is under renovation - there's gonna be a bunch of cool new stuff soon, so keep checking back! -Taimur</a></div>
<br><div class="instructions"><span id="instructions">Click inside the box below to begin</span></div><div id="spacer"></div>
<div id="main">
<div id="question"></div><br>
<div><input id="answer" type="text" autocomplete="off"></div><br>
<div id="runner"></div><span id="solidus">/</span><div id="counter">0</div>
<div id="score"></div>
<div id="form">
<div id="tweet">Tweet Score</div><br>
<div id="retry">Retry</div>
</div><br><br>
</div>
<canvas id="myChart" width="1440" ></canvas>
<script>
// Include the UserVoice JavaScript SDK (only needed once on a page)
UserVoice=window.UserVoice||[];(function(){var uv=document.createElement('script');uv.type='text/javascript';uv.async=true;uv.src='//widget.uservoice.com/aIRVe5TPDRSYNkW7H1CAg.js';var s=document.getElementsByTagName('script')[0];s.parentNode.insertBefore(uv,s)})();
//
// UserVoice Javascript SDK developer documentation:
// https://www.uservoice.com/o/javascript-sdk
//
// Set colors
UserVoice.push(['set', {
accent_color: '#448dd6',
trigger_color: 'white',
trigger_background_color: '#448dd6'
}]);
// Identify the user and pass traits
// To enable, replace sample data with actual user traits and uncomment the line
UserVoice.push(['identify', {
//email: 'john.doe#example.com', // User’s email address
//name: 'John Doe', // User’s real name
//created_at: 1364406966, // Unix timestamp for the date the user signed up
//id: 123, // Optional: Unique id of the user (if set, this should not change)
//type: 'Owner', // Optional: segment your users by type
//account: {
// id: 123, // Optional: associate multiple users with a single account
// name: 'Acme, Co.', // Account name
// created_at: 1364406966, // Unix timestamp for the date the account was created
// monthly_rate: 9.99, // Decimal; monthly rate of the account
// ltv: 1495.00, // Decimal; lifetime value of the account
// plan: 'Enhanced' // Plan name for the account
//}
}]);
// Add default trigger to the bottom-right corner of the window:
UserVoice.push(['addTrigger', { mode: 'satisfaction', trigger_position: 'top-left' }]);
// Or, use your own custom trigger:
//UserVoice.push(['addTrigger', '#id', { mode: 'satisfaction' }]);
// Autoprompt for Satisfaction and SmartVote (only displayed under certain conditions)
UserVoice.push(['autoprompt', {}]);
</script>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '219892158204692',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
// for any authentication related change, such as login, logout or session refresh. This means that
// whenever someone who was previously logged out tries to log in again, the correct case below
// will be handled.
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
if(fbconnect == true){
} else {
fbconnect = true;
$('#fbloginbutton').hide();
$('#friendcontainer').append('<span id="loader"><center>Loading...</center></span>');
// The response object is returned with a status field that lets the app know the current
// login status of the person. In this case, we're handling the situation where they
// have logged in to the app.
FB.api(
"/me",
function (response) {
if (response && !response.error) {
fbid = response['id'];
user['id'] = response['id'];
getuserhighscore(user['id']);
userpercentile(parseInt(user['highscore']));
$('#statscontainer').append('<span class="label">Highest Score</span>: '+user['highscore']+'<br>');
$('#statscontainer').append('<span class="label">Percentile (global)</span>: '+user['percentile']+'<br>');
drawuserchart(user['id']);
}
}
);
FB.api(
"/fql?q=select%20uid%2C%20first_name%2C%20is_app_user%20from%20user%20where%20uid%20in%20(select%20uid2%20from%20friend%20where%20uid1%3Dme())%20and%20is_app_user%3D1",
function (response) {
console.log('friends installed:');
console.log(response);
console.log(response['data'][0].id);
var responseArray = [];
responseArray.push(response);
console.log(responseArray);
user['friends'] = response['data'].length;
if (response && !response.error) {
for (var i=0;i<response['data'].length;i++){
friend = response['data'][i];
console.log('friend coming up');
console.log(friend);
friends.push(friend.uid);
$('#friendcontainer').append('<div class="friendbox" id="'+friend.uid+'"></div>');
$('#'+friend.uid+'').append('<img class="friendpic" src="https://graph.facebook.com/'+friend.uid+'/picture?height=60&width=60&type=square">');
$('#'+friend.uid+'').append('<div class="friendname">'+friend.first_name+'</div>');
gethighscore(friend.uid);
$('#'+friend.uid+'').append(' - '+friendscores[i]+'');
console.log(friendscores);
}
$('#loader').remove();
user['friendrank'] = 1;
for (var i=0;i<friendscores.length;i++){
if(friendscores[i] > user['highscore']){
user['friendrank']++;
}
}
$('#statscontainer').append('<span class="label">Rank (among friends)</span>: '+user['friendrank']+'<br>');
} else {
console.log(response.error)
}
}
);
console.log(friends);
console.log(user)
FB.api(
"/me/picture",
{
"redirect": false,
"height": "100",
"type": "normal",
"width": "100"
},
function (response) {
if (response && !response.error) {
user['picture'] = response['data']['url'];
console.log(user['picture']);
$('#thumbnail').append('<img id="thumbnailpic" src="'+user['picture']+'">');
}
}
);
}
testAPI();
} else if (response.status === 'not_authorized') {
// In this case, the person is logged into Facebook, but not into the app, so we call
// FB.login() to prompt them to do so.
// In real-life usage, you wouldn't want to immediately prompt someone to login
// like this, for two reasons:
// (1) JavaScript created popup windows are blocked by most browsers unless they
// result from direct interaction from people using the app (such as a mouse click)
// (2) it is a bad experience to be continually prompted to login upon page load.
FB.login();
} else {
// In this case, the person is not logged into Facebook, so we call the login()
// function to prompt them to do so. Note that at this stage there is no indication
// of whether they are logged into the app. If they aren't then they'll see the Login
// dialog right after they log in to Facebook.
// The same caveats as above apply to the FB.login() call here.
FB.login();
}
});
};
// Load the SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
// Here we run a very simple test of the Graph API after login is successful.
// This testAPI() function is only called in those cases.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
$('#sidebar').slideDown("slow");
});
}
</script>
</body>
</html>
Sorry that the code is so messy and bad - I'm not sure how much of the Javascript stuff I need to include for the problem to be diagnosed so I've just put it all in. I'm not sure why the Facebook stuff is disrupting everything else, because it's right at the very bottom of the page...
Thanks
Well, at least I notice two things in your code:
The call of testAPI() is from my perspective unneccessary and "out of context"
You can save at least one API call if you combine the first with the third one like this
FB.api('/me?fields=id,picture', function { ... });

my javascript code will not proceed to delete my data from jqGrid

just want to ask regarding my javascript code. I have a function that will delete and edit a data in my jqgrid. But everytime i run my code, it will not delete and edit if I dont put an alert in some portion of the code. Why is it happening? How can i make my program run without the alert?
Below is my delete function:
function woodSpeDelData(){
var selected = $("#tblWoodSpe").jqGrid('getGridParam', 'selrow');
var woodID='';
var woodDesc='';
var codeFlag = 0;
var par_ams = {
"SessionID": $.cookie("SessionID"),
"dataType": "data"
};
//this part here will get the id of the data since my id was hidden in my jqgrid
$.ajax({
type: 'GET',
url: 'processjson.php?' + $.param({path:'getData/woodSpecie',json:JSON.stringify(par_ams)}),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$.each(data['result']['main']['rowdata'], function(rowIndex, rowDataValue) {
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
var fldName = data['result']['main']['metadata']['fields'][columnIndex].name;
if (fldName == 'wood_specie_id'){
woodID = rowArrayValue;
}
if (fldName == 'wood_specie_desc'){
woodDesc = rowArrayValue;
alert($('#editWoodSpeDesc').val() +' '+ woodDesc); //program will not delete without this
if(selected == woodDesc){
codeFlag =1;
alert(woodID); //program will not delete without this
};
}
});
if (codeFlag == 1){
return false;
}
});
if (codeFlag == 1){
return false;
}
}
}
});
alert('program will not proceed without this alert');
if (codeFlag == 1) {
var datas = {
"SessionID": $.cookie("SessionID"),
"operation": "delete",
"wood_specie_id": woodID
};
alert(woodID);
alert(JSON.stringify(datas));
$.ajax({
type: 'GET',
url: 'processjson.php?' + $.param({path:'delete/woodSpecie',json:JSON.stringify(datas)}),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$('#tblWoodSpe').trigger('reloadGrid');
}
}
});
}
}
EDIT
My main purpose of putting an alert was just to know if my code really get the right ID of the description, and if would really go the flow of my code... But then i realized that it really wont work with it.

Categories

Resources