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.
Related
GetMandatoryFieldsforUser: function (data) {
var field = [];
$.get("api/mapping/mandatoryfield?type=USER", function (data) {
var self = this;
self.dt = [];
self.firmdata = JSON.parse(data.Data);
console.log(self.firmdata);
self.firmdata.forEach(function (item) {
field.push(item.DisplayName);
})
console.log(field) //able to print value
})
console.log(field) // not able to print value
return MandatoryFields.User;
},
EDIT
MandatoryFields = {
User: field,
}
my question here is i need to access field value outside forEach loop.How to achieve this using jquery or javascript
EDIT
"api/mapping/mandatoryfield?type=USER" returns
["First Name", "Last Name", "Location", "Email", "Password"],
see the edited question i want to use that field array inside MandatoryFields.User but if i use it its not showing the value
This implements $.ajax:
GetMandatoryFieldsforUser: function (data) {
var field = [];
$.ajax({
url: "api/mapping/mandatoryfield?type=USER"
}).done(function(data) {
// THIS PORTION IS EXECUTED AFTER DATA IS LOADED
var self = this;
self.dt = [];
self.firmdata = JSON.parse(data.Data);
console.log(self.firmdata);
self.firmdata.forEach(function (item) {
field.push(item.DisplayName);
})
console.log(field)
/*
USE return HERE!
*/
return field; // OR SOMETHING ELSE
})
// THIS WON'T WORK, BECAUSE DATA IS RETRIEVED IN ASYNC!
console.log(field)
},
Since $.get() is an asynchronous method, you can use async/await to access the returned value from the $.get method's callback.
GetMandatoryFieldsforUser: async function (data) {
var field = [];
const returnedField = await $.get("api/mapping/mandatoryfield?type=USER", function (data) {
var self = this;
self.dt = [];
self.firmdata = JSON.parse(data.Data);
console.log(self.firmdata);
self.firmdata.forEach(function (item) {
field.push(item.DisplayName);
})
console.log(field) //able to print value
return field;
}).promise()
console.log(returnedField) // not able to print value
},
You should use the ajax method in jquery.
function GetMandatoryFieldsforUser( data)
{
var field= [];
var scriptUrl = "api/mapping/mandatoryfield?type=USER";
$.ajax({
url: scriptUrl,
type: 'get',
dataType: 'html',
async: true,
success: function(data) {
var self = this;
self.dt = [];
self.firmdata = JSON.parse(data.Data);
console.log(self.firmdata);
self.firmdata.forEach(function (item) {
field.push(item.DisplayName);
})
console.log(field)
}
});
return field;
}
I have 2 arrays in my Razor view. The first one checked checkboxes and the second is for unchecked. I can send one of them but I don't know how to send both of them. This is my jQuery code:
$(document).ready(function() {
$("#checkAll").click(function() {
$(".checkBox").prop('checked', $(this).prop('checked'));
});
$("#confrim").click(function() {
var selectedIDs = new Array();
var unseletedeIDs = new Array();
$('input:checkbox.checkBox').each(function() {
if ($(this).prop('checked')) {
selectedIDs.push($(this).val());
} else {
unseletedeIDs.push($(this).val());
}
});
var options = {};
options.url = "/Parts/ConfrimAll";
options.type = "POST";
options.data = JSON.stringify(selectedIDs);
options.contentType = "application/json";
options.dataType = "json";
options.success = function(msg) {
alert(msg);
};
options.error = function() {
alert("Error!");
};
$.ajax(options);
});
});
This is the action:
public ActionResult ConfrimAll(int?[] selectedIDs, int?[] unSelectedIDs)
{
if (selectedIDs!=null)
{
foreach (int id in selectedIDs)
{
Part obj = db.Parts.Find(id);
obj.IsOk = true;
db.Entry(obj).State = EntityState.Modified;
}
}
if (unSelectedIDs!=null)
{
foreach (int id in unSelectedIDs)
{
Part objs = db.Parts.Find(id);
db.Parts.Remove(objs);
}
}
db.SaveChanges();
return Json("yes");
}
Have you tried this?
JSON.stringify({ selectedIDs: selectedIDs, unseletedeIDs: unseletedeIDs });
You should have the two parameters selectedIDs and unseletedeIDs in the Action filled with this.
You can provide both array as part of an object to the data parameter of the $.ajax call. Try this:
$("#confrim").click(function() {
var data = {
SelectedIDs: [],
UnSelectedIDs: [],
}
$('input:checkbox.checkBox').each(function() {
data[this.checked ? 'SelectedIDs' : 'UnSelectedIDs'].push(this.value);
});
$.ajax({
url: '/Parts/ConfrimAll',
type: 'POST',
data: data,
success: function(msg) {
console.log(msg);
},
error: function(x, s, e) {
console.log('Error!');
console.log(x, s, e);
}
});
});
Note that it's much better practice to provide an object to the data parameter as jQuery will then encode it for you to the required format, escaping any special characters as it does it.
I'm trying to read p_info array returned from the function getproductInfo containing a ajax call but I'm getting undefined value. I'm using a callback function to achieve this but still doesn't work. Where am I wrong?
$(document).ready(function() {
function successCallback(data)
{
var name = data.name;
var image = data.image;
var link = data.link;
var product_info = [name, image, link];
console.log(product_info); // Correct: shows my product_info array
return product_info;
}
function getProductInfo(prodId, successCallback) {
$.ajax({
type: "POST",
url: "getProductInfo.php",
data: "id=" + prodId,
dataType: "json",
success: function(data) {
var p_info = successCallback(data);
console.log(p_info); // Correct: shows my product_info array
return p_info;
},
error: function()
{
alert("Error getProductInfo()...");
}
});
return p_info; // Wrong: shows "undefined" value
}
var p_info = getProductInfo(12, successCallback);
console.log(p_info); // Wrong: shows an empty value
});
The code should speak for itself. But basically, you cant return an upper-level function inside a function. You must set a variable to be used to return after the ajax is submitted.
//This makes the p_info global scope. So entire DOM (all functions) can use it.
var p_info = '';
//same as you did before
function successCallback(data) {
var name = data.name;
var image = data.image;
var link = data.link;
var product_info = [name, image, link];
return product_info;
}
//This takes prodID and returns the data.
function getProductInfo(prodId) {
//sets up the link with the data allready in it.
var link = 'getProductInfo.php?id=' + prodId;
//creates a temp variable above the scope of the ajax
var temp = '';
//uses shorthand ajax call
$.post(link, function (data) {
//sets the temp variable to the data
temp = successCallback(data);
});
//returns the data outside the scope of the .post
return temp;
}
//calls on initiates.
var p_info = getProductInfo(12);
console.log(p_info);
As asked, i have updated the code to my specific issue:
function A(){
this.data1 = null;
this.data2 = null;
}
A.prototype.receiveData1AndData2FromServer = function(callback){
this.doneCallback = $.proxy( function foo(importantData, callback){
this.data1 = importantData.data1;
this.data2 = importantData.data2;
callback != undefined ? callback() : null;
}, this, callback);
checkFail = $.proxy(
function (jqXHR, textStatus, errorThrown) {
try {
var str = new String(jqXHR.responseText);
var result = JSON.parse(str.substring(str.indexOf('{')));
this.doneCallback(result);
} catch (ex) { console.log(ex); }
}
, this);
$.ajax({
type: 'POST', url: 'get_data1_and_data2.php', data: { 'id': this.id }, dataType: 'json'
}).done(this.doneCallback)
.fail(checkFail);
}
(The problem is that the callback parameter is replacing the first parameter(importantData) instead of the second.)
There are calls with different callback parameter to A::receiveData1AndData2FromServer.
I want to pass the callback to A::doneCallback, so when the retrieval is done, the right callback will be called.
Your question is not very clear, but jQuery.proxy() supports multiple arguments since version 1.6
I have found the solution after some thinking.
Splitting the context argument into an object with multiple fields(context and desired arguments) had solved it. I hope it will be useful for someone else.
function A(){
this.data1 = null;
this.data2 = null;
}
A.prototype.receiveData1AndData2FromServer = function(callback){
this.doneCallback = $.proxy( function foo(importantData, callback){
this.context.data1 = importantData.data1;
this.context.data2 = importantData.data2;
this.callback.callback != undefined ? this.callback() : null;
}, {context:this, callback:callback});
checkFail = $.proxy(
function (jqXHR, textStatus, errorThrown) {
try {
var str = new String(jqXHR.responseText);
var result = JSON.parse(str.substring(str.indexOf('{')));
this.doneCallback(result);
} catch (ex) { console.log(ex); }
}
, this);
$.ajax({
type: 'POST', url: 'get_data1_and_data2.php', data: { 'id': this.id }, dataType: 'json'
}).done(this.doneCallback)
.fail(checkFail);
}
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"
});
}