Grails 2.4.2 Ajax not working for OnChange - ajax

I have to dynamically load a set of values based on the value i chose in another drop down.
In Controller I have the following code,
def ajaxGetCities(params){
println params.id
def userCustPlantDetails = utilitySummaryService.fetchUserCustPlantDetails('PHILL00')
def data = []
userCustPlantDetails?.get('UserPlantList').collect{
data << it.pwr_plt_nme
}
[data: data]
}
In gsp I have :
<g:select class="btn btn-default" name="viewValue" from="${view}" onchange="${remoteFunction(
action:'ajaxGetCities',
params:'\'id=\' + escape(this.value)',
onSuccess :'updateCity(data)')}"></g:select>
When I change the value of dropdown , i see the trigger and controller action is called. Post that Javascript updateCity is not responding. What am I missing ? What is the difference between onComplete and OnSuccess.

Related

Making an AJAX POST to a class based view

I have a class based view that displays a page and handles POST requests, like so:
class citywall (View):
def get(self, request, *args, **kwargs):
template_name = 'citywall.html'
city_slug = kwargs['city_slug']
context = self.get_context_data(city_slug)
return render_to_response(template_name, context, RequestContext(request))
def post(self, request, *args, **kwargs):
if request.is_ajax:
if request.POST.has_key('comment'):
#process comment
...
if request.POST.has_key('vote'):
#process vote
...
The problem is when I try to POST the form with AJAX, two requests are being sent. The Ajax request and then a regular POST request.
This is my comment form in html:
<form class="comment_form" data-id="{{post.id}}" method="POST" >{% csrf_token %}
<textarea rows = "1" name="comment" class="form-control" placeholder="Write a comment..." ></textarea>
<button type="submit" class="btn btn-info">Go!</button>
</form>
This is the jQuery code:
var comment_form = $('.comment_form')
comment_form.submit(function(){
var post_id = $(this).data('id');
var comment = $(this).find('textarea[name="comment"]').val();
$.ajax({
url: "",
dataType:"json",
type:"POST",
data:{
comment: comment,
post_id: post_id,
csrfmiddlewaretoken:'{{csrf_token}}',
},
success:function(json)
{
alert(json);
},
});
});
When I submit the form this is happening:
AJAX POST is made with its json data(post_id, comment, csrf).
Response for the AJAX post is received back in browser.
POST is made with html form data(comment and csrf).
why is a second POST being made?
I have several types of forms on the page for example. comment form, voting form, etc and I want to make all of them AJAX. Is it a good idea to implement all of them with the above mentioned method?
The second POST with your form data is sent because your submit event handler doesn't return False. If you want to prevent the form from submitting when clicking the submit button, you have to return False in the event handler. The event handler can also be told to prevent form submission by calling e.preventDefault() on the event object that is being passed to the submit handler.
The reason for this behaviour is that, by default, the event fired when a submit button is clicked submits the forms at the very end of the event handling chain. So what happens is that in your event handler you are send a AJAX POST call (which is asynchronous), and the very next moment the handler returns without prevent the event from form submission. This results in both AJAX and form being sent.
e.preventDefault() tells the event e to avoid doing the default action specific to this event, in this case form submission. With this added, when $.ajax finishes and all the handlers are done handling the event the default handler is checked if it's allowed to be run. Since you have prevented it, nothing happens.
The very same method can be used to, e.g. prevent the webpage following a link <a> when clicked.

Ruby on Rhodes using ajax call

I am trying to build a dynamic dropdown in ruby on rhodes.There are basically two dropdowns on my screen and i am using ajax to get the values of the second dropdown from the database depending on the value selected in the first dropdown..I am a newbie to ruby and do not know the syntax on how to use ajax in ruby on rhodes..
JavaScript Code I am using...
$.post("/app/Settings/dropdown",
{ value:a },
function(data){
alert(data);
});
-----Partial Controller Code
enter code here
def dropdown
#a = #params['value']
puts #a
if #a.eql?"Auto"
mystring="auto1|auto2|"
else
mystring="personal1|personal2|"
end
end
I can get any parameter sent via ajax call to controller..My Question is how to send back the data from controller to function in that ajax call so that i can use that information to create a dynamic dropdown..I want to send this mystring to function(data)??
In Rhodes, controller actions can only render other actions or return a string consisting of partials. So, in order to populate a dropdown using AJAX, you'll have to render the view associated with the action which will returned as response to the AJAX call.
Controller 'dropdown' action:-
def dropdown
#a = #params['value']
if #a.eql?"Auto"
#optionList[:auto1]="auto1"
#optionList[:auto2]="auto2"
else
#optionList[:personal1]="personal1"
#optionList[:personal2]="personal2"
end
render :action => "dropdown"
end
'dropdown.erb' view:-
<% optionList.each do |key, value| %>
<option value="<%= key %>"><%= value %></option>
<% end %>
AJAX call:-
$.post(
"/app/Settings/dropdown",
{ value:a },
function(data){
data = data.replace("<div>","");
data = data.replace("</div>","");
alert(data);
}
});
Make sure you replace the div tags in the AJAX response, since Rhodes automatically surrounds AJAX responses with div tags.

Django: ajax & request

I don`t speak english well? but i have problem in Django.
I have models:
class Model1(models.Model):
model2 = models.ManyToManyField(Model2)
#...
class Model2(models.Model):
model3 = models.ForeignKey(Model3)
#...
class Model3(models.Model):
custom = models.CharField()
have view
def simple(request, simple_id):
if request.method == 'POST':
if request.is_ajax():
if 'delete' in request.POST:
id3 = request.POST.get('delete', '')
Model1.objects.get(id = simple_id).model2.filter(model3__id = id3).delete()
That is, when submitting a form with name = "delete" Ajax have removed all the objects belonging to Model2 with the same value of the field "model3"
Here's a piece of template:
<form action="" method="post" id="simple">{% csrf_token %}
<input type="submit" name="delete" id="simple_delete" value="">
</form>
the value passed from js:
$('.deletebutton').click(function(){
id = $(this).attr('data-id');
$('#simple_delete').attr('value', id);
$('#simple').ajaxForm();
$('#simple_delete').click();
});
Well, respectively plugin jquery.form.js also connected
The problem is this - if submission without ajax all is normal, it works ... and if with Ajax is an error such as incorrect int value ... How to make it work via Ajax?
try this
$('.deletebutton').click(function(){
id = $(this).attr('data-id');
$.ajax(function(){
type:"POST",
url :"/your_url/",
data:{
'id'=id,
}
}).done(function(result){
alert('your json object result render by view :'+result)
})
i think it work,
and i didnt get wat you are doing in i.e $('#simple_delete').click();
can you please describe about that
in view
obj = Model1.objects.get(id = simple_id)
model2.objects.filter(model3__id = id3).delete()
i just split single line query into two lines and if not working
use .select_related()

Reloading main view after button in PartialView is clicked

I have a partial view that the user can preform a search in, and the search results are shown in a select box. In my main view I have a section that is supposed to show the search results after a select button is pressed. Right now when I click the select button is loads the correct information into the correct model for my main view, but the main view doesn't change. When I click refresh, the page updates correctly. How do I make the page update automatically when a button is clicked in the plugin view?
My section in the main view (Index.vbhtml) in my main app:
#Section CUInfo
Credit Union Name: #Model.CUInfo.CUName
end section
Here is my controller method in my Plugin:
Function ChangeCUInfo(strCUName As String) As ActionResult
m_hostApp.CUInfo.CUName = strCUName
m_hostApp.blnPluginRefreshButtonPressed = True
Return View("Index", m_hostApp)
End Function
I've tried to set a boolean value in the hostApp object and then in my main razor view call this function if it is true:
#code
If Model.blnPluginRefreshButtonPressed = True Then
#<script type="text/javascript">
$(function () {
window.location.reload();
});
</script>
End If
Model.blnPluginRefreshButtonPressed = False
End Code
EDIT:
JS function called when the select button is clicked:
function loadCU(CUInfo) {
strCU = CUInfo.split('|');
strCUName = strCU[0];
$.ajax({
type: "POST",
url: "/CUContractNumberPlugin/ChangeCUInfo",
data: { "strCUName": strCUName }
});
}
Form that is used in the plugin view:
#Using (Html.BeginForm("ChangeCUInfo", "CUContractNumberPlugin"))
#<div id="LogoSigSearch" style="height:300px;width:500px;position:relative;">
<span style="display:inline-block;height:20px;width:166px;position:absolute;top:35px;left:5px;">Credit Union Name</span>
<br />
#Html.TextBox("strCUName")
<input type="submit" name="LogoSigSearch$ctl02" value="Search" id="LogoSigSearch_ctl02" tabindex="3" style="width:60px;position:absolute;top:5px;left:352px;" />
<input name="LogoSigSearch$ctl05" type="button" onclick="javascript:clearSearch()" value="Clear" style="position:absolute;top:35px;left:352px;width:60px;" />
<select size="4" name="LogoSigSearch$ctl06" id="LogoSigSearch_ctl06" tabindex="5" style="height:230px;width:342px;position:absolute;top:65px;left:5px;"></select>
<input type="button" name="SelectCU" value="Select" onclick="javascript:loadCU(LogoSigSearch_ctl06.options[LogoSigSearch_ctl06.selectedIndex].value)" tabindex="4" style="width:60px;position:absolute;top:65px;left:352px;" />
</div>
End Using
Are both buttons part of a form? A button won't invoke an action without you attaching it to script or making it part of a form with an associated action.
Use a partial view to render the results of the query, even on the main page load. This simplifies your development.
Add a jQuery event handler (jQuery.on()) to watch for the button click on your main page, or if the button is returned in the partial view, just use an on ready handler in your partial and attach a button.click() event, again using jQuery.
The jQuery event handler can take care of submitting the values of the query, posting to your controller, and displaying the results. I have a number of older articles here but they are still relevant to your question and demonstrate submitting data and fetching partials.
Your client-side code will end up looking something like this:
$("#your-button").click(function () {
var fetchUrl = '#Url.Action("ActionName", "Controller")';
$.post(fetchUrl, { searchParams: $("#your-search-box").val() })
.success(function (data) {
// replace the contents of the DIV with the results. 'data'
// here has whatever you sent back from your partial view
})
.error(function (data) {
// handle the error, use a DIV with some kind of alert message etc
});
});
Hope this helps some.

MVC3 Ajax.BeginForm with PartialView and persistent routedata issue

I have a main view and the URL for this view has a Action/Controller/Area and id value, something like:
http://localhost:56513/Incident/IncidentHome/Index/8c02a647-a883-4d69-91be-7ac5f7b28ab7
I have a partialview in this main view, one that calls methods in the controller via Ajax. This partial view needs to know the ID value of the url for the parent page. I found how to do this is through 'ParentActionViewContent'. Something like:
using (Ajax.BeginForm("UpdatePersonalStatusPanel", "Status", new { area = "Tools" , id = ViewContext.ParentActionViewContext.RouteData.Values["id"].ToString() }, new AjaxOptions { UpdateTargetId = "divPersStatus" }))
{
<p style="text-align: center;">
<span class="editor-label">#Html.LabelFor(m => m.StatusText)</span> <span class="editor-field">#Html.EditorFor(m => m.StatusText)</span>
<input type="submit" value="Change Current Status" />
</p>
}
Now, this works fantastic for calling the controller method. The ID is passed correctly so that the controller can then see it in the routedata. I use the id to perform a database call, and then return the partialview again. The problem is on the return. I get a 'Object reference not set to an instance of an object' on the ViewContext.ParentActionViewContext.RouteData.Values["id"].ToString() bit in the ajax.beginform , and my targetid doesn't refresh.
Clearly I must be doing something wrong. Does someone else have a better way to see the parent view's routedata through Ajax?
If I'm understanding you correctly, this partial view calls itself. So ParentActionViewContext works the first time because the first time your main view calls an action using this partial view. However, later an ajax call directly returns this partial view. When the partial view is invoked directly there is no Parent View action hence the null reference on ParentActionViewContext.
Rather than deal with with route data I recommend including the id in the model of your partial view.
new { area = "Tools" , id = Model.Id }

Resources