So I've implemented the Markitup bbcode editor in my Rails application and I'm currently attempting to get the preview functionality working. I followed a 4 year-old blog entry install markitup! in Ruby on Rails which got me pretty close to what I need to do. So far, when I press the preview button it renders an iframe that displays a blank template for me.
In my jquery.markitup.js I have this line as one of the options:
previewTemplatePath: '/templates/preview',
Which will make an ajax request to retrieve the page for the route:
resources :templates do
collection do
get :preview
end
end
Currently the preview action simply sets render :layout => false so I don't duplicate html. As for the preview.html.erb page itself I simply have:
<%= bb(params[:data]) %>
And the idea behind this is to send the markup entered in the editor into the params data hash and then pass that through my bb code helper which does the parsing and returns some html.
The Problem
I don't know how to fill that params[:data] with the bb code entered into the markitup editor. Does anybody know how I can send that off?
Extra details:
I thought I would include all the options I'm passing off to markItUp:
options = { id: '',
nameSpace: '',
root: '',
previewInWindow: '', // 'width=800, height=600, resizable=yes, scrollbars=yes'
previewAutoRefresh: true,
previewPosition: 'after',
previewTemplatePath: '/templates/preview',
previewParser: false,
previewParserPath: '',
previewParserVar: 'data',
resizeHandle: true,
beforeInsert: '',
afterInsert: '',
onEnter: {},
onShiftEnter: {},
onCtrlEnter: {},
onTab: {},
markupSet: [ { /* set */ } ]
};
The previewTemplatePath and the previewParserPath options needed to be set when I make the call to markItUp!.
The previewTemplatePath points to the view that displays the rendered preview and the previewParserPath is meant to point to your controller action that handles the parsing and data parameter. Assuming you're following dry conventions both paths should be the same as it was in my case.
For a better look at how to integrate markItUp! with rails check out the source for branch14's markupitup gem.
Related
I followed Railscast Tutorial to set up mercury editor.
mercuy.js
$(window).bind('mercury:ready', function() {
var link = $('#mercury_iframe').contents().find('#edit_link');
Mercury.saveUrl = link.data('save_url');
link.hide();
});
$(window).bind('mercury:saved', function() {
window.location = window.location.href.replace(/\/editor\//i, '/');
});
views/quotations/show.html.erb
<p><%= link_to "Edit Page", "/editor" + request.path, id: "edit_link", data: {save_url: mercury_update_quotation_path(#quotation)} %></p>
mercury.html.erb
new Mercury.PageEditor(saveUrl, {
saveStyle: 'form', // 'form', or 'json' (default json)
saveMethod: null, // 'PUT', or 'POST', (create, vs. update -- default PUT)
visible: true // boolean - if the interface should start visible or not
});
routes.rb
resources :quotations do
member { post :mercury_update}
end
It shows the following error
Mercury was unable to save to the url: http://localhost:3000/quotations/1
Console output
Started PUT "/quotations/1" for 127.0.0.1 at 2015-03-07 19:20:49 +0530
AbstractController::ActionNotFound (The action 'update' could not be found for QuotationsController):
It worked well for static id's but not like this. Please help me to solve this error.
Your error is telling you
ActionNotFound
Meaning you are missing the mercury_update in your QuotationsController. Try adding
def mercury_update
quote = Quotations.find(params[:id])
quote.FIELD_FROM_YOUR_DB = params[:content][:quotation_content][:value]
quote.save!
render text:""#tells mercury of successful save (I think)
end
If that doesn't work, try checking your console for the the parameters mercury is passing around. It should look something like
Started PUT "/quotations/1/mercury_update" for ...
Parameters:{"content"=>{...}}
Notice that it is a PUT request, that's what Mercury is telling you that it's doing. Thus the route needs to be updated
resources :quotations do
member do
put 'mercury_update' #this may change your path to mercury_update_quotation_page_path(#quotation)
end
end
Also, ensure that resources :quotations is not defined twice in config/routes.rb. I defined it following that tutorial and then ran
rails g scaffold quotations
in order to auto-generate views and such. This command defined quotations again at the top of my config/routes.rb as
resources :quotations
#...
resources :quotations do #... This was my definition
thus ignoring my definition with the member 'mercury_update'.
Finally, let me know if your saved response is working, as mine is not. GL!
I'm using Node.js, Express and Jade and I'm trying to figure out how to post, validate & process form data.
In my jade file I create a contact form:
div#contact-area
form(method='post',action='')
label(for='name') Name:
input(type='text',name='name',id='name')
label(for='email') Email:
input(type='text',name='email',id='email')
input(type='submit',name='submit',value='Submit').submit-button
I'm then utilising the module 'express-validator' to validate the form as follows:
var express = require('express')
,routes = require('./routes')
,http = require('http')
,path = require('path')
,expressValidator = require('express-validator')
;
var app = express.createServer();
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade'); //not needed if we provide explicit file extension on template references e.g. res.render('index.jade');
app.use(express.bodyParser());
app.use(expressValidator);
app.use(express.methodOverride());
app.use(app.router);
});
//display the page for the first time
app.get('/mypage', function(req,res){
res.render('mypage', {
title: 'My Page'
});
});
//handle form submission
app.post('/mypage', function(req,res){
req.assert('name', 'Please enter a name').notEmpty();
req.assert('email', 'Please enter a valid email').len(6,64).isEmail();
var errors = req.validationErrors();
if( !errors){
sendEmail(function(){
res.render('mypage', {
title: 'My Page',
success: true
});
});
}
else {
res.render('mypage', {
title: 'My Page',
errors: errors
});
}
});
So there are three scenarios where my pages is rendered, and each one has access to different local variables:
When the page is loaded for the first time (errors=undefined,success=undefined)
When the form is submitted and there are errors (errors=array,success=undefined)
When the form is submitted and there are no errors (errors=undefined,success=true)
So my main problems are that:
When my Jade page is loaded, it seems to throw an error when I attempt to access a variable that doesn't exist. For example, I want to see if the variable 'success' is set, and if it is I want to hide the form and display a "thanks" message. Is there an easy way to handle a variable in Jade that will either be undefined or a value?
When the form has been submitted and there are validation errors, I want to show an error message (this isn't a problem) but also populate the form with the variables that were previously submitted (e.g. if the user provided a name but no email, the error should reference the blank email but the form should retain their name). At the moment the error message is displayed but my form is reset. Is there an easy way to set the input values of the fields to the values in the post data?
You can fix that by using locals.variable instead of just variable. Also you can use javascript in jade.
-locals.form_model = locals.form_data || {};
I used two ways to solve this problem. The first one is to re-render the view and you pass the req.body as a local. I have a convention that my forms use form_model.value for their field values. This method is works well for simple forms but it starts to breakdown a little when you form is relying on data.
The second method is to pass your req.body to session then redirect to a route that renders the form. Have that route looking for a certain session variable and use those values in your form.
Inside your jade file add error msg and then run your code.
Simply update your jade code with below code:
div#contact-area
ul.errors
if errors
each error, i in errors
li.alert.alert-danger #{error.msg}
form(method='post',action='')
label(for='name') Name:
input(type='text',name='name',id='name')
label(for='email') Email:
input(type='text',name='email',id='email')
input(type='submit',name='submit',value='Submit').submit-button
I'm trying to add some Ajax functionality in my Rails 3 app.
Specifically, I want a button that will submit an Ajax request to call a remote function in my controller, which subsequently queries an API and returns a JSON object to the page.
Once I receive the JSON object I want to display the contents.
All of this with the new Rails 3 UJS approach, too. Is there a good example/tutorial for this online somewhere? I haven't been able to find one on google. A simple example using a button as the entry point (ie, the user clicks the button to start this process) would work, too.
Edit
Let me try this with a different approach. I want to have this button query an external API, which returns JSON, and display that JSON on the page. I have no idea where to even begin. Does the button itself query the external API? Do I need to go through the controller, and have the controller query the external API, get the JSON, and give the JSON back to this page? How do I display/access the contents of this JSON? I honestly can't find a good Rails 3.x example of how to handle JSON...
Here is a start:
First create your button with a link_to method in your view, for example:
=link_to "delete", "#{invitation_path(invitation)}.json", :method=>:delete, :remote=>true, :class=>"remove", :confirm=>'Are you sure you?'
Note that I am appending ".json" to the url of my resource. This is just an example of a an AJAX delete, google link_to to see the meaning of the parameters. The concept if that you make your HTTP request with the parameter :remote set to true, in other words this is translated to an AJAX call from your browser.
Second, write some javascript so that you can process what ever is the result of the AJAX call your browser will make when the user click on the link_to of step 1. For details you can see this blog post: http://www.alfajango.com/blog/rails-3-remote-links-and-forms/
An example from my site:
jQuery(function($) {
// create a convenient toggleLoading function
var toggleLoading = function() { $("#loading").toggle() };
$("#pending_invitation")
.live("ajax:loading", toggleLoading)
.live("ajax:complete", toggleLoading)
.live("ajax:success", function(event, data, status, xhr) {
var response = JSON.parse(xhr.responseText)
if (response.result == "ok") {
$(this).fadeOut('fast');
}
else {
var errors = $('<div id="error_explanation"/>');
errors.append('<h2>Pending invitation action error</h2><ul><li>' + response.error + '</li></ul>');
$('#new_invitation_error').append(errors)
}
});
});
where you can see that I parse the returned json and and change the html on the page based on that. Note that this js uses the CCS ids and classes defined in the top view that is not included here.
If you now want to write you own controller to spit out the json here is an example:
class InvitationsController < ApplicationController
respond_to :html, :json
# other methods here
# ...
def destroy
#invitation = Invitation.find(params[:id])
respond_to do |format|
if #invitation
#invitation.destroy
flash[:success] = I18n.t 'invitations.destroy.success'
format.json { render :json =>{:result => "ok", :message=>"Invitation #{params[:id]} was destroyed", :resource_id=>params[:id] } }
else
format.json { render :json => { :result=>"failed", :error=>"Cannot find Invitation #{params[:id]}", :resource_id=>params[:id] } }
end
end
end
end
Hope this help.
Old question, but a really good overview of Ajaxifying Rails applications is:
Ajax in Rails 3.1 - A Roadmap
Also consider returning errors in the following format:
render :json => #myobject.to_json, :status => :unprocessable_entity
This will ensure that your client can process the response as an error.
(First of all English is not my native language, I'm sorry if I'll probably be mistaken).
I've created Yii Web app where is input form on the main page which appears after button click through ajax request. There is a "Cancel" button on the form that makes div with form invisible. If I click "Show form" and "Cancel" N times and then submit a form with data the request is repeating N times. Obviously, browser binds onclick event to the submit button every time form appears. Can anybody explain how to prevent it?
Thank you!
I've had the exact same problem and there was a discussion about it in the Yii Forum.
This basically happens because you are probably returning ajax results with "render()" instead or renderPartial(). This adds the javascript code every time to activate all ajax buttons. If they were already active they will now be triggered twice. So the solution is to use renderPartial(). Either use render the first time only and then renderPartial(), or use renderPartial() from the start but make sure the "processOutput" parameter is only set to TRUE the first time.
Solved!
There was two steps:
First one. I decided to add JS code to my CHtml::ajaxSubmitButton instance that unbind 'onclick' event on this very button after click. No success!
Back to work. After two hours of digging I realized than when you click 'Submit' button it raises not only 'click' event. It raises 'submit' event too. So you need to unbind any event from whole form, not only button!
Here is my code:
echo CHtml::submitButton($diary->isNewRecord ? 'Создать' : 'Сохранить', array('id' => 'newRecSubmit'));
Yii::app()->clientScript->registerScript('btnNewRec', "
var clickNewRec = function()
{
jQuery.ajax({
'success': function(data) {
$('#ui-tabs-1').empty();
$('#ui-tabs-1').append(data);
},
'type': 'POST',
'url': '".$this->createUrl('/diary/newRecord')."',
'cache': false,
'data': jQuery(this).parents('form').serialize()
});
$('#new-rec-form').unbind();
return false;
}
$('#newRecSubmit').unbind('click').click(clickNewRec);
");
Hope it'll help somebody.
I just run into the same problem, the fix is in the line that starts with 'beforeSend'. jQuery undelegate() function removes a handler from the event for all elements which match the current selector.
<?php echo CHtml::ajaxSubmitButton(
$model->isNewRecord ? 'Add week(s)' : 'Save',
array('buckets/create/'.$other['id'].'/'.$other['type']),
array(
'update'=>'#addWeek',
'type'=>'POST',
'dataType'=>'json',
'beforeSend'=>'function(){$("body").undelegate("#addWeeksAjax","click");}',
'success'=>'js:function(data) {
var a=[];
}',
),
array('id'=>'addWeeksAjax')
); ?>
In my example I've added the tag id with value 'addWeeksAjax' to the button generated by Yii so I can target it with jQuery undelegate() function.
I solved this problem in my project this way, it may not be a good way, but works fine for me: i just added unique 'id' to ajax properties (in my case smth like
<?=CHtml::ajaxLink('<i class="icon-trash"></i>',
$this->createUrl('afisha/DeletePlaceAjax',
array('id'=>$value['id'])),
array('update'=>'.data',
'beforeSend' => 'function(){$(".table").addClass("loading");}',
'complete' => 'function(){$(".table").removeClass("loading");}'),
array('confirm'=>"Уверены?",'id'=>md5($value['id']).time()))
?>
).
Of course, you should call renderPartial with property 'processOutput'=true. After that, everything works well, because every new element has got only one binded js-action.
text below copied from here http://www.yiiframework.com/forum/index.php/topic/14562-ajaxsubmitbutton-submit-multiple-times-problem/
common issue...
yii ajax stuff not working properly if you have more than one, and if
you not set unique ID
you should make sure that everything have unique ID every time...
and you should know that if you load form via ajax - yii not working
well with it, cause it has some bugs in the javascript code, with die
and live
In my opinion you should use jQuery.on function. This will fire up event on dynamically changed content. For example: you're downloading some list of images, and populate them on site with new control buttons (view, edit, remove). Example structure could looks like that:
<div id="img_35" class='img-layer'>
<img src='path.jpg'>
<button class='view' ... />
<button class='edit' ... />
<button class='delete' ... />
</div>
Then, proper JS could look like this ( only for delete, others are similiar ):
<script type="text/javascript">
$(document).on('click', '.img-layer .delete', function() {
var imgId = String($(this).parent().attr('id)).split('_')[1]; //obtain img ID
$.ajax({
url: 'http://www.some.ajax/url',
type : 'POST',
data: {
id: imgId
}
}).done({
alert('Success!');
}).fail({
alert('fail :(');
});
}
</script>
After that you don't have to bind and unbind each element when it has to be appear on your page. Also, this solutiion os simple and it's code-clean. This is also easy to locate and modify in code.
I hope, this could be usefull for someone.
Regards
. Simon
%a{:href => "/new_game?human_is_first=true", :remote => "true"}
%span Yes
Above is my link. Just wondering how to handle this. I need to be able to execute some javascript. Below is a .js.erb file from back when I using rails.
$('.welcome_container').fadeOut(500, function(){
$( '.shell' ).html( "<%= escape_javascript( render( :partial => "board/board" ) ) %>" );
$('.board_container').fadeIn(500);
});
So, my question is, Once /new_game is called in app.rb, I want to be able to send some javascript to the current page (without leaving the page, and have the partial rendered)
See my answer to your other recent question for a comprehensive setup for sending and receiving HTML partials in a production Sinatra app.
As Sinatra is a nice lightweight framework, you are free (forced?) to come up with your own workflow and code for implementing partials and handling such calls. Instead of my explicit route-per-partial, you might choose to define a single regex-based route that looks up the correct data based on the URL or param passed.
In general, if you want Sinatra to respond to a path, you need to add a route. So:
get "/new_game" do
# This block should return a string, either directly,
# by calling haml(:foo), erb(:foo), or such to render a template,
# or perhaps by calling ...to_json on some object.
end
If you want to return a partial without a layout and you're using a view, be sure to pass layout:false as an option to the helper. For example:
get "/new_game" do
# Will render views/new_game.erb to a string
erb :new_game, :layout => false
end
If you want to return a JSON response, you should set the appropriate header data:
get "/new_game" do
content_type :json
{ :foo => "bar" }.to_json
end
If you really want to return raw JavaScript code from your handler and then execute that...well, here's how you return the JS:
get "/new_game" do
content_type 'text/javascript'
# Turns views/new_game.erb into a string
erb :new_game, :layout => false
end
It's up to you to receive the JS and *shudder* eval() it.