I am using jQuery to save the values of my javascript objects. I need to retreive the ID of inserted object from the database. I know how to do it, if the Save function is within the javascript object (see code below). But how can I set the ID variable, if the Save function is not in the javascript object?
Working:
Person = function() {
var self = this;
self.ID;
self.Name;
self.SurName;
self.Save = function() {
$.ajax({
type: "POST",
url: "Save",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ Name: self.Name, SurnName: self.SurName }),
dataType: "json",
success: function (result) {
var ID = result.d.ID; //this is the ID retreived from database
self.ID = ID; //set the ID, it works, since I can reference to self
}
});
};
}¨
So how would I now implement a function (outside the Person class!) like:
SavePerson = function(p) {
$.ajax({
type: "POST",
url: "Save",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ Name: p.Name, SurnName: p.SurName }),
dataType: "json",
success: function (result) {
var ID = result.d.ID; //this is the ID retreived from database
p.ID = ID; //set the ID, it doesn't work, becouse if I call SavePerson repetedly for different objects, a p will not be a correct person.
}
});
};
Just to clarify, you would like the Person object id property to be updated with the recent save? If so the following script would suffice. I have used deferred's to ensure that p.ID is only updated upon completion of the asynchronous request.
$.Person = function() {
var self = this;
self.ID;
self.Name;
self.SurName;
}
$.SavePerson = function() {
var dfd = $.Deferred();
$.ajax({
type: "POST",
url: "Save",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ Name: p.Name, SurnName: p.SurName }),
dataType: "json",
success: dfd.resolve
});
return dfd.promise();
};
var p = new $.Person();
$.SavePerson().then(function(result){
p.ID = result.d.ID;
});
There may be better ways to do this but I'd have my database also return the Name and Surname along with the ID, then search my Person list to find the correct object in the success function.
Perhaps this is what you desire?
I borrowed some code here:
/*** makeClass() ***
* The following allows us to easily create
* Javascript classes. Source of this:
* http://ejohn.org/blog/simple-class-instantiation/
* makeClass - By John Resig (MIT Licensed)
*/
function makeClass() {
return function(args) {
if (this instanceof arguments.callee) {
if (typeof this.init == "function") this.init.apply(this, args.callee ? args : arguments);
} else return new arguments.callee(arguments);
};
});
/* set up ajax */
$.ajaxSetup({
async: false,
type: "POST",
contentType: "application/json",
converters: {
"json jsond": function(msg) {
return msg.hasOwnProperty('d') ? msg.d : msg;
}
},
data: '{}',
dataType: "json",
error: function(jqXHR, status, error) {
alert("An error occurred on the server. Please contact support.");
}
});
/* set up my person class */
var personClass = makeClass();
personClass.prototype.init = function() {
this.ID = '';
this.SurName = '';
this.Name = '';
}
/* create my save function */
personClass.prototype.SavePerson = function(p) {
this.Name = (typeof p === 'undefined') ? this.Name : p.Name;
this.SurName = (typeof p === 'undefined') ? this.SurName : p.SurName;
$.ajax({
url: "Save",
data: JSON.stringify({
Name: this.Name,
SurnName: this.SurName
}),
success: function(result) {
var ID = result.ID; //ID from database
this.ID = ID; //set the ID,
}
});
};
//create two persons
var person1 = personClass();
var person2 = personClass();
//set person1 to be fred
person1.Name = "Fred";
person1.SurName = "Flintstone";
// independent person
var p = {Name: "Barney", SurName: ""};
p.Surname = "Rubble";
//save specific and the independent (as person2)
person1.SavePerson();
person2.SavePerson(p);
//alert the ID of both
alert(person1.ID + ":" + person2.ID);
Related
I try to send two arrays to the controller, each array from a different class. But all I get is alert with an error message. What am I doing wrong? When I send only one array in ajax data, it is obtained fine in the first array of the controller.
my code js:
$("#Button2").click(function () {
var dict = new Array();
$(":checkbox").each(function () {
if ($(this).prop("checked")== true) {
var key = this.name
if ($("input[name = 'r" + key + "']").length) {
dict.push({
Code: key,
Reccomendation: $("input[name = 'r" + key + "']").prop("value"),
});
}
else{
dict.push({
Code: key,
Reccomendation: $(this).prop("value"),
});
}
}
}) //end function each
var dict2 = new Array();
dict2.push({
Mentioned: $("#yesno").val(),
FollowUp: $("#Follo").val(),
UpdateCode:5
})
$.ajax({
type: 'POST',
url: "#Url.Action("SavevisitSummary")",
traditional: true,
dataType: 'JSON',
contentType: 'application/json; charset=utf-8',
data: { 'a': JSON.stringify(dict), 'b': JSON.stringify(dict2) },
success: function () {
alert("sucssec")
},
error:function(){
alert("error")
}
})
})
controller looks like:
public ActionResult SavevisitSummary(Reccomendations[] a, Summary[] b) { }
This is my view model:
function viewModel() {
var self = this;
self.posts = ko.observableArray();
self.newMessage = ko.observable();
self.error = ko.observable();
and these are my two loads functions:
self.reloadPosts = function () {
$.ajax({
type: "Get",
url: postApiUrl2,
data: { id: $("#Locations").val() },
datatype: "json",
contentType: "application/json"
})
}
self.loadPosts = function () {
// to load existing posts
$.ajax({
url: postApiUrl1,
// data: { id: $("#Locations").val() },
datatype: "json",
contentType: "application/json",
cache: false,
type: 'Get'
})
}
self.loadPosts();
self.reloadPosts();
return self;
here, self.loadPosts is the function with no parameter in it and self.reloadPosts passes selected dropdown id to controller.
My question is-- is it possible to put condition here so that self.reloadPosts should only load data on the view page when it has some data.
Right now, both of these are loading one by one. i want to control it by some condition.this code is in .js file not on .cshtml page.
I am trying something like this but getting uncaught reference errror at first line:
if (id != null) {
self.reloadPosts();
}
else {
self.loadPosts();
}
Can anyone suggest me something how to do it.
I don't know what #locations refers to, but if it's a select list or something try this in the HTML (for example):
<select data-bind="value: locations">
<option>location 1</option>
<option>location 2</option>
<select>
And change the script:
function viewModel() {
var self = this;
// location will be stored here
self.locations = ko.observable();
self.posts = ko.observableArray();
self.newMessage = ko.observable();
self.error = ko.observable();
// we can avoid some repeat code:
self.loadPosts = function () {
// read value
var id = self.locations();
// set url and data
var url = (id) ? postApiUrl2 : postApiUrl1;
var data = (id) ? { id: id } : null;
$.ajax({
type: "Get",
url: url,
data: data,
datatype: "json",
contentType: "application/json"
})
}
self.loadPosts();
return self;
Hope this helps.
I've got an array of Objects in jQuery:
function customersList() {
this.selectedCustomers = [];
}
function customerObject(customerId, bookingId) {
this.customerId = customerId;
this.bookingId = bookingId;
}
I need to post this to my Controller:
[HttpPost]
public ActionResult CreateMultipleCasesFormPost(CreateMultipleCasesModel model)
{
return PartialView("_CreateMultipleCases", model);
}
My ViewModel:
public class CreateMultipleCasesModel
{
[Display(Name = "Selected Customers")]
public List<CustomerList> Customers { get; set; }
I need to pass the Array from jQuery and the Data from this Form to my Controller (My View Model contains other properties):
$('#createMultipleCasesForm')
This is my Post Form jQuery Code:
$('#createMultipleCasesBtn').click(function () {
var btn = $(this);
var mUrl = btn.data('actionurl');
var formModel = $('#createMultipleCasesForm').serializeArray();
var customerList = customersList.selectedCustomers();
var requestData = {
model: formModel,
Customers: customerList
};
var sData = JSON.stringify(requestData);
$.ajax({
url: mUrl,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: sData,
success: function (response) {
debugger;
},
error: function (response) {
$('#ErrorMessage').html('<span class="icon black cross"></span>' + response.Message);
}
});
});
My Model from jQuery is not Binding either the Array of Customer Objects or the Form, What am I doing wrong here?
EDIT
What happens when I post Back my Form:
I found a solution this did the trick for me:
$('#createMultipleCasesBtn').click(function () {
var btn = $(this);
var mUrl = btn.data('actionurl');
var formModel = $('#createMultipleCasesForm').serializeObject();
formModel['Customers'] = customersList.selectedCustomers;
var sData = JSON.stringify(formModel);
$.ajax({
url: mUrl,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: sData,
success: function (response) {
},
error: function (response) {
$('#ErrorMessage').html('<span class="icon black cross"></span>' + response.Message);
}
});
});
This Function Below Used from Answer Here: Convert form data to JavaScript object with jQuery
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
I have the following:
var q = new app.models.OverwriteLineItemsProcess();
q.set('id', $("#process_id").val());
q.saveSource($("#source_quote").val());
q.lockSource();
saveSource is sending data to the backend using ajax. So is lockSource.
I want to execute in this SEQUENTIAL manner: saveSource >> lockSource.
How do I write the q.js to make it work?
By q.js, I mean https://github.com/kriskowal/q
UPDATE: added saveSource and lockSource
saveSource: function (quotation_id) {;
var type = "PUT";
var verb = "Updated";
var headers = {
'X-HTTP-Method-Override': type
};
var url = app.base_url + "/overwrite_line_items/" + this.id;
this.set('source_quote', quotation_id);
var data = this.toFormData();
var result = false;
var currentModel = this;
var settings = {
headers: headers,
type: type,
url: url,
data: data,
success: function(json) {
response = JSON && JSON.parse(json) || $.parseJSON(json);
console.log(response);
currentModel.lockSource();
$("#facebox-source-quote-status").html('<font color="green">SELECTED</font>');
},
error: function(response) {
$("#facebox-source-quote-status").html('<font color="red">UNABLE TO SELECT</font>');
},
dataType: 'json'
};
$.ajax(settings).done(function() {
});
},
lockSource: function () {
var type = "PUT";
var verb = "Updated";
var headers = {
'X-HTTP-Method-Override': type
};
var url = app.base_url + "/quotations/is_editable/" + this.attributes.source_quote;
var data = this.toFormData();
var result = false;
var currentModel = this;
var settings = {
headers: headers,
type: type,
url: url,
data: data,
success: function(response) {
console.log(response);
},
error: function(response) {
$("#facebox-source-quote-status").html('<font color="red">UNABLE TO SELECT</font>');
},
dataType: 'json'
};
$.ajax(settings).done(function() {
});
},
The jQuery.ajax function which you're using already returns a promise for its result. You just need to return that from your functions:
saveSource: function (quotation_id) {;
…
var settings = {
headers: headers,
type: type,
dataType: 'json', // jQuery will automatically parse it for you
url: url,
data: data
};
return $.ajax(settings).done(function() {
// ^^^^^^
$("#facebox-source-quote-status").html('<font color="green">SELECTED</font>');
// notice I did remove the currentModel.lockSource(); call from the callback
}, function() {
$("#facebox-source-quote-status").html('<font color="red">UNABLE TO SELECT</font>');
});
},
lockSource: function () {
…
var settings = // analoguous, no callbacks here
return $.ajax(settings).fail(function(response) {
$("#facebox-source-quote-status").html('<font color="red">UNABLE TO SELECT</font>');
});
}
Now you can easily chain them:
var q = new app.models.OverwriteLineItemsProcess();
q.set('id', $("#process_id").val());
q.saveSource($("#source_quote").val()).then(function(saveResponse) {
console.log(saveResponse);
return q.lockSource();
}).done(function(lockResponse) {
console.log(lockResponse);
});
You don't even need Q for that. If you want to use it, wrap the $.ajax() calls in a Q() invocation, as explained in the Converting JQuery Promises to Q section of the docs.
I have the following javascript:
$('#edit_category').on('click','#btn_save_category_name',function(){
currently_edit.text($('#txt_edit_category').val());
edit_category_name(currently_edit,current_category_id);
$('#edit_category').modal('hide')
})
function edit_category_name(name, id){
$.ajax({
type: 'POST',
url: '/Category/edit_team_category',
dataType: 'json',
data: {
request: 'ajax',
name: name,
id: id
},
success: function (data) {
}
});
}
Now when i attempt this i get the following error: called 'click' called on an object that does not implement interface HTMLElement.
But if i comment the function line out aka : edit_category_name(currently_edit,current_category_id);
everything works fine.
Can anyone tell me why this is happening?
Update my full script
var mode = 'team';
var currently_edit = '';
var current_team_id = 0;
var current_category_id = 0;
jQuery(document).ready(function(){
//Main click function for Team (selection of team)
$('#team_wrapper').on('click', '.panel-heading', function () {
if(mode === 'team'){
current_team_id = $(this).siblings('small').text()
title = $(this).find('.text-white').text();
var i = 100;
$('#span_search').hide();
$('#btn_new_team').fadeOut();
$('.col-lg-3').each(function(){
$('.alt').toggle('slow');
$(this).fadeOut(300,function(){
$(this).remove();
});
});
$('#team_title').text('Select Category');
$('#btn_new_category').delay(500).fadeIn();
$('#selected_team_name').text(title);
$('#selected').delay(695).fadeIn();
$('#span_search').delay(500).fadeIn();
$('#back').delay(500).fadeIn();
generate_categories();
mode = 'category';
}else{
$(this).next('div').find('a')[0].click();
}
})
$('#team_wrapper').on('click', '.btn_administrate', function(){
current_team_id = $(this).next('.team_id').text();
load_team_members(current_team_id);
});
//Modal category:
//create
$('#btn_create_category').click(function(){
add_category($('#txt_create_category').val());
$('#group-form').modal('hide');
$('#txt_create_category').val('');
})
// edit
$('#team_wrapper').on('click','.team_category_edit',function(){
current_category_id= $(this).next('input').val()
edit_mode('txt_edit_category',$(this).closest("div").prev().find("h3"));
})
$('#edit_category').on('click','#btn_save_category_name',function(){
currently_edit.text($('#txt_edit_category').val());
edit_category_name(currently_edit,current_category_id);
$('#edit_category').modal('hide')
})
});
function edit_category_name(name, id){
$.ajax({
type: 'POST',
url: '/Category/edit_team_category',
dataType: 'json',
data: {
request: 'ajax',
name: name,
id: id
},
success: function (data) {
}
});
}
in this example:
var current_team_id = 1;
var current_category_id = 2;
What is the value of currently_edit? I am assuming this is a jQuery object not a text value. Try the following instead.
edit_category_name(currently_edit.text(),current_category_id);
Update
As Barmar mentioned, currently_edit.text(...) is invalid based on what you have shared. perhaps what you meant to do was:
currently_edit = $('#txt_edit_category').val();
Try changing this line currently_edit.text($('#txt_edit_category').val());
with this : currently_edit = $('#txt_edit_category').val();