How to concate function parameter value into object literal property name - javascript

I have the following JS code (also I use jQuery):
jQuery(function($) {
$(".to_manufacturer").click(function() {
var checked = $(this).is(':checked');
var man_id = $(this).attr("to_manufacturer_id");
update_is_in_to(man_id, "to_manufacturer", checked)
});
$(".to_model").click(function() {
var checked = $(this).is(':checked');
var man_id = $(this).attr("to_model_id");
update_is_in_to(man_id, "to_model", checked)
});
$(".to_type").click(function() {
var checked = $(this).is(':checked');
var man_id = $(this).attr("to_type_id");
update_is_in_to(man_id, "to_type", checked)
});
function update_is_in_to (man_id_val, modelname, checked_val) {
$.ajax({
url: "/admin/catalog/to/"+modelname+"s/ajax/update_is_in_to",
type: "GET",
data: {id: man_id_val, modelname_is_in_to_val: checked_val},
success: function(text)
{
//$("#total_count").html(text + " товар(ов)");
},
error: function(){
alert('Ошибка обновления объекта с id = '+man_id_val+' ! Очередная попытка...');
$.ajax(this);
},
dataType : "html"
});
}
});
How can I make it so that my param modelname_is_in_to_val is composite, where the first part is the method param modelname and second is the string "_is_in_to_val"?
I tried modelname + "_is_in_to_val" but I received errors. What is it right to do it?
Also is not my code to violate according js conventions?

You'll need to use bracket notation and build your object outside the function:
function update_is_in_to (man_id_val, modelname, checked_val) {
var data = {};
data.id = man_id_val;
data[modelname + '_is_in_to_val'] = checked_val;
$.ajax({
...
data: data,
...
});
}

You can't do it directly in the object literal syntax. You'll need to create the object first, then add that property using the square bracket version of the member operator. This lets you evaluate an expression, and use its result as the property name.
function update_is_in_to (man_id_val, modelname, checked_val) {
var data = {id: man_id_val};
data[modelname + "_is_in_to_val"] = checked_val;
$.ajax({
url: "/admin/catalog/to/"+modelname+"s/ajax/update_is_in_to",
type: "GET",
data: data,
success: function(text)
{
//$("#total_count").html(text + " товар(ов)");
},
error: function(){
alert('Ошибка обновления объекта с id = '+man_id_val+' ! Очередная попытка...');
$.ajax(this);
},
dataType : "html"
});
}

Related

calling objects of functions in constructor in javascript

guys i know it is dummy question but i tried a lot and never reached .. here is my code in jsp
<button type="button" onclick="loadDepartment();" id="dep">Departments</button>
function deleteDep(id){
$.ajax({
url : '/Spring3HibernateApp1/deleteDep',
type : 'GET',
data : {
"id" : id,
},
dataType : "json"
});
}
function loadDepartment(){
$( document ).ready(function() {
$.ajax({
url : '/Spring3HibernateApp1/indexDep',
type : 'GET',
error : function(that, e) {
alert(e);
},
success : function(data) {
var newData = data.MyListDep;
gridDep = new GridLibraryDep({data: newData, deletefunction: deleteDep(id)});
gridDep.display();
}
});
});
}
and in JS
function GridLibraryDep(data, deletefunction) {
this.data = data.data;
this.deletefunction = deletefunction.deletefunction(id);
}
GridLibraryDep.prototype = {
deleteRow : function() {
$("input:checkbox:checked").each(bindContext(function(index, item) {
var str = $(item).attr("id");
str = str.substring(str.indexOf("_") + 1);
var id = this.data[str][this.columns[1]];
this.deletefunction(id);
this.data.splice(str, 1);
this.deleteTable();
this.display();
}, this));
}}
i want to access the deletefunction in jsp and use it in js .. but it gives em id not defined in jsp .. any suggestions ??
You are doing it overcomplicated and wrong.
Correct this line:
gridDep = new GridLibraryDep({data: newData, deletefunction: deleteDep(id)});
to:
gridDep = new GridLibraryDep(newData, deleteDep);
And the constructor:
function GridLibraryDep(data, deletefunction) {
this.data = data.data;
this.deletefunction = deletefunction.deletefunction(id);
}
to:
function GridLibraryDep(data, deletefunction) {
this.data = data;
this.deletefunction = deletefunction;
}
Now the declared and passed parameters match and the function is passed instead of function call result.

How to post a form with ajax and return data in array?

HI how to post a form and return data it will be a array as like this
{
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
}
My code is this
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
var formValidate = $('#add-menu-list').parsley().validate();
validateFront();
// console.log(formValidate);
var menuName = $('input[data-api-attr=menuItemName]').val();
var validUntil = $('input[data-api-attr=validUntil]').val();
var menuStatus = $('input[data-api-attr=status]').val();
var menuNote = $('textarea[data-api-attr=notes]').val();
var menuDesc = $('textarea[data-api-attr=menuItemDesc]').val();
var dataString = {
menuItemName: menuName,
validUntil : validUntil,
status : menuStatus,
notes : menuNote,
menuItemDesc : menuDesc
};
if(formValidate == true){
alert('success');
console.log(menuName + validUntil + menuStatus + menuNote + menuDesc);
var url = "xyz.html"; // the script where you handle the form input.
$.ajax({
type: "POST",
// url: url,
dataType: "json",
data: $(dataString).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response
}
});
}else{
alert('Validation fail ');
}
});
Since "data" is a server response i guess that your server return a json object. In this case you have to somehow inform the jquery's ajax that you expect a json response from server or you have to translate the "data" to a json object by your self.
It is best to follow the first option so you don t have to deal with the translation your self you can easily do that by giving an extra parameter tou your ajax reuest : dataType: 'json', this will do the trick!
Now that you have a proper response object from your request you can either stringify it with var string_resp=JSON.stringify(data); and then alert it alert(string_resp) or you can access its elements like that : alert(data.status) which will alert your object's status field etc.
so your code will be :
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $(menuName).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // will alert an object
alert(data.status); // will alert object's status field in this case 1
alert(JSON.stringify(data)) // will alert the object as a string
}
});
you are sending only one value in serialize, serialize() should be on form element not on field element, like :
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
...
$.ajax({
...
data:$("#form").serialize();
...
success: function(data)
{
alert(data.notes); // show response
....
}
var myObj = {
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
};
myObj.toString = function()
{
var str = '';
for (var property in myObj)
{
if (myObj.hasOwnProperty(property) && (property != "toString") )
{
str += (property + ': ' + myObj[property] + "\n");
// do stuff
}
}
return str;
}
alert(myObj);

Returning an object from Web Service to Ajax Request success callback function

Hello Fellow Developers,
I have a SSN textbox that onblur calls a function which does an ajax request to a Web Method to decide if an employee has been previously hired.
The Web Method returns a TermedEmployee Object to the success callback, but I'm unsure how to parse the object.
$('#<%=FormView1.FindControl("SSNField").ClientID%>').blur(hideValue);
hideValue = function (ev) {
var $this = $(this);
$this.data('value', $this.val());
$('#<%=FormView1.FindControl("hiddenSSN").ClientID%>').val($this.val());
var data2Send = '{"SSN": ' + $this.val() + ' }';
$.ajax({
type: "POST",
url: "AuthforHire.aspx/EmployeeisRehire",
data: data2Send,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var obj = JSON.stringify(result.d);
if (obj.IsTermed) {
$('#%=RadWindowRehire.ContentContainer.FindControl("TextBoxTermID").ClientID%>').val(arg.d);
var wndWidth = 900;
var wndHeight = 500;
var wnd = window.radopen(null, "RadWindowRehire");
}
},
error: function (xhr) {
alert('Form update failed. '); //error occurred
}
});
Below is a minified version of my webMethod, which works correctly
[System.Web.Services.WebMethod]
public static TermedEmployee EmployeeisRehire(string SSN)
{
TermedEmployee termedEmp = new TermedEmployee();
// Db call to get necessary data.
termedEmp.Name = dr["name"];
termedEmp.TermDate = Convert.ToDateTime(dr["TermDate"].ToString());
......
}
So How Can I extract Name, TermDate,StartDate, ReasonforTerm, etc from the object returned to the callback function?
Thank you in advance!
The first line in your success callback is:
var obj = JSON.stringify(result.d);
Which is trying to serialize what ASP.Net will already have serialized for you.
Change this to:
var obj = result.d;
And you will then have access to obj.Name, obj.TermDate and all the other properties by name.

How do I get the changed element in a multiselect, using KendoUI?

I have a multiselect-list that acts as holder for a list of tags. I can't seem to figure out how to properly get the value of the item being changed and passed along with the changed-event. Here's my Kendo multiselect:
#(Html.Kendo().MultiSelect()
.Name("tags")
.Placeholder("No tags selected for this unit")
.BindTo(new SelectList(Model.TagsAvailable))
.Events(e => e
.Select("select")
.Change("change"))
.Value(Model.TagsSelected.ToArray())
)
And here are my js-methods:
function select(e) {
var dataItem = this.dataSource.view()[e.item.index()];
var param = dataItem.Text;
var url = '/UnitDetails/TagUnit/#Model.UnitId';
$.ajax({
url: url,
data: { selectedItem: param },
type: 'GET',
dataType: 'json',
success: function (data) {
// ...
},
error: function () {
// ...
}
});
};
function change(e) {
var dataItem = this;
var param = dataItem.element.context.innerText;
var url = '/UnitDetails/UnTagUnit/#Model.UnitId';
$.ajax({
url: url,
data: { selectedItem: param },
type: 'GET',
dataType: 'json',
success: function (data) {
// ...
},
error: function () {
// ...
}
});
};
My problem beeing that I feel the assignment of param is just quick and dirty. Surely, there must be some other, more correct way of going about this?
There is no easy way (afaik) for knowing the changes. So, let do it by ourselves.
First, I'm going to save the old value using the following function.
function saveCurrent(multi) {
multi._savedOld = multi.value().slice(0);
}
Where multi is the multi-select that we pass to the function as argument (so you can use the function for multiple multiselects).
Then, you need to implement change as follow:
change : function (e) {
// Retrieve previous value of `multiselect` saved using previous function
var previous = this._savedOld;
// These are current values.
var current = this.value();
// Let's save it for the next time
saveCurrent(this);
// The difference between previous and current are removed elements
var diff = $(previous).not(current).get();
console.log("removed", diff);
// The difference between current and previous, are added elements
diff = $(current).not(previous).get();
console.log("added", diff);
}
Running example here http://jsfiddle.net/OnaBai/MapVN/
Nice answer OnaBai! very useful and helpful.
I had the same Nickla's problem.
But, I needed to "save current values" at dataBound event. And it works (logging the changed values).
If you start deleting an item, it fails because the function recognizes the "change" as an "item add".
This is what I did
function dataBound(ev) {
saveCurrent(this);
}
function saveCurrent(multi) {
multi._savedOld = multi.value().slice(0);
}
function change(ev) {
var previous = this._savedOld;
var current = this.value();
saveCurrent(this);
var diff = $(previous).not(current).get();
console.log("removed", diff);
var removedSkill = diff;
console.log("removedSkills", removedSkill);
diff = $(current).not(previous).get();
var addedSkill = diff;
console.log("added", diff);
console.log("addedSkills", addedSkill);
if (addedSkill.length > 1 || removedSkill.length > 1) {
if (addedSkill.length > 1) {
addedSkill = addedSkill[addedSkill.length - 1];
alert("Added skill code: " + addedSkill.toString());
}
if (removedSkill.length > 1) {
removedSkill = removedSkill[removedSkill.length - 1];
alert("Removed skill code: " + removedSkill.toString());
}
}
else {
if (addedSkill.length > 0) {
alert("Added skill code: " + addedSkill.toString());
}
if (removedSkill.length > 0) {
alert("Removed skill code: " + removedSkill.toString());
}
}
$.ajax({
url: "SomeUrl",
type: "POST",
dataType: "json",
contentType: "application/json",
data: JSON.stringify({ removedSkill: removedSkill, addedSkill: addedSkill })
});
}
Thanks again!
Iván

Post with ajax-jquery send blank space when the sentence have +

I am sending a request by post using jquery ajax, but some of the words i send have + to join words like: HTA+HIPERAQUITISM+DBLR, the php recieve HTA HIPERAQUITISM DBLR changing the + by blank spaces, i post the code below. help!
function getItemInfo(itemName, itemField, itemComparative, itemTable){
var result = "";
var nombreItem = itemName;
var campoItem = itemField;
var comparativeItem = itemComparative;
var tableItem = itemTable;
$.ajax({
type: 'POST',
async: false,
url: 'modules/medicos/controller.php?fun=consul_item&nombre_item=consul_item'+
'&nombre_item='+nombreItem+
'&campo='+campoItem+
'&comparador='+comparativeItem+
'&tabla='+tableItem,
success: function(data) {
result = data.toString();
},
failure: function() {
result = "";
}
});
return result;
}//end function
This is because in a URL + means space.
You'll need to URL encode the data first before adding it to the query string.
You can use the encodeURIComponent() function to encode your value before adding it to the query string.
Once your PHP code picks it up you can then decode the value with the urldecode function
So your code should update to something like this:
url: 'modules/medicos/controller.php?fun=consul_item&nombre_item=consul_item'+
'&nombre_item='+encodeURIComponent(nombreItem)+
'&campo='+encodeURIComponent(campoItem)+
'&comparador='+encodeURIComponent(comparativeItem)+
'&tabla='+encodeURIComponent(tableItem),
Your code seems to be correct. You are passing those variables one by one (nombreItem, campoItem, comparativeItem and tableItem). So I don't really understand what you say is not working.
A suggestion to make passing data easier:
$.ajax({
type: 'POST',
async: false,
url: 'modules/medicos/controller.php',
data : ({ fun : consul_item,
nombre_item : nombreItem,
campo : campoItem,
comparador : comparativeItem,
tabla : tableItem }),
success: function(data) {
result = data;
},
failure: function() {
result = "";
}
});
If you want to pass all your info as one textual string you should do:
...
data: ({ test : consul_item + '+' + nombreItem + '+' + campoItem + '+' + comparativeItem + '+' + tableItem }),
...

Categories