several call when I hit a action inside jqgrid with jquery - java

I have a jqgrid component inside my page and the rows of the grid are create with values and actions, for example:
colum: name adresss job edit
row 1: jorge my adress architect [value]
I populate the grid with several rows from a database and aech row have a value in column edit to the personal page for editing actions.
this value have this structure:
<div><span class="edit" idperson="' + items[i].id + '">Edit</span></div>
in the same script I put this:
$('.edit').live('click', this.clickedit);
and the function is:
clickedit: function(){
$.ajax('person/personedit.htm', {
cache: false,
type : 'POST',
data : { idperson: $(this).attr('idperson')},
success : function(response){
//some actions.....
}
});
},
in my java code I have a spring controller that recieve this call from jquery and do something.
The first time I clic the Edit action in a row all is OK, but after a while working with the application I see that a single edit action is called several times so the clickedit function execute 2, or 3 or 4 times and my java code are hit the same numbers of times.
any idea about this issue???
UPDATE:
I start to using onCellSelect now. But I have a problem. In a single cell I can put 3 differents action in this way:
var actions = 'editedOK ? '<div><span class="edit1" idperson="' + items[i].id + '" >EDITOK1 </span><span class="edit2" idperson="' + items[i].id + '">EDITOK2</span></div>' : '<div><span class="editnook1" idperson="' + items[i].id + '">EDITNOOK1</span></div>';
if actions = true I see in the same cell "EDITOK1 EDITOK2" and if actions = false I see in this cell "EDITNOOK1"
everyone of this actions have associates functions with differents behaviour when I clic in it.
If I use onCellSelect it´s possible to determinate when I hit EDITOK1, when I hit EDITOK2 and when I hit EDITNOOK1. More important is to determinate between EDITOK1 and EDITOK2.

I suppose that you calls $('.edit').live('click', this.clickedit); multiple times. It's the reason why this.clickedit handler will be called more as one time.
I recommend you don't use any explicit binding of this.clickedit callback. Instead of that you can use beforeSelectRow or onCellSelect. See the answer and this one for the corresponding code examples.

Related

Ng-grid doesn't update rowHeight

I have been working on trying to find a way of changing the rowHeight in my Html so I can put my directiveA(displays grid) in multiple places with different rowHeights. When I finally get that working I find out that it won't update on my webpage. What I have come to is that the directiveB(sets value from html to rowHeight)
.directive('getHeight', function(){
return{
controller: 'BNotesCtrl',
scope:{
'rowHeight': '='
},
link: function(scope){
scope.theRowHeight = scope.rowHeight;
scope.options.rowHeight = scope.theRowHeight;
}
}
})
Anyways, as you can see it uses the controller BNotesCrtl and in that is my options for ng-grid. And with console logs I have found out that it doesn't change the value of rowHeight until BNotesCrtl runs through once. And by that time the grid is already drawn and no longer can be updated. So is there a way of running through BNotesCrtl with the directive so I can update the options before it's too late?

Ruby on Rails, How to Update Div with Ajax on like/unlike

So the problem I am having is getting my like/unlike button to refresh with ajax in my Ruby on Rails app, here is my code:
app/views/_comment.html.haml
- likes = comment.likes
%div.comment{id: "comment-#{comment.id}"}
.comment-avatar
.medium-user-avatar.avatar-canvas
- if comment.user.avatar_url
= image_tag comment.user.avatar_url(:medium)
- else
%span.medium-user-initials.initials-decoration
= comment.user.avatar_initials
%span.comment-username= link_to(comment.user_name, "#")
%span.comment-body~ markdown(comment.body)
.comment-time
= time_ago_in_words(comment.created_at) + " ago"
- if can? :like, comment
= " · "
- if likes.find_by_user_id(current_user.id).nil?
= link_to "Like", like_comment_path(comment), method: :post, remote: true
- else
= link_to "Unlike", unlike_comment_path(comment), method: :post, remote: true
- if comment.user == current_user
= " · "
= link_to "Delete", comment_path(comment), method: :delete, remote: true,
:data => { :confirm => "Are you sure you want to delete this comment?" }
- if likes.count > 0
.comment-likes
- likers = likes.map { |like| link_to(like.user_name, "#") }
- if likers.length > 1
- likers = likers.slice(0, likers.length - 1).join(", ").concat(" and " + likers.slice(-1))
- else
- likers = likers[0]
= "Liked by #{likers}".html_safe
app/controllers/comments_controller.rb
class CommentsController < BaseController
load_and_authorize_resource
def destroy
destroy!{ discussion_url(resource.discussion ) }
end
def like
comment_vote = resource.like current_user
Event.comment_liked!(comment_vote)
#redirect_to discussion_url(resource.discussion )
render :partial => "like"
comment_likes
end
def unlike
resource.unlike current_user
#redirect_to discussion_url(resource.discussion)
render :partial => "unlike"
comment_likes
end
def comment_likes
render :partial => "comment_likes"
end
end
and then the .js.erb files for like, unlike and comment_likes:
app/views/_like.js.erb
$(".comment-time a#like").html("<%= escape_javascript(render('.comment-time a#like'")
app/views/_unlike.js.erb
$(".comment-time a#unlike").html("<%= escape_javascript(render('.comment-time a#unlike'")
app/views/_comment_likes.js.erb
$(".comment-likes a##").html("<%= escape_javascript(render('.comment-likes a##'")
Currently clicking like will update the database but will not show the changes until a page refresh, I just want to refresh the individual div's with ajax. A little more information about the div's could help so the ruby creates the html and contained in that as an example is or when already liked I just need to refresh these divs to show the latest from the database aswell as which contains http://localhost:3000/comments/7/unlike 500 (Internal Server Error)"
The rest of the scripting has been done in coffeescript if that matters? I read that the controller functions should use .js.erb so hope this isn't affecting it all. (Im sure my js.erb's are wrong)
I'm not sure if this is the main problem but one thing to fix would be the render statement in your .js.erb files.
The Rails render method requires as its argument the erb template or action to render. When you call:
render('.comment-time a#unlike')
Rails will try to find a template with the name ".comment-time a#unlike" somewhere in your view path which will probably raise some kind of error. Make sure you pay attention to the difference between what's happening in your javascript (in the client) in your application (on the server.)
So one way to fix this would be as follows. First check what part of the view you want to update, for simplicity's sake because you already have the _comment partial let's use that. Second figure out which part in the dom it should replace, in your case the div with the current comment's ID. We can then do the following:
$("#comment-<%= #comment.id %>").replace_html(
"<%= escape_javascript render('comments/comment', :comment => #comment) %>"
);
This will render the _comment.html.erb partial in app/views/comments, insert the result (escaped) into the javascript in your (dis-)like.js.erb and send that back to the browser to execute. The browser will then replace_html on the comment's div (indicated by the ID.)
Because we're replacing the whole comment div you can use the same method for both like and dislike. If you need to save bandwidth you could fine tune it to only re-render the like button itself, but for now this will work.
The problem is your Controller does not know how to respond to the ajax request. By default the render method will render html.erb or in your case html.haml templates.
Unless you do something like:
respond_to do |format|
format.js { comment_likes }
end
Now if an ajax requests comes in the _comments_likes.js.erb template will be rendered.
If you have more of these ajaxy type questions there are efforts being put into rewriting the ajax guides for rails.
And by the by, please consider cleaning up your view.

Form submit and HttpServletRequest

I'm facing this problem with regards to Forms and Requests. I'm using sencha and javascript to create a webpage that POSTs a form to a java web application which pulls data from a database and formats it before returning a html page to the client.
The problem I'm facing is that for some reason, while the form does get filled(checked using the debugger in chrome), the java program does not recognise the parameter within the form, and instead reads it as null.
I'm following the method of setting the form from an old java program, which works, however it fails for mine. Does anyone know how I can solve this or where I might be doing wrong?
I've included the javascript and java codes where I decide which page to return below.
Javascript handler for function call to submit form:
var MenuA = function() {
simple.getComponent('flag').setValue('MenuA');
simple.getEl().dom.action = './Soap';
simple.getEl().dom.method = 'POST';
simple.submit();}
Java code to decide choice of page:
if (request.getParameter("flag").matches("MenuA")) {
choice = 2;
} else if (request.getParameter("flag").matches("MenuB")) {
choice = 3;}
FormPanel Code:
var simple = new Ext.form.FormPanel({hidden:true,standardSubmit:true,
items:[
{xtype: 'textfield', hidden: true, name : 'password', label: 'Password', id:'password'}
,{xtype: 'textfield', hidden: true, name : 'user', label: 'user', id:'user'}
,{xtype: 'textfield', hidden: true, name: 'flag', label: 'flag', id: 'flag'}]})
Your
request.getParameter("flag").matches("MenuA");
method is looking for a form element whose name is "flag".
Since your form may not contain the flag field so it assumes it to be null.
So, to overcome you can add an input field to the form with name "flag" and put put your desired value in it.
I think this should work for you.
Nevermind. Found the problem. I didn't realise the form was not being sent properly. Sorry for the trouble!

How to test AjaxFormChoiceComponentUpdatingBehavior in WicketTester

In my Wicket application I used one radio button with "yes" and "no" options. If I select "No", I should display one dropdown choice. I wrote code using AjaxFormChoiceComponentUpdatingBehavior. How do I unittest this using WicketTester?
Solution for Wicket 1.5.x:
AbstractAjaxBehavior behavior = (AbstractAjaxBehavior)WicketTesterHelper.
findBehavior(getTester().getComponentFromLastRenderedPage("path:to:component"),
AjaxFormChoiceComponentUpdatingBehavior.class);
getTester().executeBehavior(behavior);
First select the radio button that you want.
form.select("path to radio button", 0/1)
Then execute ajax behaviour:
tester.executeBehavior((AbstractAjaxBehavior)tester.getComponentFromLastRenderedPage("path to radio buttons").getBehaviors().get(0));
Here is my piece of code which works perfectly for me with select box but should fiat as well for radio button if you change Behaviour class. Needed steps are:
Insert new value into form (use FormTester)
Find behaviour
Execute behaviour on change
Here is an example of code:
//simulate insert new value
FormTester formTester = tester.newFormTester(PANEL_ID + FORM);
formTester.setValue("selectBox", "newValue");
//Find onchange behaviour
AjaxFormComponentUpdatingBehavior behavior =
(AjaxFormComponentUpdatingBehavior) WicketTesterHelper.findBehavior(
tester.getComponentFromLastRenderedPage(PANEL_ID + FORM + ":" + "selectBox"),
ajaxFormComponentUpdatingBehavior.class);
//execute onchange
tester.executeBehavior(behavior);
I missed the par how to update form value in previous answers.
If the radio button is on a form I think you should use the FormTester class:
http://wicket.apache.org/apidocs/1.4/org/apache/wicket/util/tester/FormTester.html
For an example of an Ajax form submit test you can take a look at:
http://www.java2s.com/Open-Source/Java-Document/J2EE/wicket-1.4/org/apache/wicket/ajax/form/AjaxFormSubmitTest.java.htm
Try something like this:
tester.executeAjaxEvent("form:myRadioButtonId", "onchange");
This turns out to be somewhat painful, at least in Wicket 1.4 (I haven't tried with 1.5).
Via a web search, I found hints in Mischa Dasberg's blog. Basically, you can't use the BaseWicketTester.executeAjaxEvent((String componentPath, String event) method because the behavior you're using isn't an AjaxEventBehavior and you can't use the BaseWicketTester.executeBehavior(final AbstractAjaxBehavior behavior) because it wipes out the request parameters.
Mischa's solution was to implement his own executeBehavior method in a parent test case, which worked for his situation, but not for my need, as it assumed the request parameter id was the same as the full component path.
I've done something similar by implementing my own executeAjaxBehavior in an extension of WicketTester, but assuming (as is true in my case) that the request parameter is the last ":" separated section of the component path:
public void executeAjaxBehavior(String path, String value) {
AbstractAjaxBehavior behavior = (AbstractAjaxBehavior) getComponentFromLastRenderedPage(path).getBehaviors().get(0);
CharSequence url = behavior.getCallbackUrl(false);
WebRequestCycle cycle = setupRequestAndResponse(true);
getServletRequest().setRequestToRedirectString(url.toString());
String[] ids = path.split(":");
String id = ids[ids.length-1];
getServletRequest().setParameter(id, value);
processRequestCycle(cycle);
}
Both his solution and mine (based on his) also assume that the behavior is the first (or only) one on the component.
This is a bit clunky, but something like this may work for you.
It might be better if the ids and behavior were gotten separately and passed as parameters, and of course you might do well to find the first behavior that actually was an AjaxFormChoiceComponentUpdatingBehavior instead of blithely assuming it was the first behavior, but this is a start.
This is also similar code to what's inside the BaseWicketTester class for the other behavior testing methods, which might be worth looking through.

Saving a web page as image

As a hobby project I am exploring the ways to save a web page (HTML) as image, mostly programatically using c/c++/javascript/java. Till now I have come across the following ways:
Get the IHTMLElement of page body and use it to query for IHTMLElementRender and then use its DrawToDC method (Ref: http://www.codeproject.com/KB/IP/htmlimagecapture.aspx ). But the problem is that it did not work for all the pages (mostly pages having embedded iframes).
Another way which i can think of is to use some web browser component and when the pages is fully loaded then capture it using BitBlt (Ref: http://msdn.microsoft.com/en-us/library/dd183370%28VS.85%29.aspx ). But the problem is that the page I have requested may be longer than my screen size and it will not fit into the web browser component.
Any direction/suggestion to resolve above issues or an alternative approach is greatly appreciated.
If you use Python, there's pywebshot and webkit2png. Both of them have some dependencies, though.
Edit: Oops, Python is not in your list of preferred languages. I'll leave this answer here anyway, because you said "mostly" and not "exclusively".
Another (somewhat roundabout) option would be to run a server like Tomcat and use Java to call a command-line tool to take a screenshot. Googling for "command line screenshot windows" comes up with some reasonable-looking possibilities. Besides running a server, though, I don't know a good way to run local executables from javascript. This method would make it cross-browser, though, which is a plus (just make an ajax call to the script when you want a screenshot).
Unfortunately I don't actually know how to deploy war files. It might be more trouble to use Tomcat; I mentioned it because Java was a preferred language. It would be fairly simple to run XAMPP and use this PHP snippet, and you wouldn't really have to learn php:
<?php
exec("/path/to/exec args");
?>
EDIT
You know, I'm not sure that really answers your question. It's one way, but it's coming at it from the JavaScript end rather than the scripting end. If you want to do it via scripting, you could always use Selenium. It supports capturing screenshots of an entire page, and can be controlled via Java.
Well finally able to crack it by going through these two articles:
http://www.codeproject.com/KB/GDI-plus/WebPageSnapshot.aspx [c# code - IE]
http://www.codeproject.com/KB/graphics/IECapture.aspx [c++ & GDI - IE]
Can't share the code, but the above two articles will give you the best possible solution.
Also have a look at:
https://addons.mozilla.org/en-US/firefox/addon/3408/ [firefox + javascript]
Above things are still ok. BUT not guaranteed to work always. Check the below link:
How do I render the scrollable regions of a canvas with IViewObject::Draw?
If you are OK using javascript for it, I suggest going with phantomjs
Example from http://fcargoet.evolix.net/
var page = new WebPage(),
address = 'http://dev.sencha.com/deploy/ext-4.0.7-gpl/examples/feed-viewer/feed-viewer.html';
page.viewportSize = {
width : 800,
height : 600
};
// define the components we want to capture
var components = [{
output : 'feed-viewer-left.png',
//ExtJS has a nice component query engine
selector : 'feedpanel'
},{
output : 'feed-viewer-preview-btn.png',
selector : 'feeddetail > feedgrid > toolbar > cycle'
},{
output : 'feed-viewer-collapsed.png',
//executed before the rendering
before : function(){
var panel = Ext.ComponentQuery.query('feedpanel')[0];
panel.animCollapse = false; // cancel animation, no need to wait before capture
panel.collapse();
},
selector : 'viewport'
}];
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
} else {
/*
* give some time to ExtJS to
* - render the application
* - load asynchronous data
*/
window.setTimeout(function () {
components.forEach(function(component){
//execute the before function
component.before && page.evaluate(component.before);
// get the rectangular area to capture
/*
* page.evaluate() is sandboxed
* so that 'component' is not defined.
*
* It should be possible to pass variables in phantomjs 1.5
* but for now, workaround!
*/
eval('function workaround(){ window.componentSelector = "' + component.selector + '";}')
page.evaluate(workaround);
var rect = page.evaluate(function(){
// find the component
var comp = Ext.ComponentQuery.query(window.componentSelector)[0];
// get its bounding box
var box = comp.el.getBox();
// box is {x, y, width, height}
// we want {top, left, width, height}
box.top = box.y;
box.left = box.x;
return box;
});
page.clipRect = rect;
page.render(component.output);
});
// job done, exit
phantom.exit();
}, 2000);
}
});

Categories

Resources