Ext.Ajax.request({
url: 'foo.php', // where you wanna post
success: passFn, // function called on success
failure: failFn,
params: { foo: 'bar' } // your json data
});
I am following How to post json data with extJS and got a question regarding functions. I see that we can embed functions right in the passFn and failFn area. However, what if I want these functions to be elsewhere? Where to create these functions and code them in Sencha Architect?
You can create a folder that is outside of Sencha Architect control, and call it from inside your Architect code.
For example, I like to create a folder called "util". So here is what your folder structure will look like:
app
-- controller
-- model
-- store
-- view
-- util <--- I added this directory
-- MiscFunctions.js <-- your own class file
Inside MiscFunctions.js, you would create the class like so:
Ext.define('MyApp.util.MiscFunctions', {
singleton: true,
passFn: function() {
...
},
failFn: function() {
}
});
Then you can refer to those functions from inside your Architect code:
Ext.Ajax.request({
url: 'foo.php', // where you wanna post
success: MyApp.util.MiscFunctions.passFn, // function called on success
failure: MyApp.util.MiscFunctions.failFn,
params: { foo: 'bar' } // your json data
});
Don't forget to add the
singleton: true
part, or else you will have to create an instance of that class to use the functions inside.
Here is how you can use basic functions in architect:
Create a controller.
Add a controller action and set its attributes as follows:
controlQuery: '#btn1', // (a button component with id "btn1")
targetType : Ext.Button, // (component type)
fn : onBtn1Tap, // (function name)
name : tap // (event)
Add a basic function and set its attributes:
fn: basicFunction (function name)
Now you can use this basic function in onBtn1Tap: this.basicFunction()
Related
In a Sails 1.x app, add a property to a controller, initialize it with a boolean, a number or null and try to lift the app.
module.exports = {
_foo: 123, // illegal
_bar: '', // legal
_baz: [] // legal
};
The lift will fail with this message:
error: Failed to lift app: Error: Consistency violation: `action` (2nd arg) should be provided as either a req/res/next function or a machine def (actions2), but instead, got: ...
However, an empty string, empty array, empty object etc. work.
Am I misunderstanding something fundamental about controllers or why are booleans and numbers not allowed?
My goal is to add simple attributes to the controller in order to temporarily store information.
Action 2 controllers follow the Node Machine structure:
https://node-machine.org/spec/machine
Helpers
For dynamic content, then the better option could be to use helpers:
https://sailsjs.com/documentation/concepts/helpers
For example:
// api/helpers/custom.js
module.exports = {
friendlyName: 'Format welcome message',
sync: true, // without this use await sails.helpers.custom
fn: function(inputs, exits, env) {
return {
data: 'example'
}
}
}
Access this info in the controller as cons data = sails.helpers.custom();.
Config
For constants, you could use a config file:
https://sailsjs.com/documentation/concepts/configuration
For example:
// config/custom.js
module.exports.custom = {
data: 'example'
}
Use this data in the controller as const data = sails.config.custom.data; // result 'example'
I want to use Krajee bootstrap-fileinput (http://plugins.krajee.com/file-input) with Mvc razor, Please help me out with the process to to upload images to server and json result from actionResult.
I have just included a required js and css files in my view page and added a line
<input id="input-702" name="kartik-input-702[]" type="file" multiple="true" class="file-loading">
and a script
$("#input-702").fileinput({
uploadUrl:"#Url.Action("upload","Home")",
uploadAsync: true,
minFileCount: 1,
maxFileCount: 5,
overwriteInitial: false,
initialPreview: "",
initialPreviewConfig:"",
uploadExtraData: ""
});
This line is getting formatted and showing a drag and drop effect and select file button.The file selection and Thumbnail creation is working properly but on upload action there is the (fileinput,js) function "ajaxSubmit" which use to post the content to HomeController ActionResult "Upload".
ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError) {
var self = this, settings;
self.uploadExtra();
settings = $.extend({
xhr: function () {
var xhrobj = $.ajaxSettings.xhr();
return self.initXhr(xhrobj, 98);
},
url: self.uploadUrl,
type: 'POST',
dataType: 'json',
data: self.formdata,
cache: false,
processData: false,
contentType: false,
beforeSend: fnBefore,
success: fnSuccess,
complete: fnComplete,
error: fnError
}, self.ajaxSettings);
self.ajaxRequests.push($.ajax(settings));
},
Now i want to save all the files to server which are not uploaded using ActionResult and pass a value back to js. how to retrieve formdata and process.??
I was trying to find the solution to above problem and finally found the one. As I am able to save the file at server location from the controller but unfortunately I could not send the json response from controller to javascript.
Saving image using controller action :
[HttpPost]
public ActionResult upload()
{
foreach (string item in Request.Files)
{
HttpPostedFileBase file = Request.Files[item] as HttpPostedFileBase;
string fileName = file.FileName;
string UploadPath = "~/Images/";
if (file.ContentLength == 0)
continue;
if (file.ContentLength > 0)
{
string path = Path.Combine(HttpContext.Request.MapPath(UploadPath), fileName);
string extension = Path.GetExtension(file.FileName);
file.SaveAs(path);
}
}
return Json("");
}
To implement the delete button we have to Send Data from server in Asynchronous mode as a json array object eg.
initialPreview: [
'<img src='/images/desert.jpg' class='file-preview-image' alt='Desert' title='Desert'>',
],
initialPreviewConfig: [
{
caption: 'desert.jpg',
width: '120px',
url: '/localhost/avatar/delete',
key: 100,
extra: {id: 100}
}
]
Can anybody help me out to create json array object in controller and send it as a response object.???
I have a similar problem. Got it working (with the ajax calls) but always get one file in the request (whereas I need to get multiple but should be working for you!)
My code is as follows:
HTML:
<input id="input-id" type="file" data-preview-file-type="text" name="fileUpload[]" multiple class="file-loading" />
JS:
$("#input-id").fileinput(
{
uploadUrl: "/Galleries/Upload",
uploadAsync: true,
maxFileCount: 5
});
MVC controller which I would expect to be working - but i not:
[HttpPost]
public JsonResult Upload(IEnumerable<HttpPostedFileBase> fileUpload)
{
//somde logic
}
However when in side the method I will call:
Request.Files
My scenerio is that user:
clicks on 'browse'
selects picture and is able to see it in the preview
click on 'browse' once again
selects picture and the picture is appended to the current preview list
clicks upload and I get all the files in the controller
The only way I figure it, how it could be working is the ajax call switch on the plugin which allows to append the preview list. Unfortunatelly I can't submit all the pictures to the controller then.
I am trying to pass a simple variable value into an HTML file using ember.js. My value is contained within a json file called value.json.
My HTML code is as follows:
<h1>I won {{App.moneyvalue}} today!</h1>
However when I pass the json call via ember, it think that the entire call is a variable:
App = Ember.Application.create({
moneyvalue: function () {
return $.getJSON( "js/value.json", function( data ) {
return data.tot;
});
}
}
And returns the following:
I won function () { return $.getJSON( "js/donors.json", function( data ) { return data.tot; }); } today!
As it seems to think that moneyvalue is a string variable as opposed to a value?
The jSON file is superbasic
{
"tot": 100
}
Where is this going wrong?
you're supplying Handlebars with a function, generally you would use a computed or normal property on the object. In this case you really just shouldn't define it in the application scope either, I'd recommend using an application route (it's the root route of your app).
App.ApplicationRoute = Ember.Route.extend({
model: function(){
return $.getJSON( "js/value.json");
}
});
Then in your handlebars just use
<h1>I won {{tot}} today!</h1>
Here's an example: http://emberjs.jsbin.com/OxIDiVU/576/edit
I have done a service that gets a json file from the server with the translated values of the labels of my webapp. Seems to work fine:
mobilityApp.service('serveiTraduccions', function($resource) {
this.getTranslation = function($scope) {
var languageFilePath = 'traduccions/traduccio_en.json';
$resource(languageFilePath).get(function (data) {
$scope.translation = data;
});
};
});
What I am trying to do is acces that "$scope.translation" from my controler, I tried all and nothing worked. The object is saved in my $scope as you can see:
how can I get the values of the "registroBtnRegistro", "registroErrorRegistro" etc ?
Thanks in advance !
I tried:
console.log($scope.translation); -> undefined
console.log($scope['translation']); -> undefined
console.log($scope.translation.registroBtnRegistro); -> TypeError:
Cannot read property 'registroBtnRegistro' of undefined
console.log($scope.translation['registroBtnRegistro']); -> TypeError:
Cannot read property 'registroBtnRegistro' of undefined
Maybe you're trying to access these values from another $scope that not inherits the scope where you've created your translation model.
Try to assign this model directly to $rootScope, so you can access it from every scope:
mobilityApp.service('serveiTraduccions', function($resource, $rootScope) {
this.getTranslation = function() {
var languageFilePath = 'traduccions/traduccio_en.json';
$resource(languageFilePath).get(function (data) {
$rootScope.translation = data;
});
};
});
this answer is a blind attempt because your original post lacks basic information like the call from the controller.
we can refine it until we make it work.
First, you should be returning something from your method:
mobilityApp.service('serveiTraduccions', function($resource) {
this.getTranslation = function() {
var languageFilePath = 'traduccions/traduccio_en.json';
return $resource(languageFilePath);
};
});
You are using $resource but you might as well use basic $http.get(). at least it doesn't look like a restful api to me.
In any case, because it's an asynchronous request, it will not return the list of translated strings, but a resource "class" that allows methods like get, delete or the more general query():
from the docs: default methods are
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
sidenote: injecting $scope in a service doesn't make much sense to me: services are used to encapsulate common logic accross components. However, you can pass a scope instance as a parameter.
Then, the controller that uses this should have the service injected and use a callback to get the results when they have arrived (asynchronous operation!):
TraduccioCtrl ... {
$scope.translation = {}; // avoid undefined when the view just loads
ServeiTraduccions.getTranslation.query(function (response) {
$scope.translation = response; // and angular's two-way data binding will probably do the rest
});
}
The Angular docs about ng-resource have a working example. Other questions in SO have addressed this already too, like Using AngularJS $resource to get data
Good day! I need to render a model's attributes to JSON so I can pass them into a template.
Model:
var UserInfo = Backbone.Model.extend({
url: appConfig.baseURL + "users/",
});
Template:
<script type="text/html" class="template" id="profile-form">
<h2 class="ui-li-heading"><%= username %></h2>
<p class="ui-li-desc"><strong><%= phone %></strong></p>
</script>
View:
var ProfilePageView = Backbone.View.extend({
events: {
'click #edit': "edit"
},
initialize: function () {
this.template = $.tpl['profile-form'];
var user = new UserInfo()
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST'
});
console.log(user) //returns correct object with attrs
console.log(user.toJSON()) //returns empty object
},
render: function (eventName) {
$(this.el).html(this.template());
},
edit: function () {
window.workspace.navigate('#account/edit', { trigger: true});
}
});
When i put in console something like this, user.toJSON() returns correct data
var user = new UserInfo();
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST'
});
But when i put it to my view, its returns Object {}.
Where is a mistake or tell me how can differently pass to the template data received from the server in json format? Thanks!
You appear to have two problems. fetch is asyncronous, so you need to use a callback to use the information. But first, an explanation about toJSON. .toJSON() doesn't actually return a JSON string, it returns an object that is what you want JSON to stringify. This allows you to modify the toJSON method to customize what attributes will be taken from your model or collection and added to the JSON string representation of your model. Here is a quotation from the Backbone.js docs:
toJSON collection.toJSON([options])
Return a shallow copy of the model's attributes for JSON
stringification. This can be used for persistence, serialization, or
for augmentation before being sent to the server. The name of this
method is a bit confusing, as it doesn't actually return a JSON string
— but I'm afraid that it's the way that the JavaScript API for
JSON.stringify works.
So you should replace this line in your code
console.log(user.toJSON())
with this one
console.log(JSON.stringify(user))
The object that you saw was returned by toJSON will then be turned into JSON.
Now, even after you do that, it won't work properly, because you will execute the console.log before you get the data for your model from fetch. fetch is asynchronous, so you need to call any code you want to be executed after the fetch is done in the success callback:
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST',
success: function(){
console.log(user);
console.log(JSON.stringify(user));
}
});