How to use KnockoutJS to save data into SQL database? - javascript

Good day everybody. I have a question about how to use the right way to save data into SQL database through KnockoutJs. The record are display well in the table. It should be able to save the data via this pop-up Modal. But after I click the Create button in that modal, it only pop-up a failed Message. Can anybody please help me to solve this problem? Thank you very much.
Below is extract from main js file about Save function
var data = ko.toJSON(self.Profiles());
$.ajax({
type: 'POST',
url: '/ajaxCall/insertProAjax',
data: "{ Customer:" + ko.utils.stringifyJson(self.Name) + ",customerRemove:" + ko.utils.stringifyJson(self.CustomerRemove) + "}",
contentType: "application/json",
success: function (data) {
alert("Record has been saved Successfully");
MarkCustomerAsSaved();
$('#AddNewModel').modal('hide');
},
error: function () {
alert("Failed");
}
}).fail(function (xhr, textStatus, err) { alert(err); });
Below is extract from the ViewModel about save function
var Customer = {};
Customer.Id = c.Id;
Customer.Name = c.Name;
Customer.Age = c.Age;
Customer.Address = c.Address;
if (isNewRecord === false) {
$.ajax({
type: "PUT",
url: "/api/CustomerAPI/" + c.Id,
data: Customer
})
.done(function (resp) {
self.Message("Record Updated Successfully ");
self.reset();
})
.fail(function (err) {
self.Message("Error Occures, Please Reload the Page and Try Again " + err.status);
self.reset();
});
}
if (isNewRecord === true) {
isNewRecord = false;
$.ajax({
type: "POST",
url: "/api/CustomerAPI",
data: Customer
})
.done(function (resp) {
self.Message("Record Added Successfully ");
self.reset();
loadData();
}).fail(function (err) {
self.Message("Error Occures, Please Reload the Page and Try Again " + err.status);
self.reset();
});
}

Knockout and Javascript (in this manner) are being processed client side. You will need to create something on the back end to accept your data payload and save it to the database. If you want to stay in the JavaScript family, I would recommend
node.js. Alternatively this is where php, or C# would come into play.

Related

select2 returning position of items, not ID of items

I'm using a select2 to allow the user to select multiple options. Everything is working fine, except for one frustrating issue.
The first time I click the save button to save the items, it works. But then on subsequent calls, the ID of the items are replaced with the position of the items. For for example, if I have IDs 3, 6 and 10 selected, the first Save will work and 3,6,10 are passed to the controller.
But then if I reload the view and click save, the numbers 0,1,2 are passed in (ie, their relative positions in the select).
Here is the code:
Firstly, the HTML:
<select id="selectGroup" class="form-control" multiple="true">
On $(document).ready:
// Load Groups
$("#selectGroup").select2({ placeholder: 'Select' });
$.ajax({
url: ROOT_URL + "Group/GroupList",
type: "GET",
success: function (data) {
let dropdown = $('#selectGroup');
dropdown.empty();
dropdown.append($('<option></option>').attr('value', 0).text("(Select)"));
$.each(JSON.parse(data), function (key, entry) {
dropdown.append($('<option></option>').attr('value', entry.GroupID).text(entry.GroupName));
})
},
error: function (passParams) {
Notify(passParams, "Unexpected Error Loading Groups", "error");
}
});
And finally the js for the save (called from a button which passes in the loanID):
function LoanGroupSave(loanID) {
var grpIDs = '';
[].forEach.call(document.querySelectorAll('#selectGroup :checked'), function (elm) {
grpIDs += elm.value + ',';
})
var editURL = location.protocol + '//' + location.host + "/Loan/LoanGroupSave";
//alert(editURL);
var obj = { "LoanID": loanID, "GroupIDs": grpIDs };
alert(JSON.stringify(obj));
$.ajax({
type: "POST",
url: editURL,
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
}).done(function (response) {
if (response.success) {
Notify("Group(s) information has been saved", "Saved", "success", false, "toast-top-right", 5000);
}
else {
OpenPopupGeneral("Error(s)", response.message);
}
}).fail(function (jqXHR, textStatus, errorThrown) {
OpenPopupGeneral("Unexpected Error(s)", "Error = " + errorThrown);
});
}
Posting for people who make the same mistake.
Problem was in my load - I needed to add the GroupID as the key, not the row number which was in the key parameter value:
success: function (data) {
$.each(JSON.parse(data), function (key, entry) {
var $newOption = $("<option selected='selected'></option>").val(entry.GroupID).text(entry.GroupName);
$("#selectGroup").append($newOption).trigger('change');
}

Why I'am always getting "Duplicate Alert" error after doing update request?

I am writing Chrome Extension for Vtiger CRM.
I need to create ability to add value for "Proposal text" field in the CRM on project page.
Here is the docs: https://www.vtiger.com/docs/rest-api-for-vtiger#/Update
How I do it:
Get the project from Vtiger API.
Change value "cf_potentials_proposaltext" in the project object.
Make POST (as required by docs) request to update Vtiger API endpoint, send updated project object
Get "duplicate alert" response..
I am absolutely sure, since I checked that I am sending the modified project object - using the console.log 'Temprorary_1' (in vtigerAddProposal) and 'Temprorary_2'(in vtigerUpdatePotential), also checked changed value in Chrome dev console in Network tab..
Here is my code:
function vtigerAddProposal() {
var temprorary_potential;
var dialog = $('#dialog');
chrome.storage.sync.get(['proposal'], function(result) {
$.ajax( {
url: 'https://roonyx.od2.vtiger.com/restapi/v1/vtiger/default/retrieve',
type: 'GET',
data: {
'id': localStorage.getItem('vtiger_last_opportunity_id')
},
success: function( response ) {
temprorary_potential = response['result'];
console.log("Temprorary_1: " + JSON.stringify(temprorary_potential, null, 2));
temprorary_potential['cf_potentials_proposaltext'] = result.proposal;
vtigerUpdatePotential(temprorary_potential);
},
error: function (response) {
console.log("Failed to get opportunity from Vtiger.");
$('#dialog-inner-text').text("Vtiger: " + response.status + " " + response.statusText);
dialog.show(800);
console.log(response);
}
});
});
}
function vtigerUpdatePotential(data) {
var dialog = $('#dialog');
console.log("Temprorary_2: " + JSON.stringify(data, null, 2));
// Second Part
$.ajax( {
url: 'https://roonyx.od2.vtiger.com/restapi/v1/vtiger/default/update',
type: 'POST',
data: {
element: JSON.stringify(data)
},
success: function( response ) {
console.log("Successfully updated Vtiger potential.")
console.log(response);
localStorage.removeItem('vtiger_last_opportunity_id'); // в случае успеха удаляем oppId
},
error: function (response) {
console.log("Failed to update potential in Vtiger.")
$('#dialog-inner-text').text("Vtiger potential wasn't update: " + response.status + " " + response.statusText);
dialog.show(800);
console.log(response);
}
});
}
Thank you in advance.
Problem solved by using revise https://www.vtiger.com/docs/rest-api-for-vtiger#/Revise once instead of update. Thanks to #pinaki

MVC calling controller from javascript

I've got an MVC view that is successfully calling a controller. In the controller, I call a stored procedure (using entity framework) and get some results. That part of it all works fine. But, I'm unable to get my results back from my javascript. When I have it as an ActionResult, all is fine, I just can't seem to get to the result. When I try to change it to a JsonResult, I keep getting an "Internal Server" error, so I'm not sure which way to go. Any pointers would help (I'm not a great javascript/jquery developer).
My javascript:
var jqXHR = $.ajax({
method: 'POST',
url: varurl,
data: { text: tempField, letterId: "2" },
cache: false,
success: function (results) { alert(results) }
})
.done(function (result) {
$('#content').empty();
$('#content').html(result);
$('#content').html(result);
})
.error(function (xhr, status, error) {
alert(error);
});
//letterArea.value = letterArea.value + title[0] + "\r\n" + "\r\n" + title[1] + "\r\n" + "\r\n";
letterArea.value = "Hello";
}
My Controller:
public ActionResult ResolveText(string text, string letterId)
{
using (LMNEntities db = new LMNEntities())
{
var results = db.ResolveFieldsForLetter(Convert.ToInt32(letterId),text);
return View(results);
}
}

Ajax wait till redirect to finish executing.

I have basically the same problem as the one described in the link below, but I dont find the solution to be very clear. I want my ajax success function to wait until the window function is finished executing, THEN modify the divs. Instead, it modifies the divs of the current page, then redirects. AJAX: on success redirect then modify new page
main.js
$("#form").submit( function(e) {
e.preventDefault();
var id = $('#searchbar').val(); // store the form's data.
$.ajax({
url: '/search',
type: 'POST',
data: {id:id},
dataType: 'text',
success: function(data) {
//Redirect to the page where we want to display the data
window.location.href = '/test';
data = JSON.parse(data);
console.log(data);
$("#count").text("we analyzed...");
$("#result1").text(data.county);
$("#totals").text("with a score of..");
$("#result2").text(data.totalSentiments);
},
error: function(jqXHR, textStatus, errorThrown){
console.log("error")
alert(textStatus, errorThrown);
}
});
});
I Will Suggest you Javascript Local Storage .
main.js
$("#form").submit( function(e) {
e.preventDefault();
var id = $('#searchbar').val(); // store the form's data.
$.ajax({
url: '/search',
type: 'POST',
data: {id:id},
dataType: 'text',
success: function(data) {
//Redirect to the page where we want to display the data
window.location.href = '/test';
data = JSON.parse(data);
console.log(data);
// Store
localStorage.setItem("count", "we analyzed...");
localStorage.setItem("result1", data.county);
localStorage.setItem("totals", "with a score of..");
localStorage.setItem("result2", data.totalSentiments);
},
error: function(jqXHR, textStatus, errorThrown){
console.log("error")
alert(textStatus, errorThrown);
}
});
});
On Ready on same page:
jQuery(document).ready(function(){
if (localStorage.count) {
$("#count").text(localStorage.count);
}
if (localStorage.result1) {
$("#result1").text(localStorage.result1);
}
if (localStorage.totals) {
$("#totals").text(localStorage.totals);
}
if (localStorage.result2) {
$("#result2").text(localStorage.result2);
}
});
Local Storage Store Data in Browser Storage. You Also Can Remove Data From Local Storage.
setting the value of location.href will cause a full page refresh.
Therefore all your scripts will be wiped out.
If you REALLY wants to use the result of a ajax call to a redirected page, you should store this response data somewhere, then reuse it on your new page.
//save "data" in localSotorage
localStorage.myAjaxResponse = data; //if data is JSON then use: JSON.stringify(data) instead.
Then on your "/test" page, create a script to check for the value on the localStorage then display it.
data = JSON.parse(localStorage.myAjaxResponse);
console.log(data);
$("#count").text("we analyzed...");
$("#result1").text(data.county);
$("#totals").text("with a score of..");
$("#result2").text(data.totalSentiments);
Although, there are other better ways to accomplish what you want.
You can do something like this:
On your ajax success:
data = JSON.parse(data);
console.log(data);
window.location.href = '/test?county='+data.county+'&sentiment='+totalSentiments;
Then on your test page write in javascript block:
var params={};
window.location.search
.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str,key,value) {
params[key] = value;
}
);
if (params.length > 0) {
$("#count").text("we analyzed...");
$("#result1").text(params['county']);
$("#totals").text("with a score of..");
$("#result2").text(params['sentiments']);
}

How to render MVC 4 view on slickgrid double click via Javascript

I am using MVC4 along with slickgrid to display data to the user. I am trying to implement the ability to double click on a slickgrid row and have the page go to another view, but all I am able to get is the HTML returned to the client, but not rendered.
I am doing,
grid.onDblClick.subscribe(function (e, args) {
$.get(
"MapSetEdit/Edit/",
{ 'mapSetId': 1 }
);
});
and I have also tried:
grid.onDblClick.subscribe(function (e, args) {
$.ajax({
type: "GET",
url: "MapSetEdit/Edit/",
dataType: 'text',
data: {'mapSetId': 1}
})
.fail(function () {
console.log("Error retreiving map list.");
});
});
All this does is return the html to the browser but never renders it. How do I make a javascript request so that I am able to actually render the view. I think I am missing something obvious here as I am new to javascript and mvc.
You should render the returned HTML with jQuery. For example:
grid.onDblClick.subscribe(function (e, args) {
$.ajax({
type: "GET",
url: "MapSetEdit/Edit/",
dataType: 'text',
data: {'mapSetId': 1}
})
.succes(function(data){
var someemptydiv = $("#myEmptyDiv");
someemptydiv.html(data);
})
.fail(function () {
console.log("Error retreiving map list.");
});
});
I was able to do what I needed with:
grid.onDblClick.subscribe(function (e, args) {
window.location = '/MapSetEdit/Edit/?mapSetId=1'
});

Categories

Resources