Second click on button to send form? - ajax

I'm working on a delete function in a web app where clicking on a button deletes a row in my db. This is pretty straight forward and it works, but I want the user to be able to confirm the delete first before the form is submitted.
Here's the markup for the form as it is now:
echo '<li class="fave-item">';
echo '<div class="tasted-this box-center">';
echo '<form class="delete-fave">';
echo '<input type="hidden" name="user_id" value="'.$faves_result['user_id'].'" />';
echo '<input type="hidden" name="beer_id" value="'.$faves_result['beer_id'].'" />';
echo '<button class="icon delete" data-icon="x" />';
echo '</form>';
echo '</div>';
echo '</li>';
And here's the ajax submit func.:
$('.delete-fave').on('submit', function(){
$.ajax({
type: "POST",
url: "deletefave.php",
data: $(this).serialize(),
success: $.proxy(function(json) {
$(this).closest('li.fave-item').remove();
},this)
});
return false;
});
This is what I want to happen before the submit:
$('button.delete').click(function(){
$(this).parent().addClass('delete-fave');
$(this).addClass('ready');
return false;
});
When I tested this I removed the class from the form to achieve this order of events:
Click 'button.delete' adds class 'delete-fave' to form (making it active)
'button.delete' gets a 'ready' class
Clicking again on button with the 'ready' class submits form.
I haven't been able to merge these functions so I hope you can help me out!

The $('.delete-fave').on('submit'... function is defined BEFORE the class is added to the button.delete parent, so it's not going to work.
To get it to work just redefine the function again AFTER adding the class.
JSFiddle recreating your problem: http://jsfiddle.net/rowlandrose/XAeCh/5/
JSFiddle solving your problem: http://jsfiddle.net/rowlandrose/XAeCh/4/

Related

codeigniter Click button to call a view

I am having a view with 2 buttons in my codeigniter view:
<div class="btn-main col-md-3 col-md-offset-3">
<button id="simu-mono" type="button" class="btn btn-default">SIMULATION MONO SITE</button>
</div>
<div class="btn-main col-md-3">
<button id="simu-multi" type="button" class="btn btn-default">SIMULATION MULTI SITE</button>
</div>
I would like to call another a controller to launch then a view when the button is clicked
I tried out to call the controller simu_mono by javascript, putted on /controller/simu_mono.php but doesn' t work
$(document).ready(function(){
$("#simu-mono").click(function(){
type:'GET',
url:'simu_mono'
});
$("#simu-multi").click(function(){
});
});
simu_mono.php:
<?php
class simu_mono extends CI_Controller {
public function index()
{
$this->load->view('simu_mono');
echo 'Hello World!';
}
}
?>
Thanks for your helps
Cheers
Please, if u want to redirect only use following code:
$(document).ready(function(){
$("#simu-mono").click(function(){
window.location = base_url + "/simu_mono";
});
$("#simu-multi").click(function(){
window.location = base_url + "/simu_multi";
});
});
Note that you might need base_url, use this snippet to load base_url in JavaScript variable
<script>
base_url = <?= base_url()?>
</script>
put code above in some kind of view that is loaded always (before any other JavaScript code is executed)
Additional step would be to set up routes that take care of ugly underscore symbol (_)
something like:
routes.php
$route['simu-mono'] = "simu_mono";
$route['simu-multi'] = "simu_multi";
this way you go to your page and controller following way: yourserver.ufo/simu-mono and yourserver.ufo/simu-multi
You're not doing any class of AJAX call within your javascript. I assume you're using jQuery, so, your call should be something like:
$("#simu-mono").click(function(){
$.ajax({
url: "http://your-url.com/controller/method",
type: 'post', // <- Or get option, whatever you prefer
dataType: 'json', // <- This is important to manage the answer in the success function
//data: { param1: "value1", param2: "value2"}, <- You could add here any POST params you wanted
success: function(data){
if (data.view) {
$('#here_view').html(data.view); // <- '#here_view' would be the id of the container
}
if (data.error){
console.log(data.error);
}
}
});
});
This will call your method, where you will have to indicate you want to pass the view:
<?php
class simu_mono extends CI_Controller {
public function index()
{
$return = array(
'view' => $this->load->view('simu_mono')
);
echo json_encode( $return );
}
}
?>
json_encode will allow you easily pass vars and data from PHP to your javascript, and manage them in the client view. As you see in the javascript, I added data.error, this is just in case you'll have more logic, maybe change the view you're sending, send an error if you sent data and want to control them, etc.
Of course, in your javascript you could take the url from the clicked button, and in data.view parat of the success function, you may print in the screen a modal, send the view to a container, whatever you wanted, XD

JavaScript functions are not working in ajax tabs

In my page I have ajax tabs and every tab consists of some javascript functions. I want to load each javascript function only when the tabs are clicked. But the functions are not working in tabs. How can I solve this?
My codes are as follows:
PHP:
echo "<script type='text/javascript'>";
echo "function check(){";
echo "alert('hello');";
echo "}";
echo "</script>";
echo "<div><a href='javascript:check();'>Check</a></div>";
Ajax:
new Ajax.Request(
test.php,
{
method:'post',
onSuccess: function(data){
var tmp=data.responseText;
$$('.tolga').invoke('insert',tmp);
}
});
HTML:
<div class="tolga">
</div>

codeigniter and tab contents

I have some tabs whose contents are fully functional parts of my website.
For instance, in my admin area, I have tabs [add/delete album][add photo][delete photo]. I'm technically dividing the admin area via tabs.
I'm using ajax to load the content into these tabs. tab content area is a div.
The view that is inside the tab content area also uses ajax to load stuff.
These are ajax calls that operates inside the tab content area.
Everything works fine as long as the view inside the tab content area stays same or only part of it changes. But when certain interactions inside tab content area return a whole new view, tab content area would not show them.
I know what happens is that this new view that is returned is not passed into the tab content area div.
In firebug, I can see that ajax success function response shows the new view that is returned.
But I do not know how to pass that new view to the tab content area.
I would appreciate it if someone could help me out in explaining how this could be solved or how contents inside tabs are managed in CI.
adminTabsview.php
<ul id="adminTabs">
<li ><?php echo anchor('#album_addDelete', 'Album Add/Delete'); ?></li>
</ul>
<div id="adminTabsContent"></div>
$(document).ready(function(){
$('#adminTabs a').on({
click: function (evt){
evt.preventDefault();
var page = this.hash.substr(1);
adminTabsAjaxCall(page);
}
});
});
function adminTabsAjaxCall ($data){
$.ajax({
type: "POST",
url: "index.php/adminsite_controller/"+ $data + "/",
dataType: "html",
data: $data,
statusCode: {removed}
},
success: adminTabContent
});
function adminTabContent (data){
$('#adminTabsContent').html(data);
}
albumsEditDeleteView.php
(this is a view that gets loaded into the tab contentarea div)
<div id="adminTabsContent">
<div id="albumList">
<ul>
<li>
Asdf
<a class="add" href="http://localhost/myPHP/photoalbums/index.php/Albums_Controller/add_album/301/Asdf/1/28/0">[ add ]</a>
<a class="delete" href="http://localhost/myPHP/photoalbums/index.php/Albums_Controller/delete_album/301/Asdf/1/28/0">[ delete ]</a>
</li>
</ul>
</div>
</div>
$(document).ready(function(){
$('#albumList').on({
click: function (evt){
evt.preventDefault();
var $clickedElement = evt.target.tagName;
if ($clickedElement == 'A' ){
var urlarray = url.split('/');
$chosen.albumid = urlarray[8];
$chosen.albumname = urlarray[9];
$chosen.lft = urlarray[10];
$chosen.rgt = urlarray[11];
$chosen.nodeDepth = urlarray[12];
if ($class == 'add'){
albumajaxcall($chosen);
}
if ($class == 'delete'){
deleteajaxcall($chosen);
}
}
}
});
});
function albumajaxcall($data){
$.ajax({
type: "POST",
url: "index.php/Adminsite_Controller/add_album/",
dataType: "json",
data: $data,
statusCode: {removed}
},
success: adminTabContent
});
}
function adminTabContent(data){
$('#adminTabsContent').html(data);
}
//heres the view file that has to replace the original view inside
//tabcontent area
//addnode_view.php
<?php echo form_open('Albums_Controller/update_albumSet');?>
<input type="text" name="newAlbum" id="newAlbum" value=""/>
<input type="submit" name="submit" value="Submit" />
<?php echo form_close();?>
<?php
//heres the controller function
function add_album(){
$levelData ['albumid'] = $this->input->post('albumid');
<!-- removed-->
$levelData ['main_content'] = 'addnode_view';
$this->load->view('includes/template', $levelData);
}
//And heres the controller method that loads
//the original page (albumsEditDeleteView.php) - this is the original view
//that gets loaded into the tab- I get stuck when this view
//has to be **totally** replaced through links in the view)
function album_addDelete(){
$allNodes ['myAlbumList'] = $this->Albums_Model->get_albumList();
echo $this->load->view('albumsEditDelete_view', $allNodes);
}
thanx in advance.
basically what you need to do is load whatever new view youll be putting in the tab in the controller function(adminsite_controller/whatever function) that is handling your ajax.
this will basically echo out the view file, which will be viewed as the success variable of your ajax function.
so you have something like this then for the success part of your ajax
success:function(msg){adminTabContent(msg);}
and in your controller in codeigniter you'll load a view the standard way, but since this will be only loading a piece of the page you may need to create a new view file thats just the div that will be there. You will do all your data gathering the same way you would if it wasn't ajax.
$data['some_data'] = $this->some_model->some_function();
$this->load->view('someview', $data);

jQuery binding a form submit via a class name does not work

I have a jQuery AJAX call that creates and displays a form like this in PHP:
echo '<form class="add_suggested_solution_comment" name="suggest_solution_comment_form" method="post">';
echo '<p><textarea name="suggested_solution_comment" cols=65 rows=6 ></textarea></p>';
echo '<input type="hidden" name="problem_id" value="'.$problem_id.'" />'; echo '<input type="hidden" name="suggestion_id" value="'.$suggested_solution_id.'" />';
echo '<p><input type="submit" class="button" value="Add Comment"></input></p>';
echo '</form>';
Then when the user clicks the form, I try to catch the click in jQuery like this by using the class attribute of the form. For a specific reason, I can't use the id attribute of the form.
Here is how that jQuery looks like:
$('.add_suggested_solution_comment').bind('submit',function()
But for some reason when the user submits the form, the jQuery never gets triggered. Any idea why?
Thanks!!
If you're creating the form dynamically via AJAX, you need to bind the submit handler using jQuery's live() method:
$('.add_suggested_solution_comment').live('submit', function(){
alert('form submitted');
// other code
});
Are you firing this on load? try
$(document).ready(function(){
$('.add_suggested_solution_comment').bind('submit',function()
});

jquery ajax codeigniter

I wanted to ask, why does the response from a ajax request using the native ajax not post or get return my entire page? is there anything I should know? I have looked at the documentation on jquery.com and nothing is mentioned of something like that unless i'm looking else where. Can I get any help on why that keeps happening?
This is the function that handles the validation of the form in question.
joe
function showsupport()
{
$this->form_validation->set_rules('supportername','Your Name','trim|required|max_length[20]|xss_clean');
$this->form_validation->set_rules('supporteremail','Email Address','trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('pledgedate','Pledge Date','trim|required|xss_clean');
$this->form_validation->set_rules('messagetxt','Your Message','trim|required|xss_clean');
if($this->form_validation->run() == FALSE)
{
echo validation_errors();
} else {
$this->load->model('support_m');
$name = $this->input->post('supportername');
$email = $this->input->post('supporteremail');
$date = $this->input->post('pledgedate');
$msg = $this->input->post('messagetxt');
$qry = $this->support_m->storepledge($name,$email,$date,$msg);
if($qry){
//$this->template->write_view('content','thanks');
//$this->template->render();
$datamsg['supportmsg'] = 'Message Added Successfully';
}else{
echo 'There was an error inserting into db';
}
}
}
This is the view with the form generated.
<?php
$formdata = array('id'=>'suppform');
echo form_open('homepage/showsupport',$formdata);
$namedata = array('name'=>'supportname','id'=>'supportname','size'=>'30','max_length'=>'25','value'=>set_value('supportname'));
echo '<label for="supportername">Your Name:'.form_input($namedata).'</label><br /><br />';
$emaildata = array('name'=>'supporteremail','id'=>'supporteremail','size'=>'30','max_lenth'=>'25','value'=>set_value('suppoteremail'));
echo '<label for="supporteremail">Email Address:'.form_input($emaildata).'</label><br /><br />';
$pledgedata = array('name'=>'pledgedate','id'=>'pledgedate','size'=>'30','max_length'=>'20','value'=>set_value('pledgedate'));
echo '<label for="pledgedate">Today\'s Date:'.form_input($pledgedata).'</label><br /><br />';
$msgdata = array('name'=>'messagetxt','id'=>'messagetxt','col'=>'2','rows'=>'8');
echo '<label for="messagetext">Your Pledge:'.form_textarea($msgdata).'</label><br />';
$submitdata = array('name'=>'submitbtn','id'=>'submitbtn','value'=>'Send');
echo '<label for="submitbutton">'.form_submit($submitdata).'</label><br />';
echo form_close();
?>
</div>
<div id="errorsechoed"><?php echo validation_errors();?></div>
The html of the retured page is dumped in the div #errorsechoed
$('#suppform').submit(function(eve){
eve.preventDefault();
$.ajax({
type: 'POST',
cache: false,
url: 'homepage/showsupport',
data: $('#suppform').serialize(),
beforeSend: function(){
$('#supportform').block({message:'<h4> Processing...</h4>'})
},
complete: function(){
},
success: function(html){
$('#errorsechoed').text(html);
}
});
});
I have been trying to get this figured out and I think I have made some progress, here is what I have:
a) the template library from William Colin works where regions are specified and so only a particular region will be refreshed all the time and not the only page. As a result it sort of works differently from other standard setups for codeigniter. This is definitely getting in the way of jquery getting a response from the server. It gets the bits of template library (i.e. regions) and renders it out which ends up rebuilding the whole page again.
b) When you run the form_validation library, Template doesn’t allow you to just load a view the normal way in codeigniter, rather you do this by running:
$this->template->write_view('contentregion','viewname'); //writes the view
$this->template->render(); //renders the view on screen.
so if this is not done if validation fails, the error messages spat out by the formvalidation library just never seem to get to the view.
I have tried a lot of permutations of using functions that come with this library and still am just able to render out another page of my site. confused
CONCLUSION:
I think this template library is great but it needs some updating so these issues are met. I will have to look at other templating systems when I have to do a site with a lot of ajax required. Hope Mr. William can see this and help look into this.
Thanks community for an avenue to say what I have learned. Hope this is useful to someone.
It's because you are setting the datatype in the postback to be of type 'html':
"html": Returns HTML as plain text;
included script tags are evaluated
when inserted in the DOM.
if you just want to show that the request succeeded or failed you can have #errorsindicated populated like so:
success: function(){
$('#errorsechoed').html('<h4> Request Successfull...</h4>');
}
error: function(){
$('#errorsechoed').html('<h4> Request Failed...</h4>');
}
you can get more detailed information on the error if you want. See the error option section of the jQuery ajax documentation: http://api.jquery.com/jQuery.ajax/

Resources