MGB C
MGB C

Reputation: 452

display an alert when the button is click in javascript and ajax

Good day. newbie here... my code is working will.. my problem is after clicking the button twice or more than that the alert text doesn't show again.. what I want to do is to display the text if I click the button once or many time without refreshing the page.. here is my code...

script

<script type="text/javascript"> 
// Ajax post 
 $(document).ready(function() { 
 $(".submit").click(function() { 

var message = $("textarea#l_message").val(); 

 jQuery.ajax({ 
 type: "POST", 
 url: "<?php echo base_url(); ?>" + "admin/user_data_submit", 
 dataType: 'json', 
 data: {l_message: message}, 
 success: function(res) { 
 if (res) 
 { 
  // Show Entered Value 
 jQuery("div#msg").show(); 
 jQuery("div#msg").html('Update Successfully!'); 
 window.setTimeout(function() {
    $("#msg").fadeTo(1000, 0).slideUp(1000, function(){
        $(this).remove(); 
  });
}, 5000);
} else {
 } 
} 
 }); 
  return false; 
 }); 
}); 

 </script>

my form

<?php echo form_open();
                echo form_label('Librarians Message');
                ?>
                <textarea class="form-control" name="the_librarian" id="l_message">  </textarea>

                <?php echo form_submit('submit', 'Update',"class='btn btn-success navbar-btn submit'");?>
                <?php echo form_close();?>

 <div id="msg" style="color: green;">
 </div>

the alert message will close after 5sec then after that if I click the button again the alert message doesn't show. I want to show that message again even I click the button multiple times... sorry for the Grammar,..

help me to solve this problem.

Upvotes: 0

Views: 2166

Answers (1)

John Fable
John Fable

Reputation: 1091

The line

$(this).remove();

is removing the entire #msg div from the DOM, so it isn't there to be shown again. You could use

$(this).hide();

instead.

Also, opacity is remaining at 0, so change:

jQuery("div#msg").hide();

to

jQuery("div#msg").hide().css('opacity','1');

Upvotes: 1

Related Questions