Why the value assigned in method is not reflecting in UI - html

I am calling a function on click of li data. Am passing the li data into that function and am trying to modify the data, but the data is not getting modified. Please suggest. Here is the plunkr.
https://next.plnkr.co/edit/ENExN1q40yY9dVFL?open=lib%2Fscript.js&deferRun=1&preview
$scope.selectRow = function(folders) {
console.log(folders);
folders = 'apple';
$http({
method: "GET",
url: "https://reqres.in/api/users?page=2",
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
folders = response.page;
});
}

To achieve that you need to change the $scope.folderList not the folders.
Changing the function to this:
$scope.selectRow = function(folders) {
$http({
method: "GET",
url: "https://reqres.in/api/users?page=2",
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
var index = $scope.folderList.indexOf(folders);
if (index >= 0 ) {
$scope.folderList[index] = String(response.data.page)
}
});
}
https://next.plnkr.co/edit/h3XKo5klP2F1qmAg?open=lib%2Fscript.js&deferRun=1

Folders is a variable that only exists in the method in your controller and then in the ng-repeat directive in your Html. Nowhere else does it exist so it's basically not a valid variable and is out of scope. In the ng-repeat directive you assign a name to the items in a list, so you could call it fuzzlebumps and it would still work.
So my suggestion: if you want to keep a variable in scope correctly do this in your controller to initialise it:
$scope.nameOfVariable;
Or in your case:
$scope.folders;
This is creating a variable that is bound to the scope. Scope is very important in JS so do a google search for the basics mate.

Related

Trying to pass list of ids to the M-V-C Action through Ajax Function

I am trying to get and store the Ids of all the selected check-boxes in the JavaScript object. And then passing this object as a data to my JSON Action. I am able to successfully get the Ids of all the selected check-boxes, but when I am passing this object to my action I am getting null. Following is my code:
$("#btnSave").on('click', function () {
var selected = [];
$('input:checked').each(function () {
selected.push($(this).attr('id'));
});
$.ajax({
url: '#Url.Action("SaveRecords", "Users")',
data: { ids: selected },
cache: false,
type: "GET",
success: function (data) {}
});
});
My Action:
public JsonResult SaveRecords(List<int> ids) //Here I'm getting Null.
{
return Json(true, JsonRequestBehavior.AllowGet);
}
As suggested in the comments, since you are saving data POST is more appropriate than GET. Also, I think you will save yourself some trouble by using JSON as input - you're already using it as output format from the action. This means your AJAX call will look like this:
$.ajax({
type: 'POST',
url: '#Url.Action("SaveRecords", "Users")',
contentType: 'application/json',
data: JSON.stringify(selected),
success: function (data) { /* ... */ }
});
When I say "save yourself trouble by using JSON as input" I mean that model binding collections and complex types in MVC can be a bit tricky when sending data as a form post - google it and you'll see that there are several implementation characteristics to be aware of. In my experience, using JSON for structured data posted with AJAX just works much more like what you would expect.

How do I handle a MySQL query with multiple parameters whilst using Angular / Express

I am designing a used cars website using AngularJS and NodeJS/Express. The database is MySQL (so not quite a MEAN stack).
I am very familiar with Angular but this is the first time I have used Express (in the past I have gone for JAX-RS).
I have no problem whilst only sending one or two paramaters e.g.
app.get('/api/images/:vehicleId', function (request, response) {
images.getThumbnailImage(request, response, connection, request.params.vehicleId);
});
but I am unsure how to move forward with multiple parameters, some of which are optional.
The client is built using TypeScript. The form data is collected by way of a TypeScript object, but I am not sure what the best practice is for sending multiple parameters.
The options I have thought of are:
1). Send the object and then use that to build a query:
return this.$http({
method: 'POST',
url: this.API_ADDRESS + 'vehicles/',
data: vehicleSearchModel,
headers: {
'Content-Type': 'application/json'
}
}).then((response: any) => {
return response.data;
});
and retrieve it from the body using body-parser i.e.
request.body.data (or something similar)
or
2). send multiple params in the url i.e.
app.get('/api/vehicles/:make/:model/:bodyStyle/:fuelType/:transmission/:minPrice/:maxPrice/:minYear/:maxYear/:counties', function (request, response) {
//Do something with request.params!!!
});
Please advise.
First, you should make the http post request as following.
var data = {
make : make,
model : model,
fuelType : fueltype,
....
}
return this.$http({
method: 'POST',
url: this.API_ADDRESS + 'vehicles/',
data: vehicleSearchModel,
headers: {
'Content-Type': 'application/json'
}
}).then((response: any) => {
return response.data;
});
And then, you can receive the multiple parameters as following.
app.post('/api/vehicles/', function(req, res){
var make = req.body.make;
var model= req.body.model;
var bodyStyle= req.body.bodyStyle;
var fuelType= req.body.fuelType;
var transmission= req.body.transmission;
.....
});

parameter passing from CDE to PDI pentaho

I have a scenario to pass parameters from pentaho cde using kettle to pentaho data integration and then update the table using the passed parameter in PDI. How can i pass the parameter and get the passed parameter in PDI?
Thanks in advance!!!
You will need to use the Pentaho plugin builder, SPARKL.
With it you can upload a transformation as a callable endpoint and use a CDE dashboard to call it.
First of all, you need a transformation that expects parameters. You can try it with a test one before going to a more advanced transformation:
Example:
defining a parameter and fetching with a Get Variables step
Second you will create a new plugin on SPARKL.
Sparkl welcome screen
Give your plugin a name and add a kettle endpoint to it. If you now look at your pentaho-solutions/system folder, you will have a new folder with the plugin name. Open it and find the ktr file inside the subfolders to replace it with your transformation.
The last step is to add a new dashboard to your plugin and edit it. If you go to the datasources tab now, notice the datasources with 'endpoint' in the name. We will access them by code, but is good to know they are here so you can read data from it too, not just input data.
add a new resource of javascript to your CDE layout with the following code:
var myPluginName = {};
(function(myself) {
myself.runEndpoint = function (pluginId, endpoint, opts) {
if (!pluginId && !endpoint) {
Dashboards.log('PluginId or endpointName not defined.');
return false
}
var _opts = {
success: function () {
Dashboards.log(pluginId + ': ' + endpoint + ' ran successfully.')
},
error: function (){
Dashboards.log(pluginId + ': error running ' + endpoint + '.')
},
params: {},
systemParams: {},
type: 'POST',
dataType: 'json'
}
var opts = $.extend( {}, _opts, opts);
var url = Dashboards.getWebAppPath() + '/plugin/' + pluginId + '/api/' + endpoint;
function successHandler (json) {
if (json && json.result == false) {
opts.error.apply(this, arguments);
} else {
opts.success.apply( this, arguments );
}
}
function errorHandler () {
opts.error.apply(this, arguments);
}
if (endpoint != 'renderer/refresh' ) {
var ajaxOpts = {
url: url,
async: true,
type: opts.type,
dataType: opts.dataType,
success: successHandler,
error: errorHandler,
data: {}
}
} else {
var ajaxOpts = {
url: url,
async: true,
type: 'GET',
dataType: opts.dataType,
success: successHandler,
error: errorHandler,
data: {}
}
}
_.each( opts.params , function ( value , key) {
ajaxOpts.data['param' + key] = value;
});
_.each(opts.systemParams , function (value , key) {
ajaxOpts.data[key] = value;
});
$.ajax(ajaxOpts)
}
})(myPluginName);
You can change myPluginName with whatever you want but that enables you to call that endpoint sending parameters with any button. To do so you can use that code:
myPluginName.runEndpoint(
'myPluginName', // Plugin identifier.
'endpointName', // Put your endpoint name here!
{
params: {
'EXAMPLE_PARAMETER' : foo_bar
},
success: function() { Dashboards.fireChange('refresh', 1); alert('data sent'); },
error: function() { alert('Ops, something went wrong. Check the logs.'); }
})
You can keep track of the execution by monitoring the bi-server logs.
More information on the sources:
Diethard Steiner - Blog
Francesco Corti - Blog
Follow these guys, they are amazing.
You could do that, or you could just create a CDA data source, which takes a parameter as defined in your transformation.
Params are passed to CDA via the usual &paramYOURPARAMNAME=x syntax on the URL.
In the transformation you get the parameter using the get variables step.
Did I miss something?

viewbag data is empty in $.ajax

Iam using asp.net mvc4 and facing some problem in accessing viewbag.price.
This is what i am doing:-
[HttpPost]
public ActionResult FillModel(int id)
{
var vehModel = db.Vehicle_Model.Where(vehMod => vehMod.MakeID == id).ToList().Select(vehMod => new SelectListItem() { Text = vehMod.Model, Value = vehMod.pkfModelID.ToString() });
ViewBag.Price = 100;
return Json(vehModel, JsonRequestBehavior.AllowGet);
}
i am calling above using below:-
$.ajax({
url: '#Url.Action("FillModel","Waranty")',
type: 'post',
data: { id: id },
dataType: 'json',
success: function (data) {
$('#ddModel').empty();
$.each(data, function (index, val) {
var optionTag = $('<option></option>');
$(optionTag).val(val.Value).text(val.Text);
$('#ddModel').append(optionTag);
});
var a = '#ViewBag.Price';
},
error: function () {
alert('Error');
}
});
But i am not able to access ViewBag.Price.
Anyone know the reason??
thanks
The reason you aren't able to access items from the ViewBag inside your ajax success function is because the view that contains your script has already been rendered by the Razor view engine, effectively setting the variable a to whatever the value of #ViewBag.Price was at the time the page was rendered.
Looking at the process flow might be helpful:
(1) The request comes in for the view that has your script fragment in it.
(2) The controller method that returns your view is called.
(3) The Razor view engine goes through the view and replaces any references to #ViewBag.Price in your view with the actual value of ViewBag.Price. Assuming ViewBag.Price doesn't have a value yet, the success function in your script is now
success: function (data) {
$('#ddModel').empty();
$.each(data, function (index, val) {
var optionTag = $('<option></option>');
$(optionTag).val(val.Value).text(val.Text);
$('#ddModel').append(optionTag);
});
var a = '';
}
(4) The rendered html gets sent to the client
(5) Your ajax request gets triggered
(6) On success, a gets set to the empty string.
As you had mentioned in the comments of your question, the solution to this problem is to include a in the Json object returned by your action method, and access it using data.a in your script. The return line would look like
return Json(new {
model = vehModel,
a = Price
});
Keep in mind that if you do this, you'll have to access model data in your ajax success function with data.model.Field. Also, you shouldn't need to specify the JsonRequestBehavior.AllowGet option, since your method only responds to posts and your ajax request is a post.

TDD and configuration variables

I'm learning TDD (in Javascript), and I wanted to know, what is the right way to use configuration variables? Should I make a separate class and have them be member variables of the class, and pass an instance of the class to every object that needs it, or make a list of global variables and just use those? What are the benefits / setbacks of each method?
For example, I have to get data from a URL as follows:
function getData (remoteDataDelegate) {
remoteDataDelegate.getData(userInfoURL)
}
where userInfoURL is a configuration variable that I set elsewhere to the URL for a page on my site.
This is an example of how I do it:
function NewConfiguration() {
var config = {};
config.carriersSelector = NewCarriersSelector();
config.paymentMethodsSelector = NewPaymentMethodsSelector();
return config;
}
Usage:
function NewOrderModel(request, searchRequest) {
var configuration = NewConfiguration();
// ... other variables code
var that = {
getContentSuccess: function(cb) {
// .. setup code
$.ajax({
type: 'GET',
url: request.page,
dataType: 'json',
data: request.data,
async: request.async,
success: function(data) {
if (data.status === 'success') {
cb(data.html, activeCustomer, step, configuration);
}
if (data.status == 'flash') {
flash(data.flash);
}
},
complete: request.complete
});
},
}
You will notice that the configuration is not being injected. for me, in this sample code the configuration never changes. Now my request objects change so they get injected, so I can mock those out or redirect the pages.
Global variables are usually set by the setUp method of your TestCase.