Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Development Tools

Bootstrap 3 Modal

Good Evening,

Has anybody had any experience using Twitter Bootstrap 3 Modals, that is able to advise?

My problem

I am created a small site and have placed the contact form inside the modal that is activated via a button, my problem is when the form is submitted, what happens is before it can display the errors generated from PHP validation the modal is automatically closed and I have to re open it to see the prompts.

So my question is how do I disable the auto close function.

Thanks

11 Answers

Alan Johnson
Alan Johnson
7,625 Points

Any way you could share a small sample that reproduces what you're seeing?

I can do you one better follow this link

Thanks for replying

Alan Johnson
Alan Johnson
7,625 Points

So it looks like the issue is that your form is using normal requests, rather than XHR, so the page is refreshing. Have you ever worked with XHR/Ajax?

Oh i see. Never heard of XHR. Heard of Ajax but never works with it, Could you point me in the right direction.

Alan Johnson
Alan Johnson
7,625 Points

Do you have jQuery loaded up on your page?

Yes

Alan Johnson
Alan Johnson
7,625 Points

OK, so this isn't super trivial. I'm going to outline what you'll need to do in basic steps, and from there I can help you work through each part if needed. So, here goes:

  1. Replace the normal form submission with a callback using the jQuery .submit() method.
  2. Inside of the callback, prepare your data - serialize() is great for that - and submit it using jQuery.post.
  3. Reply from your PHP script with a success message or error depending on what happens.
  4. Process the results within the callbacks for your jQuery.post call.

Here's a tiny sample of how the fronted would work just to get you going. I haven't tested it, but it should get you pointed in the right direction:

<form id="contact-form" action="contact.php" method="post">
  <input name="name" type="text" placeholder="Name" />
  <input name="email" type="email" placeholder="Email" />
  <textarea name="message" placeholder="Your Message" />
</form>

<script>
$(function() {
  $("#form").submit(function(e) {
    // keep the form from submitting
    e.preventDefault();

    // serialize the form to a set of variables
    var form = $("#form");
    var params = form.serialize();

    // send the data to your server via XHR
    $.post(form.attr("action"), params)
      .done(function(data) {
        // show a success message here
      })
      .fail(function(data) {
        // show the form validation errors here
      })
  });
});
</script>

I haven't coded PHP in a really long time, but on the PHP side you'll want to look at $_POST for those parameters, and then you'll want to reply with an error response code and some sort of data (probably JSON) about the validation errors if it's bad. If it's successful you can just respond with about anything and a success http response code.

Thanks for this i will have a proper look at it in the morning and see how it goes.

Have to say I don't fully understand the process here not overly great a jQuery (going to get them courses done this week) could you try to explain the concepts at play here so i can better understand what need to be done. From what i can ascertain i need to get the form validated with jQuery then have that send the data to my PHP script But i feel lost. I appreciate you taking the time to help.

Is this gist on the right tracks?

Alan Johnson
Alan Johnson
7,625 Points

It's pretty close, but that gist isn't taking errors into account, and it sounded like you wanted to include error messages as well.

Feel free to ask clarifying questions and I can help you work through it.

Thanks. So this is what I assume is the process here, I am to use the js from above to collect the data from the form in the modal and submit it to a file called contact.php then my php script can process the form with the validation and send the email.

But what i don't understand is if it is submitted to a new page how can i get the modal to stay open on index.php and have the error responses show up without the modal closing.

If you look at the site now and submit the form without entering any data it will close the modal and if you re open it the error messages are there. It's the close feature on submit that is causing the problem.

Again much appreciated

Alan Johnson
Alan Johnson
7,625 Points

I don't see where you've added the script to the page to catch the form submission event. Basically what's happening now is that you're submitting the form and then redisplaying the page, and when it's displayed it's showing the validation errors. To keep the modal open you've got to keep the browser from submitting the form (which causes a full page re-render) and instead submit it with Ajax.

As a first step, add this code to your page:

<script>
$(function() {
  $("#contact_modal form").submit(function(e) {
    e.preventDefault();
    alert("No page refresh.");
  });
});
</script>

That should cause clicking the submit button to show an alert box, and the modal should stay open. Is that the case?

Yes that is correct. So now I need to look into submitting it with Ajax. will that then send validation results back to the modal?

Alan Johnson
Alan Johnson
7,625 Points

Awesome, so yes, now it's time to submit it via Ajax. My recommendation would be to configure where you're submitting the form via the action attribute. So add action="contact.php" method="post" to your form tag.

Now let's tweak that submit callback a bit to handle the form:

<script>
$(function() {
  $("#contact_modal form").submit(function(e) {
    e.preventDefault();

    // send the data to your server via XHR
    $.post(form.attr("action"), params)
        .done(function(data) {
          // show a success message here
          alert("SUCCESS");
        })
        .fail(function(data) {
          alert("ERROR");
        });
  });
});
</script>

That update should keep the modal up for you, but nothing will send yet since we don't have the backend wired up. Does that work for you?

Yes that works perfect. So what happens in the back end now?

Cheers

Alan Johnson
Alan Johnson
7,625 Points

:smile: Rad!

So now we need to get contact.php into shape. What do you have for your contact script now?

I have this PHP and it inserts the errors under the inputs and textarea.

<?php
  if($_POST)
  {
    //not empty

    $errors= array();

    //start validation
    if(empty($_POST["name"]))
    {
        $errors["name1"] = "You name cannot be empty";
    }
    if(strlen($_POST["email"]) < 9)
    {
        $errors["email2"] = "Your email address is not valid";
    }
    if(empty($_POST["email"]))
    {
        $errors["email1"] = "You email address cannot be empty";
    }
    if(empty($_POST["message"]))
    {
        $errors["message1"] = "You message cannot be empty";
    }

    $name = $_POST["name"];
    $email = $_POST["email"];
    $message = $_POST["message"];

    $msg_body = "Name: " . $name . "\n" . "Email: " . $email . "\n" . "Message: " . $message . "\n";


    //check errors
    if(count($errors) == 0)
    {
        //redirect to success page

        mail('Sacki2013@gmail.com', "HeadAmp Message", $msg_body);    
        header("Location: success.php");    
        exit();
    }
  }
?>

Just a simple script to validate not empty then send it

Alan Johnson
Alan Johnson
7,625 Points

Here's a start. I'm not sure what you're doing with $msg_body after the script runs, so we may need to tweak it all a bit, but hopefully this points you in the right direction.

This should send a response back to the client with either a json object containing error messages if it fails or a successful response if it doesn't.

<?php
  if($_POST)
  {
    //not empty

    $errors= array();

    //start validation
    if(empty($_POST["name"]))
    {
        $errors["name1"] = "You name cannot be empty";
    }
    if(strlen($_POST["email"]) < 9)
    {
        $errors["email2"] = "Your email address is not valid";
    }
    if(empty($_POST["email"]))
    {
        $errors["email1"] = "You email address cannot be empty";
    }
    if(empty($_POST["message"]))
    {
        $errors["message1"] = "You message cannot be empty";
    }

    $name = $_POST["name"];
    $email = $_POST["email"];
    $message = $_POST["message"];

    // if we have some errors, send them back. otherwise, just send the email
    if(count($errors) > 0) {
      // not sure what you're doing with $msg_body, but we'd like to respond with json here
      $msg_body = json_encode($errors);
      header("Content-type: text/json");
      http_response_code(422);
    }
    else
    {
        //redirect to success page

        mail('Sacki2013@gmail.com', "HeadAmp Message", $msg_body);    
        http_response_code(200);
        exit();
    }
  }
?>

Thanks again. It sends the message now if i fill in the form and directs to the success.php page but if i dont fill it it and submit it loads the page again without the modal but the errors are present. Do i need to trigger the modal to load once its complete?

Alan Johnson
Alan Johnson
7,625 Points

What happens if errors occur. Is there another script that's using $msg_body?

If errors occur it loads the page but the modal is not loaded, the errors are in the right place but a click on contact form is needed to know about it. No other scripts using msg_body

Alan Johnson
Alan Johnson
7,625 Points

Instead of rendering the whole page, you'll want to update how you're running the scripts to just respond with $msg_body. So I'd probably update that part of the code to be something like:

echo json_encode($errors);
header("Content-type: text/json");
http_response_code(422);
exit();

That'll make it so the response is just the json output. Does that keep the modal from going away? The error messages probably won't get filled in for you.

It does keep it from going away. Sorry for delay

Alan Johnson
Alan Johnson
7,625 Points

Awesome! So now you'll want to do something with the success or error responses that come back. You can do that in the done and fail functions in your JavaScript. Let me know if you need help with that!

I have a question Alan, I was looking to do something like this with modals. I was able to read over your suggestion to Adam but my thing is, it will post and give me whatever my php side shows. So if I was to echo out something it would show that or if I redirected it back to the main page it would do that. But I want it to show a bootstrap alert either in the modal or on the main page. How can I accomplish this? Oh btw, my modal doesn't stay up, it just does whatever the php code tells it.

Alan Johnson
Alan Johnson
7,625 Points

Do you have a place where I can see your front-end code?

Alan Johnson
Alan Johnson
7,625 Points

At least one thing I'm noticing here is that on line 213:

$("#addingTask").submit(function(e) {

you're referencing the button (#addingTask) rather than the form (#test), but the .submit() event only fires on a form. What happens if you change #addingTask to #test?

Alright, I was able to get everything to work plus more. :) I was able to get a successful post with a bootstrap alert to say it was successful and on closing the modal it would refresh the page.

I do have 1 more question tho. (This is a php+ajax question) I have a table to that is generated by php+mysql. I also have a button that is front of each row that has an ID(from mysql) that directs to that id's information. (ie. getPhones.php?id='.$row['id'].') On clicking that it would bring up the modal and have a form in the modal populate with the corresponding information from the database based on the id. My question is, how would I be able to pass the id through ajax through to the modal?

I did post about this Passing Variable To Ajax Into A Modal Not sure if you can help me on this. I cant seem to get it work.

btw, how do i do markdown for php or javascript on here? can't seem to get coding to work.

Alan Johnson
Alan Johnson
7,625 Points

I'll jump to your other post for that one, but I wanted to let you know that for markdown in the forum it's best to use code fences (three backtick ` characters). You'll put the three backticks on their own line before and after your code.