I'd like to call one controller action on checking checkbox and another on unchecking.
That is, I want to call "meeting#create" on checking and "meeting#destroy" on unchecking.
This is signup form where You can sign up for several meetings via checkboxes. On checking the checkbox, the corresponding meeting gets added to an order (practically a cart) and on unchecking, the corresponding meeting gets removed from the order.
How is it possible to call a different action depending on actual status of the check_box_tag?
I'm no professional, so it took me long enough to figure out the options I should supply (the url_for) and I don't have a clue how to do it conditionally.
Please help!
<% #meeting.each do |meeting| %>
<%= check_box_tag 'checkbox', meeting.id, checked = false, :data => {:remote => true, url: url_for(controller: :order, action: :create, meeting_id: meeting), method: :post}, :class => 'checkbox' %>
<% end %>
In the end, I wrote the ajax script by hand.
$( document ).ready(function() {
$(".checkbox").click(function() {
var chb = $(this);
if($(this).prop('checked')){
$.ajax({
url: '/bookings?meeting_id='+chb.attr('value'),
type: "post"
});
}
else{
$.ajax({
url: '/bookings?meeting_id='+chb.attr('value')+'&cart_id='+currentcartid,
type: "delete"
});
};
});
});
One ajax script sufficed.
Related
after i submit a form with Ajax and i have the result back ... i need to update my EJS tag with this new data.
$.ajax({
type: "POST",
url: url,
data: data,
success: function(result){
........
console.log(result)
}
and in my EJS file i have this code:
<% if(test.type =='type_1' ) { %> type 1 information <% } %>
<% if(test.type =='type_2' ) { %> type 2 information <% } %>
so if the user change the input to type 2 i need to update my page and show the user the information of type 2 without refreshing the page
After $.ajax post request to the controllers action I would like to get info from the server and then update my partial view, for example I have a list rendered in my view I delete an item from the list using the $.ajax post request and then i would like my list to update itself asynchronously.
Here is my function that deletes the item from the list:
$(".btnDeleteCurrentFavSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteCurrentFav/",
data: { id: songId },
success: ShowMsg("Song deleted successfully"),
error: ShowMsg("There was an error therefore song could not be deleted, please try again"),
dataType: "json"
});
});
Should I somehow redirect to the action on ajax success that returns the list of songs to the view?
if your clicked list item looked like this:
<li name="120">Artist - Title</li>
your javascript could look something like this:
$(".btnDeleteCurrentFavSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteCurrentFav/",
data: { id: songId },
success: function () {
ShowMsg("Song deleted successfully");
$("li[name=" + songId + "]").remove();
},
error: ShowMsg("There was an error therefore song could not be deleted, please try again"),
dataType: "json"
});
});
It depends upon the user experience that you wish to give. Convention dictates that a user should be shown the effect of their action. From your example it appears that you are doing this via the ShowMsg function. As to whether you should redirect or not, I'm afraid there's nothing authororative out there, do whatever is consistent across your site and would feel natural to users.
option A
return deleted item id from action
on success remove deleted item with js
option B
return partial view from action
on success replace container with rendered html
I'm trying to use Ajax in CakePHP, and not really getting anywhere!
I have a page with a series of buttons - clicking one of these should show specific content on the current page. It's important that the page doesn't reload, because it'll be displaying a movie, and I don't want the movie to reset.
There are a few different buttons with different content for each; this content is potentially quite large, so I don't want to have to load it in until it's needed.
Normally I would do this via jQuery, but I can't get it to work in CakePHP.
So far I have:
In the view, the button control is like this:
$this->Html->link($this->Html->image('FilmViewer/notes_link.png', array('alt' => __('LinkNotes', true), 'onclick' => 'showNotebook("filmNotebook");')), array(), array('escape' => false));
Below this there is a div called "filmNotebook" which is where I'd like the new content to show.
In my functions.js file (in webroot/scripts) I have this function:
function showNotebook(divId) {
// Find div to load content to
var bookDiv = document.getElementById(divId);
if(!bookDiv) return false;
$.ajax({
url: "ajax/getgrammar",
type: "POST",
success: function(data) {
bookDiv.innerHTML = data;
}
});
return true;
}
In order to generate plain content which would get shown in the div, I set the following in routes.php:
Router::connect('/ajax/getgrammar', array('controller' => 'films', 'action' => 'getgrammar'));
In films_controller.php, the function getgrammar is:
function getgrammar() {
$this->layout = 'ajax';
$this->render('ajax');
}
The layout file just has:
and currently the view ajax.ctp is just:
<div id="grammarBook">
Here's the result
</div>
The problem is that when I click the button, I get the default layout (so it's like a page appears within my page), with the films index page in it. It's as if it's not finding the correct action in films_controller.php
I've done everything suggested in the CakePHP manual (http://book.cakephp.org/view/1594/Using-a-specific-Javascript-engine).
What am I doing wrong? I'm open to suggestions of better ways to do this, but I'd also like to know how the Ajax should work, for future reference.
everything you show seems fine. Double check that the ajax layout is there, because if it's not there, the default layout will be used. Use firebug and log function in cake to check if things go as you plan.
A few more suggestions: why do you need to POST to 'ajax/getgrammar' then redirect it to 'films/getgrammar'? And then render ajax.ctp view? It seems redundant to me. You can make the ajax call to 'films/getgrammar', and you don't need the Router rule. You can change ajax.ctp to getgrammar.ctp, and you won't need $this->render('ajax');
this is ajax call
$(function() {
$( "#element", this ).keyup(function( event ) {
if( $(this).val().length >= 4 ) {
$.ajax({
url: '/clients/index/' + escape( $(this).val() ),
cache: false,
type: 'GET',
dataType: 'HTML',
success: function (clients) {
$('#clients').html(clients);
}
});
}
});
});
This the action called by ajax
public function index($searchterm=NULL) {
if ( $this->RequestHandler->isAjax() ) {
$clients=$this->Client->find('list', array(
'conditions'=>array('LOWER(Client.lname) LIKE \''.$searchterm.'%\''),
'limit'=>500
));
$this->set('clients', $clients);
}
}
This is a function I use to submit forms in cakephp 3.x it uses sweet alerts but that can be changed to a normal alert. It's very variable simply put an action in your controller to catch the form submission. Also the location reload will reload the data to give the user immediate feedback. That can be taken out.
$('#myForm').submit(function(e) {
// Catch form submit
e.preventDefault();
$form = $(this);
// console.log($form);
// Get form data
$form_data = $form.serialize();
$form_action = $form.attr('action') + '.json';
// Do ajax post to cake add function instead
$.ajax({
type : "PUT",
url : $form_action,
data : $form_data,
success: function(data) {
swal({
title: "Updated!",
text: "Your entity was updated successfully",
type: "success"
},
function(){
location.reload(true);
});
}
});
});
I am trying to submit a form remotely.
<% form_for #awareness_item, :remote => 'true', :url => admin_awareness_item_path(#awareness_item), :html => {:id => 'updteAwarenessItem'} do |f| %>
and have the below ajax callbacks configured to the form,
$(document).ready(function(){
$("#updteAwarenessItem").unbind();
$("#updteAwarenessItem")
.bind("ajax:success", function(event, data, status, xhr) {
console.log('...POSTING....');
})
.bind("ajax:loading", function(event, data, status, xhr) {
console.log('...LOADING....');
});
});
The problem is, that though I have bound the ajax:loading callback with the form, it never gets called. The onlything that ever gets called is ajax:success. Kindly let me know how can I bind ajax:loading and ajax:complete to the form. Am I doing something wrong here?
Some callbacks have been renamed (see the pull request).
ajax:loading is now ajax:beforeSend, because it's been named beforeSend in jQuery, to avoid confusion.
How can I send data from a dialog to the controller? Model Binding?
Can I have example please?
I'm making some assumptions here based on your previous questions that you are interested in ASP.NET MVC and are using jQuery UI dialogs. Further I'm guessing that you want the data submitted without reloading the page -- i.e., the dialog should be dismissed and return you back to the original page.
The simplest way is to create a form in the dialog and have that form submited via AJAX. I would suggest that you have the dialog populated via a controller action that loads a partial view. This will make it simpler to generate the mark up for the dialog. Give the content area of the dialog a class that makes it easy to find once the dialog is created, then in the dialog open handler replace the HTML inside the content area via a load to the controller action. Use the buttons on the dialog to submit the form.
$(function() {
$('.someSelector').click( function() {
$('<div title="Update Contacts"><p class="dialog-content"></p></div>').dialog({
autoOpen: true,
modal: true,
open: function() {
$(this).find('.dialog-content')
.load( '<%= Url.Action( "show", "contact", new { id = Model.UserID } ) %>',
function() {
$(this).find('form').submit( function() {
return false;
}
}
);
}
buttons: function() {
'Update': function() {
var $this = $(this);
var form = $this.find('form');
$.post( form.attr('action'), form.serialize(), function(){
$this.dialog('destroy');
});
},
'Cancel': function() {
$(this).dialog('destroy');
}
}
});
});
});
Partial view
<% using (Html.BeginForm( "update", "contact", null, FormMethod.Post, new { id = "contact-form" } )) { %>
<%= Html.EditorForModel() %>
<% } %>