Modal Form Submission without refresh

12,352

Solution 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).

Solution 2

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...

Share:
12,352
Borko Kovacev
Author by

Borko Kovacev

Updated on June 04, 2022

Comments

  • Borko Kovacev
    Borko Kovacev almost 2 years

    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
    Borko Kovacev almost 10 years
    I understand what you mean, but, for some reason it still does not work. :( Could it be that my POST is wrong? I have included it in the main question. Thank you!
  • Ionică Bizău
    Ionică Bizău almost 10 years
    Do you see any erros in the browser console?
  • Borko Kovacev
    Borko Kovacev almost 10 years
    Only some css attributes, but that's about it. They are related to something else.
  • Borko Kovacev
    Borko Kovacev almost 10 years
    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.
  • Jaime Gómez
    Jaime Gómez almost 10 years
    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.
  • Borko Kovacev
    Borko Kovacev almost 10 years
    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.
  • Jaime Gómez
    Jaime Gómez almost 10 years
    Glad we could help :)
  • Ionică Bizău
    Ionică Bizău almost 10 years
    @BorkoKovacev I guess that the problem is that you don't bind the event to the correct form. See the edit.