emberjs rails submitting in controller without model - ruby-on-rails-3

I'm am brand new to emberjs (1.0.0-RC1) which I'm using on top of rails. I want to submit a form for a session without using an ember model. I feel this is better because there is not real session model in my rails app. For now what works is the following:
#login_controller.js.coffee
SkillUp.LoginController = Ember.ObjectController.extend
# Just a title to pass to the template, for fun
title: "Login Controller"
submit: (controller) ->
model = #get 'model'
model.get('transaction').commit()
#session.js.coffee
SkillUp.Session = DS.Model.extend
email: DS.attr 'string'
password: DS.attr 'string'
#login_route.js.coffee
SkillUp.LoginRoute = Ember.Route.extend
setupController: (controller) ->
controller.set 'title', "Login"
controller.set 'content', SkillUp.Session.createRecord()
<!-- login.handlebars -->
<h2>template: {{title}}</h2>
<form>
{{#with controller}}
email: {{view Ember.TextField valueBinding="email"}}
password: {{view Ember.TextField valueBinding="password" type="password"}}
<button {{action submit}}>Submit</button>
{{/with}}
</form>
As I said my goal is to remove the session.js.coffee because a rails model does not exist for it.
Help would be appreciated thanks

I don't recommend implementing $.ajax directly. I recommend keeping the DS model. This should make testing easier if you use DS.FixtureAdapter. Ideally you should keep all the ajax behind a layer in the application. You shouldn't be dropping in $.ajax in various parts of the application.
EDIT: just because you don't have a Session model in the backend doesn't mean you can't have one on the frontend. The ember app will have it's own models. Don't worry about a 1:1 mapping.

You can just use $.ajax in your controller method to post the values to rails using jQuery manually.
$.ajax('/sessions', {
type: 'POST',
data: {
email: this.get('email'),
password: this.get('password)
},
...
});
Add appropriate handlers for success and failure.

Related

How to render a template with VueJS and Axios?

I have a Vue app that generates as many forms as the user likes. Each form represent a 'risk' in this 'risks' data model:
var app = new Vue({
el: '#app',
data: {
risks: [
{
'risk_name': '', 'fields': [{'field': '', 'type': ''}], 'errors':[]
}
],
},
Then I send the 'risks' to a post API request. Then I make a second get request that brings back a template with the processed data as JSON. So far so good. However, how do I render the template (new page) with this data.
This is how I receive the data:
Submit() {
if (this.checkValidity()) {
console.info(this.risks)
axios.post('risks', this.risks)
.then(function(response) {
axios.get('risks')//This gets the data back
})
.catch(function(error) {
alert('This Error occured: ' + error)
})
}
},
This is the GET API call that I called above (Flask):
#app.route('/risks', methods=['GET'])
def getInsurancePolicyForm():
risks = getTables(app.metadata)
return render_template('form.html', risks=risks)
I can see the rendered template in developer tools, but the page the user sees remains the same.
Your page should be focussed on the risks object instead of the response from the API call.
When the user selects options, add them to the risks data object so your risks object looks like:
risks: [
{
'risk_name': '', 'fields': [{'field': 'My Field', 'type': 'text', modelToHoldData: ''}], 'errors':[]
}
]
Then, when the user clicks on Submit, by all means send it to the API but you don't need a template from there, use the risks object like so (remembering to hide the form they've just chosen their fields with):
<div v-for="risk in risks">
<label>{{risk.field}}</label>
<input type="text" v-if="risk.type === 'text'" v-model="risk.modelToHoldData" />
</div>
You can adjust the above example to add as many variations of the example as you allow the user to select.
Once all this is done and you need access to the data the user enters, you can loop through the array again and just access the modelToHoldData prop on each of the risks.

how to connect MySql db with sencha touch application

I'm new to Sencha and have been reading tons of documentation but what I haven't been able to find is the proper way to make a connection to my MySQL DB, Could someone point me in the right direction.
You don't really "connect" to a database with a Sencha Touch application. You have to create some kind of API for it to interact with. So wherever you database is hosted you might have a file like "users.php", inside that file you would have code that pulls whatever you need from the database (or inserts data into the database) and then outputs it to the browser in a JSON format.
Then in your Sencha Touch application you would make an Ajax request to that page like this:
Ext.Ajax.request({
url: 'https://www.example.com/users.php',
method: 'post',
params: {
data: data
},
success: function(response){
}
});
or you could define a proxy in your models or stores like this:
proxy: {
type: 'ajax',
api: {
create: 'http://example.com/users.php?action=create',
read: 'http://example.com/users.php?action=read',
update: 'http://example.com/users.php?action=update',
destroy: 'http://example.com/users.php?action=destroy'
},
reader: {
rootProperty: 'users'
}
}
I've written a pretty in depth tutorial if you want some more details: http://www.joshmorony.com/part-1-sencha-touch-email-facebook-log-in-system-with-php-mysql-backend/

Multi language support in Hot towel(Durandal framework)

I'm in the process of creating a application using Hot Towel, which supports multiple language (eg. english, french)
I have the referred the following links
Translating Views
Durandal localization example
And my question is how can i render views of application based on user language. If user selects english, the complete application should display contents in english. How to achieve this
I have tried something like in the second link.
define({
'root': {
welcome: 'Welcome!',
flickr: 'Flickr'
},
'fr-fr': true,
'es-es': true,
});
Is this i have to create seperate views for languages or i have to create seperate App folder for contents
Suggest me some best practices.
I don't recommend using separate views or separate folders if your project is a big one.
You can just create a file of the labels and if you use lib like knockout just data-bind these labels once (text: xxxx). In addition you can use i18n to manage labels.
With selected language just load the specific language file to your viewmodel.
EDIT1:
I'd never encountered a complete sample nor tutorial. So how I do is to :
use tools like i18n to get the key-paired dictionary file for labels in html and in some javascript code like messages.
then manually I indexed these labels by augmenting knockout viewmodels for views and variables for modules.
This is my last option in waiting for better solution. Hope this can help!
you can do some thing like this . YOu can change the APP folder if you are need do lot of locale changes you can use the following method
#{
string strAcceptLanguage;
strAcceptLanguage = System.Configuration.ConfigurationManager.AppSettings["Locale"].ToString();
if (strAcceptLanguage == "en-us")
{
#Scripts.Render("~/Scripts/vendor.js")
<script type="text/javascript" src="~/Scripts/require.js" data-main="en-US/main"></script>
}
else if (strAcceptLanguage == "es-es")
{
#Scripts.Render("~/Scripts/vendor.js")
<script type="text/javascript" src="~/Scripts/require.js" data-main="en-UK/main"></script>
}
else if (strAcceptLanguage == "fr-fr")
{
#Scripts.Render("~/Scripts/vendor.js")
<script type="text/javascript" src="~/Scripts/require.js" data-main="AUZ/main"></script>
}
}
in the Index.cshtml you can use the above code and for the you need to have value in Webconfig file
<add key="Locale" value="en-us" />
and in the SPA page each time when the user try to change the locale by pressing button or any kind of option you have to trigger a event to call a AJAX post to assess a REST api to update the Given Locale Value in the webconfig file
changeLocale: function (val) {
var name = JSON.stringify({
locale: val
});
$.ajax({
cache: false,
url: "http://localhost:49589/api/Locale",
type: "POST",
dataType: "json",
data: name,
contentType: "application/json; charset=utf-8",
processData: false,
success: function (json) {
alert(json);
location.reload();
},
error: function (json) {
alert("error" + JSON.stringify(json));
}
});
you have to write the above code in the shell.js and the shell.html has the following code
<div class="btn-group" data-toggle="buttons-radio">
<button type="button" class="btn btn-primary" data-bind="click: changeLocale.bind($data, 'en-us')">English</button>
<button type="button" class="btn btn-primary" data-bind="click: changeLocale.bind($data, 'es-es')">French</button>
<button type="button" class="btn btn-primary" data-bind="click: changeLocale.bind($data, 'fr-fr')">Japanese</button>
</div>
And the rest api like this
[HttpPost]
public string ChangeLocale(Locale l)
{
ConfigurationManager.AppSettings["Locale"] = l.locale;
return "success";
}
hope this will help

Press submit on Ajax Form from javascript / jquery timer

I would like to automatically click the submit button of an Ajax enabled form, so that the user does not have to click the button (but can optionally).
Right now, I'm working on the first boundary, which is to call the form from Javascript, so that at the very least, once i build my timer, I will have this part figured out.
I've tried many ways to do this, and NONE work. Please keep in mind that this is an ASP.NET MVC 4 Mobile application (which uses jquery.mobile) but I do have the jquery.mobile ajax disabled so that my button works at all (creating manual ajax based forms with updating divs, does not work in a jquery.mobile app because it hooks on the submit of all ajax forms).
So my current button works fine, I just can't seem to fire it programmatically.
I have my form:
<% using (Ajax.BeginForm("SendLocation", null, new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "result", HttpMethod = "POST" }, new { #id = "locationForm" }))
{ %>
<ul data-role="listview" data-inset="true">
<li data-role="list-divider">Navigation</li>
<li><%: Html.ActionLink("About", "About", "Home")%></li>
<li><%: Html.ActionLink("Support", "Support", "Home")%></li>
<li data-role="list-divider">Location</li>
<%: Html.HiddenFor(model => model.GPSLongitude)%>
<%: Html.HiddenFor(model => model.GPSLatitude)%>
<li><input type="submit" id="submitButton" value="Send" /></li>
</ul>
<% } %>
I have tried to do this in javascript:
$.ajax({
type: "POST",
url: action,
success: function () {
alert('success');
}
});
And I do get the server code firing that normally would. However, the DIV is not updated and also, the model was not intact either (it existed with all internal values null, so i assume newly instantiated).
I have also tried different ways to fire the form:
var form = $('#locationForm', $('#myForm'));
if (form == null) {
alert('could not find form');
} else {
alert('firigin on form');
form.submit(function (event) { eval($(this).attr("onsubmit")); return false; });
form.submit();
}
This did not work either:
var f = $('#locationForm', $('#myForm'));
var action = f.attr("action");
var data = f.attr("data");
$.post(action, data, function() { alert('back'); });
Which were all ways to do this that I found throughout the web.
None of them worked to fire the form and have it work the way it would normally as if a user had pressed the submit button themselves. Of course, once this fails, if I hit my submit button, it works perfectly...
Using Chrome Developer Tools, I found that the $.ajax call needs to have valid data before it will even attempt to function.
I was getting a silent Internal 500 Error on the post. But of course because of AJAX it was silent and the controller was not firing because it didn't get past IIS.
So I found out that the data I was sending, saying its JSON, was not and the .serialize() does not use JSON formatting. I tried to incorporate the JSON Javascript libraries to convert the object into JavaScript, however, this does not work either, because the Data Model object (or the form object) seems to not be compatible with those libraries. I would get errors in the JavaScript console and those libraries would crash when trying.
I decided to actually just pass the object I want manually:
var encoded = '{ GPSLongitude: ' + $('#GPSLongitude', $('#myForm')).val() + ',GPSLatitude: ' + $('#GPSLatitude', $('#myForm')).val() + '}';
Which passed the hidden fields i wanted to send (GPS LON/LAT) to the controller, and the model was intact in the controller call!
Now, for anyone that is reading this answer. the actual AJAX update process that is supposed to update the view, failed to work. Although for my purpose, I did not actually need the view to update correctly. Eventhough a partial view is returned, the special AJAX call seems to break the linkage between the form's div to update.
However, since the data was passed to the controller intact, this basically passed the GPS data that I needed to the server which was my ultimate goal.
make sure you are including the proper js libraries.
you need. jquery.js, jquery.unobtrusive-ajax.js
make sure unobtrusivejavascriptenabled = true in the web.confg
<appSettings>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
please try $('#locationForm').submit();
does it give error message?
if you're using i.e. you can look use the develper tools to look at network traffic to make sure nothing is sent.

How to update Rails partials at set intervals with $.ajax()?

I'm building a sort-of clone of CoverItLive in Rails 3.1 and want to have the stream of comments automatically update. I'm using a partial in the view to display comments. There's a lot of info out there on doing UJS and AJAX wit forms or buttons or links in Rails, but I can't find any specific examples for what I need to do.
I'm assuming that .ajax() is the best approach, but I've never used it before and not sure if I need to provide .js.erb files when using this particular function? Could I just have the controller send JSON back to the client and go from there, or is there a better approach in rails?
This is what I'm thinking so far, based on what I read at another question:
setInterval(function() {
$.ajax({
type: 'GET',
url: ''<%= comments_path(:json) %>'',
data: {
data: "comments_data"
},
cache: false,
success: function(result) {
if (result == "true"){
alert("true");
}else{
alert("false");
}
}
});
}, 3000);
As an alternative you should look into Private Pub, a gem that Ryan Bates has put togeather. See a screencast about it on railscasts.
The trouble with your solution is now often you server will be hit unnecessarily, i guess it depends on the number of concurrent users you thing will be viewing this page.
if you do go down your route the .js.erb could just have a somthing like this in it:
$('#id_of_area_to_replace').html("<%= escape_javascript(render"comments/index") %>")
This would replace the whole area else you could just append new comments to the bottom of the area