Davor Davor - 10 months ago 56
jQuery Question

Getting data back from a Bootstrap modal

I have a signup page that triggers a modal window (using Bootstrap) containing for example a Facebook login and I want this modal to pass back data (errors, or if success the token / user data) to the main window so I can fill the relevant form fields and let the user complete the signup process (tick the "I approve the terms and conditions" box etc.).

I know how to do all of it except the bit about sending data back when the modal closes. Is there a way to pass data from the modal to the main window on the modal close event?

EDIT: here is a visual representation of what I want to accomplish:


Well. You have access to both the main window and the modal content, so basically you just need to copy content from modal elements before closing. Working Example (copy the two codeblocks into two files) :

auth.php (dont know how your auth works, but perhaps you call a remote login and get some results, you can store in a JSON-array)

<label for="modal-username">Username</label><input type="text" name="modal-username" id="modal-username">
$result = array();
$javascript_array = json_encode($result);
<input type="hidden" id="modal-result" value='<? echo $javascript_array;?>'>

modal.html, main window

<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>

<!-- button to trigger modal -->
<a href="auth.php" data-target="#myModal" data-toggle="modal">remote modal</a>

<!-- hidden fields to store modal result in -->
<input type="hidden" id="main-username">
<input type="hidden" id="main-result">

<!-- modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Modal test</h3>
  <div class="modal-body">
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
    <button class="btn btn-primary" onclick="login();">Login</button>

<script type="text/javascript">
//called when user clicks login
function login() {

//called when the modal is closed, logs values grabbed from the modal in login()
$('#myModal').on('hidden', function() {
    console.log('username : '+$("#main-username").val());
    console.log('result : '+$("#main-result").val());