How to keep values of variable? - javascript

I don't know I can't access to values of the variable in Javascript.
urli have values like: https://cors.io/?https://tb.rg-adguard.net/php/get_edition.php?version_id=11&lang=name_en
But I tried to print values of name_lang with console.log(this.namelang) but it shows undefine
Here my code:
var urli = 'https://cors.io/?https://tb.rg-adguard.net/php/get_edition.php?version_id=' + version_id + "&lang=" + namelang;
$.ajax({
type: "GET",
url: urli,
dataType: 'json',
success: function(response){
var options = '';
console.log(this.namelang);
$.each(response.editions, function() {
options += '<option value="' + this.edition_id + '" style="color: ' + this.color + '">' + this.namelang + '</option>';
});
$('#edition_id').html('<option value="0">- ' + seledition + ' -</option>'+options);
$('#edition_id').attr('disabled', false);
$('#language_id').html('<option>- ' + sellanguage + ' -</option>');
$('#language_id').attr('disabled', true);
$('#arch_id').html('<option>- ' + selachitecture + ' -</option>');
$('#arch_id').attr('disabled', true);
}
});

Are you sure you have namelang in your response???
I can not see namelang when I checked the URL.
Below is response from the urli
{
"editions": [
{
"name_en": "Windows 8.1 Pro + Core",
"color": "green",
"edition_id": "960032"
},
{
"name_en": "Windows 8.1 Pro N + Core N",
"color": "green",
"edition_id": "960033"
}
]
}
After I understanding your requirements properly here I came up with the solution. You don't know what will be the language name, it can be name_en or name_fr but name_ will be common. Right? If YES then below is the solution:
Working code snippet here:
let response = {"editions":[{"name_en":"Windows 8.1 Pro + Core","color":"green","edition_id":"960032"},{"name_en":"Windows 8.1 Pro N + Core N","color":"green","edition_id":"960033"}]};
$.each(response.editions, function() {
console.log(this.edition_id);
console.log(this.color)
let keysArr = Object.keys(this);
let langname = "name_";
for (var key in this) {
if (key.substring(0, langname.length) === langname) {
console.log(this[key]); // your desired value
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

That's because this, inside that callback, is just the JQuery xhr object, as seen here:
The response object contains what you want. But namelang is not inside that. The sample URL you gave has an array of two JSON objects.
To access, say, the first object's color, you'd take response[0].color.

Related

Use variable from callback as global variable

I made a block in which the request to the specified URL occurs.
Inside this block, I can work with the data from response, but outside this block I can not get this data because of asynchrony.
Is it possible to simulate a synchronous request in blockly or in some other way, save the received data to a global variable?
code of the created block:
Blockly.Blocks['request'] =
'<block type="request">'
+ ' <value name="URL">'
+ ' <shadow type="text">'
+ ' <field name="TEXT">text</field>'
+ ' </shadow>'
+ ' </value>'
+ ' <value name="LOG">'
+ ' </value>'
+ ' <value name="WITH_STATEMENT">'
+ ' </value>'
+ ' <mutation with_statement="false"></mutation>'
+ '</block>';
Blockly.Blocks['request'] = {
init: function() {
this.appendDummyInput('TEXT')
.appendField('request');
this.appendValueInput('URL')
.appendField('URL');
this.appendDummyInput('WITH_STATEMENT')
.appendField('with results')
.appendField(new Blockly.FieldCheckbox('FALSE', function (option) {
var delayInput = (option == true);
this.sourceBlock_.updateShape_(delayInput);
}), 'WITH_STATEMENT');
this.appendDummyInput('LOG')
.appendField('log level')
.appendField(new Blockly.FieldDropdown([
['none', ''],
['info', 'log'],
['debug', 'debug'],
['warning', 'warn'],
['error', 'error']
]), 'LOG');
this.setInputsInline(false);
this.setPreviousStatement(true, null);
this.setNextStatement(true, null);
this.setColour(230);
this.setTooltip('Request URL');
this.setHelpUrl('https://github.com/request/request');
},
mutationToDom: function() {
var container = document.createElement('mutation');
container.setAttribute('with_statement', this.getFieldValue('WITH_STATEMENT') === 'TRUE');
return container;
},
domToMutation: function(xmlElement) {
this.updateShape_(xmlElement.getAttribute('with_statement') == 'true');
},
updateShape_: function(withStatement) {
// Add or remove a statement Input.
var inputExists = this.getInput('STATEMENT');
if (withStatement) {
if (!inputExists) {
this.appendStatementInput('STATEMENT');
}
} else if (inputExists) {
this.removeInput('STATEMENT');
}
}};
Blockly.JavaScript['request'] = function(block) {
var logLevel = block.getFieldValue('LOG');
var URL = Blockly.JavaScript.valueToCode(block, 'URL', Blockly.JavaScript.ORDER_ATOMIC);
var withStatement = block.getFieldValue('WITH_STATEMENT');
var logText;
if (logLevel) {
logText = 'console.' + logLevel + '("request: " + ' + URL + ');\n'
} else {
logText = '';
}
if (withStatement === 'TRUE') {
var statement = Blockly.JavaScript.statementToCode(block, 'STATEMENT');
if (statement) {
var xmlhttp = "var xmlHttp = new XMLHttpRequest();";
var xmlopen = "xmlHttp.open('POST', " + URL + ", true);";
var xmlheaders = "xmlHttp.setRequestHeader('Content-type', 'application/json');\n" +
"xmlHttp.setRequestHeader('Authorization', 'Bearer psokmCxKjfhk7qHLeYd1');";
var xmlonload = "xmlHttp.onload = function() {\n" +
" console.log('recieved:' + this.response);\n" +
" var response = this.response;\n" +
" var brightness = 'brightness: ' + JSON.parse(this.response).payload.devices[0].brightness;\n" +
" " + statement + "\n" +
"}";
var json = JSON.stringify({
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [{
"intent": "action.devices.QUERY",
"payload": {
"devices": [{
"id": "0",
"customData": {
"smartHomeProviderId": "FkldJVJCmDNSaoLkoq0txiz8Byf2Hr"
}
}]
}
}]
});
var xmlsend = "xmlHttp.send('" + json + "');";
var code = xmlhttp + '\n' + xmlopen + '\n' + xmlheaders + '\n' + xmlonload + '\n' + xmlsend;
return code;
} else {
var xmlhttp = "var xmlHttp = new XMLHttpRequest();";
var xmlopen = "xmlHttp.open('POST', " + URL + ", true);";
var xmlheaders = "xmlHttp.setRequestHeader('Content-type', 'application/json');\n" +
"xmlHttp.setRequestHeader('Authorization', 'Bearer psokmCxKjfhk7qHLeYd1');";
var xmlonload = "xmlHttp.onload = function() {\n" +
" console.log('recieved:' + this.response);\n" +
"}";
var json = JSON.stringify({
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [{
"intent": "action.devices.QUERY",
"payload": {
"devices": [{
"id": "0",
"customData": {
"smartHomeProviderId": "FkldJVJCmDNSaoLkoq0txiz8Byf2Hr"
}
}]
}
}]
});
var xmlsend = "xmlHttp.send('" + json + "');";
var code = xmlhttp + '\n' + xmlopen + '\n' + xmlheaders + '\n' + xmlonload + '\n' + xmlsend;
return code;
}
} else {
var xmlhttp = "var xmlHttp = new XMLHttpRequest();";
var xmlopen = "xmlHttp.open('POST', " + URL + ", true);";
var xmlheaders = "xmlHttp.setRequestHeader('Content-type', 'application/json');\n" +
"xmlHttp.setRequestHeader('Authorization', 'Bearer psokmCxKjfhk7qHLeYd1');";
var xmlonload = "xmlHttp.onload = function() {\n" +
" console.log('recieved:' + this.response);\n" +
"}";
var json = JSON.stringify({
"requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
"inputs": [{
"intent": "action.devices.QUERY",
"payload": {
"devices": [{
"id": "0",
"customData": {
"smartHomeProviderId": "FkldJVJCmDNSaoLkoq0txiz8Byf2Hr"
}
}]
}
}]
});
var xmlsend = "xmlHttp.send('" + json + "');";
var code = xmlhttp + '\n' + xmlopen + '\n' + xmlheaders + '\n' + xmlonload + '\n' + xmlsend;
return code;
}};
We actually use Promises extensively in our Blockly environment. My suggestion would be to Promisify this and then use a generator function. For example, we use the co library to wrap our generated code, then use yield statements for asynchronous values to make them behave synchronously. For example:
For a block setup similar to this --
The generated code would be something like this (simplified) --
co(function* () {
var getUsername;
// getFieldValue makes an asynchronous call to our database
getUsername = (yield getFieldValue("username", "my user record Id", "users"));
Promise.all(inputPromises)
let inputPromises = [];
inputPromises.push('User name is');
inputPromises.push(getUsername);
yield new Promise(function(resolve, reject) {
Promise.all(inputPromises).then(function(inputResults) {
let [TITLE, MESSAGE] = inputResults;
let activity = "toastMessage";
let LEVEL = "success";
try {
var params = {message: MESSAGE, title: TITLE, level: LEVEL};
interface.notification(params);
return resolve();
} catch(err) {
return reject(err);
}
}).catch(reject);
});
return true;
}
As you may have noticed, though, this isn't always as easy as just sticking a "yield" before the block. Depending on your setup, you may have to get more creative using Promise.all to get values in your block, etc. (We actually wound up editing a bunch of the Blockly core blocks to append 'yield' in front of inputs which had a "promise" type set amongst their output types in order to make this work, but based on your setup, this may be overkill.)
Obviously, you would need to make sure this was either transpiled or run in an environment which supports ES6.
Of course, once you enter an asynchronous setup, there's not really any going back -- co functions themselves return a Promise, so you will need to deal with that appropriately. But in general, we've found this to be a pretty robust solution, and I'm happy to help you figure it out in more detail.
You can have blocks that execute asynchronously without Promises, async functions, or callbacks by using the JS Interpreter (docs, GitHub), conveniently written by the same guy that created Blockly. JS Interpreter is a JavaScript-in-JavaScript implementation. This does mean there needs to be a lot of code to connect the functions/commands of the main JS VM to the interpreter's embedded implementation.
Blockly has a few demonstrations of doing this (src). In particular, you'll want to investigate async-execution.html and the wait block implementation. You can find the wait block running live here.
Conveniently, the interpreter's doc's section on External API happens to use XMLHttpRequest as its example implementation. This should should be a good starting point for your request block's implementation.

How do I get specific value key pair in ajax javascript for datatype json?

I want to get the value of "status" from data in the code below,
$.ajax({
dataType: "json",
url: "calendar/php/date.php",
type: "POST",
data: {
select: "%Y-%c-%e",
where: "%Y-%c",
d: y + "-" + m,
order: "timestamp, id"
},
beforeSend: function() { $('#loading').show(); },
success: function(data) {
sessionStorage[y+"-"+m] = JSON.stringify(data);
for (var key in data) {
$("<span class=\"label label-success\">" + Object.keys(data[key]).length + "</span>").prependTo($("#" + key));
console.log('key: ' + key + '\n' + 'value: ' + JSON.stringify(data));
}
},
complete: function() { $('#loading').fadeOut(200); }
});
Following is some part of the console.log result:
key: 2014-11-11
value: {"2014-11-11":[{"0":"3","1":"2014-11-11 11:11:00","2":"2014-11-28 10:12:00","3":"test","4":"test","5":"0","6":"","7":"","8":"","9":"0","10":"0","11":"0","12":"0","13":"0","14":"0","15":"0","16":"","17":"2014-11-11","id":"3","timestamp":"2014-11-11 11:11:00","toTimestamp":"2014-11-28 10:12:00","title":"test","location":"test","status":"0","organizer":"","organizerContact":"","organizerEmail":"","projector":"0","laptop":"0","speaker":"0","pointer":"0","whiteboard":"0","mediaCoverage":"0","parking":"0","remark":"","selector":"2014-11-11"}],"2014-11-12":[{"0":"15","1":"2014-11-12 07:07:00","2":"2014-11-12 03:09:00","3":"test","4":"test","5":"1","6":"","7":"","8":"","9":"0","10":"0","11":"0","12":"0","13":"0","14":"0","15":"0","16":"","17":"2014-11-12","id":"15","timestamp":"2014-11-12 07:07:00","toTimestamp":"2014-11-12 03:09:00","title":"test","location":"test","status":"1","organizer":"","organizerContact":"","organizerEmail":"","projector":"0","laptop":"0","speaker":"0","pointer":"0","whiteboard":"0","mediaCoverage":"0","parking":"0","remark":"","selector":"2014-11-12"}]}
I want get the value of "status" i.e 0, as seen in the above result, in order to include it in the for loop (for (var key in data) {...}) to change the class 'label-success' to 'label-failure' if the status is 0. Could you help me?
Hello maybe I am wrong but
console.log('key: ' + key + '\n' + 'value: ' + JSON.stringify(data));
returns the whole data object in string format when you say JSON.stringify(data);
You want the value which is returned when you give data a specific key to read values from:
console.log('key: ' + key + '\n' + 'value: ' + data[key]);
EDIT: Im not sure if data[key] will return a [object Object]... if it does try JSON.stringify(data[key])
I would also suggest Itterating through data with the
for(var i = 0; i < data.length; i++){}
this makes it readable and is measured the most performant way of extracting data.
EDIT nr 2:
This is your object:
{"2014-11-11":[{"0":"3","1":"2014-11-11 11:11:00","2":"2014-11-28 10:12:00","3":"test","4":"test","5":"0","6":"","7":"","8":"","9":"0","10":"0","11":"0","12":"0","13":"0","14":"0","15":"0","16":"","17":"2014-11-11","id":"3","timestamp":"2014-11-11 11:11:00","toTimestamp":"2014-11-28 10:12:00","title":"test","location":"test","status":"0","organizer":"","organizerContact":"","organizerEmail":"","projector":"0","laptop":"0","speaker":"0","pointer":"0","whiteboard":"0","mediaCoverage":"0","parking":"0","remark":"","selector":"2014-11-11"}],"2014-11-12":[{"0":"15","1":"2014-11-12 07:07:00","2":"2014-11-12 03:09:00","3":"test","4":"test","5":"1","6":"","7":"","8":"","9":"0","10":"0","11":"0","12":"0","13":"0","14":"0","15":"0","16":"","17":"2014-11-12","id":"15","timestamp":"2014-11-12 07:07:00","toTimestamp":"2014-11-12 03:09:00","title":"test","location":"test","status":"1","organizer":"","organizerContact":"","organizerEmail":"","projector":"0","laptop":"0","speaker":"0","pointer":"0","whiteboard":"0","mediaCoverage":"0","parking":"0","remark":"","selector":"2014-11-12"}]}
this is a bit nested, so try to get an overview of what you have:
data = {
"2014-11-11": [],
"2014-11-12": []... }
This object has a length method that returns the length of your object. this allows you to itterate over the Data Object will give you "2014-11-11" as key and with this key you can access your values like this: data[key] this will return your array...to read data from your array you will have to itterate again data[key][i]... now you can read the data inside each array element like this
data[key][i]["status"];
Hope this helped somehow... cant be bothered to write all this code :D
success: function(data) {
sessionStorage[y+"-"+m] = JSON.stringify(data);
for (var key in data) {
var status = data['status'];
var klass = status === 0 ? 'label-failure' : 'label-success';
$('<span class="label '+klass+'">' + Object.keys(data[key]).length + "</span>").prependTo($("#" + key));
console.log('key: ' + key + '\n' + 'value: ' + JSON.stringify(data));
}
},
Try this code instead.
$.ajax({
dataType: "json",
url: "calendar/php/date.php",
type: "POST",
data: {
select: "%Y-%c-%e",
where: "%Y-%c",
d: y + "-" + m,
order: "timestamp, id"
},
beforeSend: function() { $('#loading').show(); },
success: function(data) {
sessionStorage[y+"-"+m] = JSON.stringify(data);
for (var key in data) {
for (var i in data[key]) {
$("<span class=\"label " + ((data[key][i] === "0") ? "label-failure" : "label-success") + "\">" + Object.keys(data[key]).length + "</span>").prependTo($("#" + key));
}
console.log('key: ' + key + '\n' + 'value: ' + JSON.stringify(data));
}
},
complete: function() { $('#loading').fadeOut(200); }
});

Creating Javascript Buttons

I have created buttons using javascript, these buttons are created onload by the javascript page. The number of buttons created, as well as the button attributes (id, name), depend on the info that is fetched from a database table. Now I need to use the buttons independently, but I don't know the id in advance so I could mention it on any function, please help.
var CABLE_BOM_ALT_QUERY_PAGE = 'GetAltFromBom.json.aspx';
var WIRE_TYPE = 'AVSSXF2B';
var WIRE_LENGTH = 2000;
$(document).ready(function () {
FetchCableBom();
});
function FetchCableBom() {
$.ajax({
url: CABLE_BOM_ALT_QUERY_PAGE
, data: "WireType=" + WIRE_TYPE + "&WireLength=" + WIRE_LENGTH
, dataType: 'json'
, success: DisplayButtons
, error: ErrorHandler
, async: false
});
}
function createButtons(tbID, tbClass, tbType, tbValue, onClick) {
return '\n<input'
+ (tbID ? ' id=\'' + tbID + '\'' : '')
+ (tbClass ? ' class=\'' + tbClass + '\'' : '')
+ (tbType ? ' type=\'' + tbType + '\'' : '')
+ (tbValue ? ' value=\'' + tbValue + '\'' : '')
+ (onClick ? ' onclick=\''+ onClick + '\'':'')
+ '>';
}
function DisplayButtons(cableData) {
var newContent = '';
$.each(cableData, function (i, item) {
newContent += createButtons(item.CommonCable, null, "submit", item.CommonCable, toggle);
});
$('#Categories').html(newContent);
}
function toggle() {
console.log("P#ssw0rd");
return;
}
function ErrorHandler() {
alert('ERROR: ' + jqXHR.status + '\r\nURL: ' + this.url + '\r\nContact the I.T Department.');
}
Even after reading it a few times I am not quite sure I know what you are trying to do. But here is my guess: You have some result set containing button attributes which come from a database. And you want these buttons "independently", I assume without having queried the database, because you need some kind of Id.
Have you thought about statically pre-populating your result set whenever the database hasn't been queried yet? Something along the lines of this:
if (hasDatabaseResult) {
buttonData = getDatabaseResult();
} else {
buttonData = [ {id : 1, name : "First record"} ]
}

Javascript function not called in jQuery $.submit

Hey there,
Again, I've been searching a solution to find out why a function, would not being called... and guess what, I did not find.
I have a form, that I submit using jQuery Ajax. When error, I get every local data, I got, I sorted them, and show them to the user.
Here is the sample code :
$.ajax({
type: "POST",
url: "http://xxx/register.php",
data: form,
success: function(msg){
//console.log("Data Saved: " + msg);
$.iGrowl(2,stringdata[4]);
var data = parseJSON(msg);
if(data.msg.score != undefined){
var cpt = 0;
$.each(data.msg.score, function(index,el){
if(cpt<8){
if(el.selected)
$('tbody').append('<tr class="win"><td>' + el.name + '</td><td>' + el.score + '</td></tr>');
else
$('tbody').append('<tr><td>' + el.name + '</td><td>' + el.score + '</td></tr>');
}
});
}
else{
$.iGrowl(3,"Erreur inconnue...");
}
$("#scorediv").css("visibility","visible");
$( "#formule" ).css('opacity',0);
$( "#scorediv" ).css('opacity',1);
},
error: function(data) {
cpt = 0;
var i = 0;
score.each(function(r){
arrayScore[i] = r;
i++;
});
arrayScore.sort(function(a, b){
console.log("sorting...");
if(a[3])
{
if(b[3])
{
return (b[3].value - a[3].value); //causes an array to be sorted numerically and descending
}
}
});
$.each(arrayScore, function(index,el){
//arrayScore.forEach(function(el) {
//score.each(function(el){
if(cpt<8)
{
if(el[2].value == form[2].value)
$('tbody').append('<tr class="win"><td>' + el[1].value + '</td><td>' + el[3].value + '</td></tr>');
else
$('tbody').append('<tr><td>' + el[1].value + '</td><td>' + el[3].value + '</td></tr>');
cpt++;
}
else
return false;
});
var user = form;
store.save(user, function(r) {
});
$.iGrowl(3,stringdata[5]);
$("#scorediv").css("visibility","visible");
$("#formule").css('opacity',0);
$( "#scorediv" ).css('opacity',1);
}
});
My array is never sorted. If I change this part :
var i = 0;
score.each(function(r){
arrayScore[i] = r;
i++;
});
by this :
score.each(function(r){
arrayScore.push(r);
});
arrayScore is never filled.
I try to execute each line in the console step by step, it works.... I'm getting kind of crazy... and I really do not know what could have happened ?
Any help would be graceful appreciate !
P.S : I'm using, jQuery1.5 + Lawnchair and CSS3 animation.
Code tested on safari and chrome.
Thanks !
Javascript array objects don't support a method called each. You should try
$.each(score, function(index, value){...});

Asynchronous database search with AJAX, MVC, JQuery

Sorry about the odd question wording. In all honesty I'm in right at the deep end here, having to learn a huge amount all at once.
I'm trying to figure out how to perform an asynchronous search on a database using AJAX, but it keeps coming up with a "500 internal server error". I've done some AJAX tutorials but none of them involve the MVC method of web development. I'm a bit lost with what information needs to be sent where, and how.
All I know is that a 500 Server Error means it's happening on the server side rather than the client side, so I presume there's a break in logic at the point where the controller starts to get involved. That's just a newbie guess though.
I'll paste all of what I believe to be the relevant code. For context, the database info is from an 'accounts' table in a mock bank database I've been working with for practice.
Thanks for any help.
Firstly, here's the error information I get when looking at debug info on Chrome
Now here's the code involved.
Javascript/JQuery:
var $j = jQuery.noConflict();
var key = 0;
$j(function () {
$j("#search_btn").click(function () {
key = $j("#acc-id-search").val();
searchAcc();
return false;
})
});
function searchAcc() {
var callback = function (data) {
$j("#account_data_table").empty();
var htmlArray = [];
if (data.total > 0) {
$j.each(data.items, function (i, item) {
htmlArray.push("<tr>");
htmlArray.push('<td class="text-center">' + item.account_id + '</td>');
htmlArray.push('<td class="text-center">' + item.product_id + '</td>');
htmlArray.push('<td class="text-center">' + item.cust_id + '</td>');
htmlArray.push('<td class="text-center">' + item.open_date + '</td>');
htmlArray.push('<td class="text-center">' + item.close_date + '</td>');
htmlArray.push('<td class="text-center">' + item.last_activity_date + '</td>');
htmlArray.push('<td class="text-center">' + item.status + '</td>');
htmlArray.push('<td class="text-center">' + item.open_branch_id + '</td>');
htmlArray.push('<td class="text-center">' + item.open_emp_id + '</td>');
htmlArray.push('<td class="text-center">' + item.avail_balance + '</td>');
htmlArray.push('<td class="text-center">' + item.pending_balance + '</td>');
htmlArray.push("</tr>");
});
}
else {
htmlArray.push('<tr><td colspan="10">No results!</td></tr>');
}
$j("#account_data_table").append(htmlArray.join(''));
alert("Sucess?");
};
alert("Searching for '" + key + "'");
postData('#Url.Content("~/Accounts/Index")', key, callback, '#account_data_table');
}
function postData(url, data, callback, lockObj, dataType, loadingMessage)
{
data = data || {};
dataType = dataType || 'json';
loadingMessage = loadingMessage || 'Loading...';;
var isLock = !!lockObj;
$.ajax({
url: url,
data: data,
method: 'post',
dataType: dataType,
cache: false,
beforeSend: function(){
alert("About to send");
},
success: callback,
error: function(){
alert("Failed..!");
},
complete: function(){
}
});
}
The controller that '#Url.Content("~/Accounts/Index")' points to:
[HttpPost]
public NewtonJsonResult Index(int key)
{
var _service = new BankEntities();
var searchCondition = new account() { account_id = key };
var resultObj = new AjaxDataResult();
var allitems = _service.All(searchCondition);
var itemArray = new JArray();
resultObj.total = allitems.Count();
JObject temp;
foreach(var item in allitems)
{
temp = new JObject();
temp["account_id"] = item.account_id;
temp["product_cd"] = item.product_cd;
temp["cust_id"] = item.cust_id;
temp["open_date"] = item.open_date;
temp["close_date"] = item.close_date;
temp["last_activity_date"] = item.last_activity_date;
temp["status"] = item.status;
temp["open_branch_id"] = item.open_branch_id;
temp["open_emp_id"] = item.open_emp_id;
temp["avail_balance"] = item.avail_balance;
temp["pending_balance"] = item.pending_balance;
itemArray.Add(temp);
}
resultObj.items = itemArray;
return new NewtonJsonResult(resultObj);
}
The 'All(searchcondition)' method which is used to find the required items in the table:
public List<account> All(account acc)
{
var data = accounts.Where(x => x.status == "ACTIVE");
if(acc.account_id != 0)
{
data = data.Where(x => x.account_id == acc.account_id);
}
return data.OrderBy(x => x.account_id).ToList();
}
Special thanks to #nnnnnn whose answer lies in the comments after the initial question:
The method might not be called because you're not setting the right
request parameters, so no method exists for the request hence the 500
error. Your current code is trying to include the key value without
giving it a request parameter name. Try changing key =
$j("#acc-id-search").val(); to key = { key: $j("#acc-id-search").val()
};. (The actual request would then end up with a parameter
key=thesearchvaluehere.)

Categories

Resources