Solved

Javascript Variable Through Modal Window

Posted on 2016-10-05
22
41 Views
Last Modified: 2016-10-07
I'm trying to pass a javascript variable through a modal window.  I can get the variable into a text field, but can't figure out how to pass it to another page.  Here's the javascript...

<script type="text/javascript">
$(document).on("click", ".open-AddBookDialog", function (e) {

    e.preventDefault();

    var _self = $(this);

    var myBookId = _self.data('id');
    $("#bookId").val(myBookId);

    $(_self.attr('href')).modal('show');
});
</script>

Open in new window


Here's the code that triggers the javascript
<a data-id="<?php echo $id_family_member;?>" title="Add this item" class="open-AddBookDialog btn btn-primary" href="#addBookDialog">test</a>

Open in new window


Here's the input command that puts the javascript variable into the field.

<input type="text" name="bookId" id="bookId" value="" />

Open in new window


Any ideas on how to get a button or a link to pass the variable to a PHP page?

Thanks,

Steve
0
Comment
Question by:stkoontz
22 Comments
 
LVL 32

Expert Comment

by:ste5an
ID: 41829868
It depends on the functionality of your button, but you have some options:

When it is a form submit button, then store your value in a hidden form field.
When it is just a generic button build on an anchor append it as a parameter.

But I don't see how your code calls another page. It looks more like bootstrap. In this case you don't need to pass anything. Cause your "model window" is part of your current page. Thus your variable is already in scope.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41829933
Any ideas on how to get a button or a link to pass the variable to a PHP page?
Can you explain?
If you are putting it into a modal - what is the modal there for?
If you are submitting the modal to the backend the BookId (if it is in the same form) will be submitted
If you are submitting the modal with ajax then just add the BookId

Not sure what the problem is - can you elaborate?
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 41830070
PHP variables that need to be persistent across page loads are typically stored in the session.  So a useful design might go like this:  Once the modal window submits some information to the server-side PHP script, the PHP script calls session_start(), inserts the information into the $_SESSION array, and calls session_write_close().  Thereafter the other PHP scripts can use the information from the modal window by finding it in the $_SESSION array.
https://www.experts-exchange.com/articles/11909/PHP-Sessions-Simpler-Than-You-May-Think.html
0
 
LVL 2

Author Comment

by:stkoontz
ID: 41830522
Thanks to all 3 of you for coming on to give me a hand.  I appreciate it.

Yes, I'm using a Bootstrap modal. Here's a link to a working demo.  I stripped out a lot of the 'pretty stuff' and customized the code sample for my application.

http://testregister.cenational.org/test/modal_link.php

The page is part of an event registration system.  Someone chooses a family member to register for an event.  A list of events pops up in a modal that are specific to that family member.  The person chooses an event and is taken to a page to fill out more information so the family member's ID needs to go to the second page.  The button works great, but it seems easier if I can just have the event link pass the family ID.

Here's the full code for the page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CE National Event Registration System</title>
  <link rel="stylesheet" href="../support/bootstrap.css">
  <link href="../support/style.css" rel="stylesheet" type="text/css" />
  <script src="../support/jquery.min.js"></script>
  <script src="../support/bootstrap.min.js"></script>

<script type="text/javascript">
$(document).on("click", ".open-id_family_member", function (e) {

    e.preventDefault();

    var _self = $(this);

    var myBookId = _self.data('id');
    $("#bookId").val(myBookId);

    $(_self.attr('href')).modal('show');
});
</script>

</head>

<body>
<p>Choose a family member and the modal pops up with a list of events that the family member can register for.</p>
<p align="center"><a data-id="Family Member 1" title="Add this item" class="open-id_family_member btn btn-primary" href="#addEventDialog">Family Member 1</a></p>

<p align="center"><a data-id="Family Member 2" title="Add this item" class="open-id_family_member btn btn-primary" href="#addEventDialog">Family Member 2</a></p>
   <form action="test2.php" method="post" name="form1" id="form1">
      <!-- Modal -->
<form name="form1" method="post" action="get_event_requirements.php">
              <div class="modal fade" id="addEventDialog" role="dialog">
                 <div class="modal-dialog">
                   <!-- Modal content-->
                     <div class="modal-content">
  <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal">&times;</button>
                            <h4 class="modal-title">Choose Your Event</h4>
                </div> 
                <!--modal-header-->
            <div class="modal-body">

               <a href="test2.php?id_family_member=<?php echo $id_family_member;?>"> Event 1</a> (Since multiple events, I want these links to pass the id_family_member to the next page (test2.php) instead of using mutiple buttons)<br />
                        <a href="test2.php?id_family_member=<?php echo $id_family_member;?>"> Event 2</a> <br />
                        <a href="test2.php?id_family_member=<?php echo $id_family_member;?>"> Event 3</a> <br />
                    
                        <input type="text" name="bookId" id="bookId" value="" />
                        <input name="pass_Id" type="submit" value="Pass Id" />
                
</form>
                </div><!--modal-body-->
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div><!--modal-footer-->
               </div><!--modal-content-->
              </div><!--modal-dialog-->
</body>
</html>

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41830642
So basically you want to append the family id to the URL for the event
You will need to modify this code - it binds an event to a non-existent ID that is meant to be your button - you can use a class if you wish - simply modify your button to have the id / class.
It then loops through all the <a> elements in modal-body - again you can modify by identifying your event links with a class and substituting that class for the modal-body in the .each().
The .each then appends the id to each of the event URL's
This code can run on the Pass ID button click or on the Family Member 1 Button click - depending on your requirements. The code is meant as an illustration not a working sample.
Implement in your test link and post back if you get stuck
// Representative of an event where ID is passed
$('#passId').click(function() {
   // get the id you want to pass
   var id = $(this).val();

   // Loop through the event links appending the id to the URL
   $('.modal-body a').each(function() {
       // Get the current url and append the id
       var href = $(this).attr('href') + '&id=' + id;

       // Save the URL back
       $(this).attr('href', href);
   });
});

Open in new window

0
 
LVL 2

Author Comment

by:stkoontz
ID: 41830744
I haven't done much in Javascript except tweak examples, so these are going to be basic questions...

I put your code in the headers section below the code that calls the modal and tweaked for my situation.

<script type="text/javascript">
$('#passId').click(function() {
	 console.log();
   // get the id you want to pass
   var id_family_member = $(this).val();

   // Loop through the event links appending the id to the URL
   $('.modal-body a').each(function() {
       // Get the current url and append the id
       var href = $(this).attr('href') + '&id_family_member=' + id_family_member;

       // Save the URL back
       $(this).attr('href', href);
   });
});
</script>

Open in new window


I added the onclick function to the buttons...

<p align="center"><a data-id="Family Member 1" title="Add this item" class="open-id_family_member btn btn-primary" href="#addEventDialog" onclick="passId">Family Member 1</a>

In the console, I'm getting the error 'passId not defined' which makes me think it's not running the new javascript.

Thanks again for the help!

Steve
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41831234
Good - we can work from here - a few corrections
Onclick is used to bind an event handler to an event. In this case we are doing the binding from jQuery so all you need to do is identify this button with an id. change the onlick to id

<p align="center"><a data-id="Family Member 1" title="Add this item" class="open-id_family_member btn btn-primary" href="#addEventDialog" id="passId">Family Member 1</a>

Open in new window


Next make sure the jquery library is included in your code before the custom script

Third, put the custom code inside a document ready block
$(function() {
  $('#passId').click(function() {
     console.log();
     // get the id you want to pass
     var id_family_member = $(this).val();

     // Loop through the event links appending the id to the URL
     $('.modal-body a').each(function() {
       // Get the current url and append the id
       var href = $(this).attr('href') + '&id_family_member=' + id_family_member;

       // Save the URL back
       $(this).attr('href', href);
     });
  });
});

Open in new window

We need to make sure we are getting the right value to pass in. That is what this line does
     // get the id you want to pass
     var id_family_member = $(this).val();

Open in new window

Except this line is assuming the value is stored in an <input> somewhere on the page.
$(this) refers to the element that triggered the event - in this case the <a> which does not have a value so we need to change this.

Next step from your side - Where does the value you want to pass to the event come from on the page - we need to find that and put that into the code.
0
 
LVL 2

Author Comment

by:stkoontz
ID: 41831689
We're making progress!  The javascript is now running when I click the link.  

The id_family_member comes from a table. I tried manually putting a test in an input...

<input name="id_family_member" id="id_family_member" type="text" value="smith123456" />

I also tried...

<input name="id_family_member" id="passId" type="text" value="smith123456" />

Neither worked.

Thanks again for walking me through this.  I do appreciate it.

Steve
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41831758
Where is the id going to come from eventually?

Let's take your first example
<input name="id_family_member" id="id_family_member" type="text" value="smith123456" />

Open in new window

That is fine - now we nee to update our jQuery to find this control. The current implement uses $(this) which is going to refer to the element that generated the click event (the <a>) which is not what we want. We need to make a simple change to get the value from the input above
$(function() {
  $('#passId').click(function() {
     console.log();
     // UPDATE: we are now targeting the input with id = id_family_member
     var id_family_member = $('#id_family_member').val();

     // Loop through the event links appending the id to the URL
     $('.modal-body a').each(function() {
       // Get the current url and append the id
       var href = $(this).attr('href') + '&id_family_member=' + id_family_member;

       // Save the URL back
       $(this).attr('href', href);
     });
  });
});

Open in new window

0
 
LVL 2

Author Comment

by:stkoontz
ID: 41831884
If I don't answer this question, "Where is the id going to come from eventually?" then I don't understand what you need to know.

It's working now on the test side.  I moved the code into the full page and am looping through the table to get the id_family_member, but the ID isn't changing on the link parameter.  It's always the first of the 3 family members.

Here's a code snipit where I'm trying to pass the variable so it changes.  Let me know if you need more.

<input name="id_family_member" id="id_family_member" type="text" value="<?php echo $id_family_member;?>" />
<a data-id="<?php echo $id_family_member;?>" title="Get event" class="open-id_family_member btn btn-primary" id="passId" href="#addBookDialog">Register</a>

Open in new window


Here's a wider view.  I still have some code cleanup to do.

                <td><a href="fm_view_family_member.php?id_family_member=<?php echo $id_family_member;?>"><?php echo $row_f_members['fm_lname'];?></a></td>
                <td><?php echo $row_f_members['fm_fname'];?></td>
                <td><div class="container">
                          <!-- Trigger the modal with a button -->
					<input name="id_family_member" id="id_family_member" type="text" value="<?php echo $id_family_member;?>" />
					<a data-id="<?php echo $id_family_member;?>" title="Get event" class="open-id_family_member btn btn-primary" id="passId" href="#id_family_dialog">Register</a>
                  
                          <!-- Modal -->
                       <form name="form1" method="post" action="get_event_requirements.php">
                          <div class="modal fade" id="id_family_dialog" role="dialog">

                                <div class="modal-dialog">
                                  
                                  <!-- Modal content-->

                                  <div class="modal-content">
                                        <div class="modal-header">
                                          <button type="button" class="close" data-dismiss="modal">&times;</button>
                                          <h4 class="modal-title">Choose Your Event</h4>
                                        </div> <!--modal-header-->
                                        <div class="modal-body">


                                            <input type="text" name="bookId" id="bookId" value="<?php echo $id_family_member;?>" />
                                            <input name="pass_ISBN" type="submit" value="<?php echo $id_family_member;?>" />
                                                Events:<br />
                                               <?php
                                               foreach ($array_events as $sub_array) {
												   $id_event_group=$sub_array['id_event_group'];
                                                   $id_event = $sub_array['id_event'];
                                                   $event_name = $sub_array['event_name'];
                                                   $event_group_desc = $sub_array['event_group_desc'];
                                              
                                              		echo $event_group_desc?>
                                                	-- <a href="get_event_requirements.php?id_event=<?php echo $id_event;?>&id_family_member=<?php echo $id_family_member;?>&id_event_group=<?php echo $id_event_group;?>"><?php echo $event_name;?><br /></a>
                                               <?php } ?>
                                               <?php
                                               foreach ($array_events_no_lc as $sub_array) {
												   $id_event_group=$sub_array['id_event_group'];
                                                   $id_event = $sub_array['id_event'];
                                                   $event_name = $sub_array['event_name'];
                                                   $event_group_desc = $sub_array['event_group_desc'];

                                           		   echo $event_group_desc?>
                                                	-- <a href="get_event_requirements.php?id_event=<?php echo $id_event;?>&id_family_member=<?php echo $id_family_member;?>&id_event_group=<?php echo $id_event_group;?>"><?php echo $event_name;?></a><br />

                                               <?php } ?>
                                        </div><!--modal-body-->
                                        <div class="modal-footer">
                                          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                                        </div><!--modal-footer-->
    	                         </div><!--modal-content-->
                              
	                         </div><!--modal-dialog-->
                       </div><!--modal-fade-->
                </div><!--End of container-->

				</td>

Open in new window


The page I'm working on now is here...

http://www.testregister.cenational.org/family/family_dashboard.php
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41831991
Ok I see where you are going.
The input question - I was not sure where the family_id was stored on your page hence my question. I see now it is in the link (data-id) which means we are almost there.

1. loose the input - the reason it was not working is that there is 1 input with an id that must be unique but three buttons - you would need an input per button but that makes no sense - especially since the information in in the <a> element already

2. The following simple change should be what you want
$(function() {
  $('#passId').click(function() {
     console.log();
     // UPDATE: family_id is stored in the links data-id so we get it from there
     var id_family_member = $(this).datal('id');

     // Loop through the event links appending the id to the URL
     $('.modal-body a').each(function() {
       // Get the current url and append the id
       var href = $(this).attr('href') + '&id_family_member=' + id_family_member;

       // Save the URL back
       $(this).attr('href', href);
     });
  });
});

Open in new window

0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 2

Author Comment

by:stkoontz
ID: 41832094
Still not there.  I think I'm following your logic, though. So that's good.

If id_family_member is stored in data-id, why would the javascript code be

.data1('id)?

Why is the '1' there?

Also, I tried tweaking $id_family_member in this line..

var href = $(this).attr('href') + '&id_family_member=' + id_family_member;

to be $id_family_members, but the URL didn't change.  Should it have?

Steve
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41832210
Why is the '1' there?
Because I type and don't check - should be data('id')
var href = $(this).attr('href') + '&id_family_members=' + id_family_member;

Open in new window

Which raises the question - is this process adding a single family_id to the link or are we trying or add more than one?
0
 
LVL 2

Author Comment

by:stkoontz
ID: 41832262
I should have mentioned that I tried data('id') and it didn't work.

it's only to supposed to add one family_id to the link.  

Just a curious thing I noticed: When I go to the page: http://www.testregister.cenational.org/family/family_dashboard.php. I click Register next to 'Firstname3' and there's no link appended.  When I click Register next to 'firstName123' the correct link is appended.  Then when I go back and click Register next to 'Firstname3' the link 'firstName123' is still there.

I don't know if this has anything to do with it, but I'm getting the links in the modal from 2 different queries because they have different criteria.  Here's the code:

 foreach ($array_events as $sub_array) {
$id_event_group=$sub_array['id_event_group'];
$id_event = $sub_array['id_event'];
$event_name = $sub_array['event_name'];
$event_group_desc = $sub_array['event_group_desc'];
                                              
echo $event_group_desc?>
-- <a href="get_event_requirements.php?id_event=<?php echo $id_event;?>&id_event_group=<?php echo $id_event_group;?>"><?php echo $event_name;?><br /></a>
<?php } ?>
<?php
foreach ($array_events_no_lc as $sub_array) 

id_event_group=$sub_array['id_event_group'];
$id_event = $sub_array['id_event'];
$event_name = $sub_array['event_name'];
$event_group_desc = $sub_array['event_group_desc'];

echo $event_group_desc?>
-- <a href="get_event_requirements.php?id_event=<?php echo $id_event;?>&id_event_group=<?php echo $id_event_group;?>"><?php echo $event_name;?></a><br />

Open in new window


Steve
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41832337
I should have mentioned that I tried data('id') and it didn't work.
Can you be more specific - was there an error or did it just do what you expected.

The code is correct for what we are trying to achieve so I need to know more about the implementation - can you implement it on your test link and then bump the thread so I can take a look.
0
 
LVL 2

Author Comment

by:stkoontz
ID: 41832397
There was no error.  It just didn't append id_family_member to the link.

Can you see this page?  It's where I'm working now.

http://www.testregister.cenational.org/family/family_dashboard.php  I Ieft in the inputs so we can see what's supposed to be passed.

I don't understand 'bump the thread'

Thanks,

Steve
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41832453
Perfect - able to see error immediately.

The problem is the selector.
#('#passId') targets ONLY the button with the id="passId" - the other buttons don't have that ID so they won't trigger the event.
Change the code to rather target the class that each of those buttons has (open-id_family_member)
Notice in this code the selector changes from
$('#passId')
to
$('.open-id_family_member');
The # in the first selector means an ID
The . in the second selector means a class
Same as in CSS

$(function() {
  // Change selector to target the class of the button
  $('.open-id_family_member').click(function() {
     // UPDATE: family_id is stored in the links data-id so we get it from there
     var id_family_member = $(this).data('id');

     // Loop through the event links appending the id to the URL
     $('.modal-body a').each(function() {
       // Get the current url and append the id
       var href = $(this).attr('href') + '&id_family_member=' + id_family_member;

       // Save the URL back
       $(this).attr('href', href);
     });
  });
});

Open in new window

In you current implementation you will see the first button is actually working - the value is being appended.
I loaded the above into the console and tested - it works so you should be good to go.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41832454
the other buttons don't have that ID so they won't trigger the event.
Correction - I see they do - remove the id="passId" from the buttons - id's must be unique and in this case you don't need the id anymore.
0
 
LVL 2

Author Comment

by:stkoontz
ID: 41832511
It's passing the correct variable now.  But it's not clearing the variable when the modal is closed. So each time the Register button is clicked, it appends another variable.  All we need to do is clear the link each time and we're good!

Steve
0
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 41832714
Right so what we need to do is
1. Check href for the presence of the &id_family_member parameter
2. If we find it we must remove it

We can use the indexOf() and substring() string functions to do this
var ps = href.indexOf('&id_family_member');

Open in new window

This will give us a value from -1 up. If the needle is found a position in the haystack from 0 up is returned or -1 if it is not found.
if (ps >=0) {
   // Found one so remove the last part of the string with substring(start, len)
   href = href.substring(0,ps);
}
// we have a clean string so append the parameter
href += '&id_family_member=' + id_family_member;

Open in new window

Putting it all together
$(function() {
  // Change selector to target the class of the button
  $('.open-id_family_member').click(function() {
     // UPDATE: family_id is stored in the links data-id so we get it from there
     var id_family_member = $(this).data('id');

     // Loop through the event links appending the id to the URL
     $('.modal-body a').each(function() {
       // Get the current url and append the id
       var href = $(this).attr('href');
       var ps = href.indexOf('&id_family_member=');
       if (ps >= 0) {
         href = href.substring(0,ps);
       }
       href += '&id_family_member=' + id_family_member;
       // Save the URL back
       $(this).attr('href', href);
     });
  });
});

Open in new window

0
 
LVL 2

Author Closing Comment

by:stkoontz
ID: 41833556
That is awesome!  Thank you so much for walking me through the solution.  I wish I could give you more points.  :)

Steve
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41833600
You are most welcome Steve,
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Suggested Solutions

Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now