3

I have a modal window that pops up when I want to add a new project to my dashboard. I have gotten it to work with jquery post however, I cannot prevent it from refreshing. What I want to do is after the project is added to the database, show a success message and close the modal window after few seconds and not refresh the page (parent page of modal).

Here is my modal

<div class="modal fade" id="add-project-dialog" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&amp;times;</button>
        <h4 class="modal-title" id="myModalLabel">Add a new Project</h4>
        </div>
        <div class="modal-body">
            <h3>New Project:</h3>
            <form class="form-horizontal" id="add-project-form" action="/projects/add" method="POST">
        <fieldset>
        <!-- Text input-->
        <div class="form-group">
          <label class="col-md-4 control-label" for="name">Project Name</label>
          <div class="col-md-4">
          <input id="name" name="name" type="text" placeholder="" class="form-control input-md">

          </div>
        </div>

        <!-- Text input-->
        <div class="form-group">
          <label class="col-md-4 control-label" for="description">Project Description</label>
          <div class="col-md-4">
          <input id="description" name="description" type="text" placeholder="" class="form-control input-md">

          </div>
        </div>

        <!-- Text input-->
        <div class="form-group">
          <label class="col-md-4 control-label" for="project_state">Project State</label>
          <div class="col-md-4">
          <input id="project_state" name="project_state" type="text" placeholder="" class="form-control input-md">

          </div>
        </div>

        </fieldset>
                            <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

                <button id="add-btn" class="btn" type="submit">Add</button>
                     </div>

            </form>
        </div>


</div>

Here is my project-dashboard.js

AddProject = function(){
  $(document).ready(function() {
   $("#submit").submit(function(event){
       event.preventDefault();
       $.ajax({
           url: "/projects/add",
           type:"POST",
           data:
           {
            'name': $('#name').val(),
            'description': $('#description').val(),
            'project_state': $('#project_state').val()
           }
           });
        });
   });
 }

My views.py

class AddProject(webapp2.RedirectHandler):
    def get(self):
    template_values = {
        #'greetings': greetings,
        #'url_linktext': url_linktext,
        }
    path = os.path.join(os.path.dirname(__file__), '../templates/project-add.html')
    self.response.write(template.render(path, template_values))

def post(self):
    project = Project()
    project.name = self.request.get('name')
    project.description = self.request.get('description')
    project.project_state = self.request.get('project_state')
    time.sleep(2)
    project.put()
    self.redirect('/projects')

I have tried removing the self.redirect('/projects') however that only takes me to a blank page that is /projects/add (that is the action in the form).

Borko Kovacev
  • 1,010
  • 2
  • 14
  • 33

3 Answers3

1

The issue is that you added .ready(foo) handler inside of the AddProject function. I suppose that document is loaded when AddProject is called.

Another issue is that in your HTML, the form has id add-project-form, so you should do $("#add-project-form") instead of $("#submit").

$(document).ready(function () {
   $("#add-project-form").submit(function(event){
       event.preventDefault();
       $.ajax({
           url: "/projects/add",
           type:"POST",
           data:
           {
            'name': $('#name').val(),
            'description': $('#description').val(),
            'project_state': $('#project_state').val()
           }
           });
        });
   });
});

Take ready handler outside of the AddProject function and it should work (the submit handler is added).

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
1

Edit: After some debugging, the answer was to use the right id and proper placing of the javascript code, as noted by the comments.

For starters, a refresh is easy to avoid, just make sure to prevent the default event from running; since you're using jQuery, I would recommend doing return false to end the function, since it both 'prevents default' and 'stops propagation'.

So the first thing you should do is check if your javascript code is actually running and not erring in the middle of execution. If everything is fine there, the worst case is that the project is not actually added (server side error) but the page should not refresh.

Your server side code has nothing to do with the refresh (if it's being properly hijacked), so the response doesn't really matter, I would actually return the id of the new project (so you could provide a link for the newly created item or something like that), but i digress...

Community
  • 1
  • 1
Jaime Gómez
  • 6,961
  • 3
  • 40
  • 41
  • I have added `return false;`, but still no luck. The form adds the project well, so I am assuming server side error is out of the question. I will take your advice on the id. – Borko Kovacev Jul 28 '14 at 19:07
  • 1
    Well that is really weird, the only other thing that could be happening is that the form is being submitted somewhere else. A couple questions, reviewing your code the only form I see has the id of `add-project-form`, not `submit` like in your javascript, is that how it works? And why there's no success function? I guess it's a simplified example but had to ask. – Jaime Gómez Jul 28 '14 at 19:15
  • Great observation. When `submit` changed to `add-project-form` it worked. I thought I was binding the submit of the form to the jquery. Thank you, this with the removal of AddProject as suggested by another answer worked. The problem now is what answer should I mark as correct, as both of you did help tremendously. – Borko Kovacev Jul 28 '14 at 19:25
  • Glad we could help :) – Jaime Gómez Jul 28 '14 at 19:29
0

Here is a snippet for not only closing modals without page refresh but when pressing enter it submits modal and closes without refresh

I have it set up on my site where I can have multiple modals and some modals process data on submit and some don't. What I do is create a unique ID for each modal that does processing. For example in my webpage:

HTML (modal footer):

 <div class="modal-footer form-footer"><br>
              <span class="caption">
                <button id="PreLoadOrders" class="btn btn-md green btn-right" type="button" disabled>Add to Cart&nbsp; <i class="fa fa-shopping-cart"></i></button>     
                <button id="ClrHist" class="btn btn-md red btn-right" data-dismiss="modal" data-original-title="" title="Return to Scan Order Entry" type="cancel">Cancel&nbsp; <i class="fa fa-close"></i></a>
              </span>
      </div>

jQUERY:

$(document).ready(function(){
// Allow enter key to trigger preloadorders form
    $(document).keypress(function(e) {       
      if(e.which == 13) {   
          e.preventDefault();   
                if($(".trigger").is(".ok")) //custom validation dont copy
                   $("#PreLoadOrders").trigger("click");
                else
                    return;
      }
    });
});

As you can see this submit performs processing which is why I have this jQuery for this modal. Now let's say I have another modal within this webpage but no processing is performed and since one modal is open at a time I put another $(document).ready() in a global php/js script that all pages get and I give the modal's close button a class called: ".modal-close":

HTML:

<div class="modal-footer caption">
                <button type="submit" class="modal-close btn default" data-dismiss="modal" aria-hidden="true">Close</button>
            </div>

jQuery (include global.inc):

  $(document).ready(function(){
         // Allow enter key to trigger a particular class button 
        $(document).keypress(function(e) {
                if(e.which == 13) {
                   if($(".modal").is(":visible")){   
                        $(".modal:visible").find(".modal-close").trigger('click');
                    }
                }
         });
    });

Now you should get no page refreshes on any of your modals if u follow these steps.

yardpenalty.com
  • 1,244
  • 2
  • 17
  • 32