0

Problem: I don't know why my script is not loading a value into the selected input section of a form

Scenario: The page, call it the host page, permanently displays a dialog with a link as the content. If a user clicks on the link another dialog, call it the "form dialog" opens with a form. Some items are inserted into the form by the code - platform, browser and url of the host page.

It’s the URL that is not working.

The URL is acquired on the host page and stored as a .data item for recovery by the "form dialog" script. I tested this on a simpler set up and it worked perfectly however, it refuses to work on the current set up.

Symptoms: The URL is read and stored as expected but the script is not writing it into the form. The approach I've used is to add a callback function when the dialog is first loaded. The callback uses a .val() function to write the data to the form, or at least that's the intention. The value is written to the form during the dialog setup so that when the user clicks the information is already loaded into the form.

I'd appreciate any pointers or suggestions as to what might be the cause of the problem and/or how to correct it.

Thanks.

script:

enter <script type="text/javascript">
//Triggers a modal containing the feedback form.
$(document).ready(function() {
$('#target a').each(function() {
    var $link = $(this);
    var $dialog = $('<div></div>')
        .load($link.attr('href'))
        .dialog({
            autoOpen: false,
            title: $link.attr('title'),
            width: 600,
            height: 500,
            modal:  true,
            open:   function (event,ui) {
                $("input[name='url']").val($('body').data('value2'));


            }
        });

    $link.click(function() {
        $dialog.dialog('open');
        $( "#accordion" ).accordion({
            collapsible: true,
            active: false
        });
        return false;
    });
});
});
</script>

HOST PAGE

<html xmlns="http://www.w3.org/1999/xhtml">

</head>

<body>


<!--Script to get the url of the page and store it as a data item for use on the form -->
<script type="text/javascript">
<?php 
     $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
     ?>
var pageAddress="<?php echo $url?>";

$('body').data('value2', pageAddress );

</script>
<p>The following just confirms that the  url is being stored on the page</p>
<div>
The URL value stored on the page is 
<span id='urlcheck'></span>
<p>The location is 
</p>

<script type="text/javascript">
$("span#urlcheck").html("<p>" +$("body").data("value2")+ "</p>");
</script>
</div>



<!--Check to see if the cookie is set -->
<?php include ('../_assets/include_files/checkreaderStatus.php');?>
<!-- The following file is for development only. It adds a navigation menu to pages in   which its included. -->
<?php  include('../_assets/include_files/navigation.html');?>
<!--------------------------------------------------------------------------->
<!-- Start The Page Display -->
<h1>Page 1 Of The Blog</h1>
<p>This page simulates the page on the blog where testers will land.</p>

<!--Dialog for the "Feedback Form Button -->
<script type="text/javascript">
//Reads the flag readerStatus, if set creates a dialog with a permanently displayed "Feedback Button". NOTE TO SELF: This has to be on the page in order for the php to be to be processed by the server!
var readerStatus="<?php echo $readerStatus; ?>";
if (readerStatus == "tester") {
    $(function(){
        $("#dialog").dialog();
                })
}
</script>

<!-- Content for the Feedback Form Button -->   
<div id="dialog" title="Feedback Button">
<div  title="Feedback Form">
    <p id='target'><a href="feedbackform.php"  title='Feedback Form' >Feedback   Form</a></p>
    <p class="notes">This form is dragable and resizable</p>
</div>
</div>




<script type="text/javascript">
//Triggers a modal containing the feedback form.
$(document).ready(function() {
$('#target a').each(function() {
    var $link = $(this);
    var $dialog = $('<div></div>')
        .load($link.attr('href'))
        .dialog({
            autoOpen: false,
            title: $link.attr('title'),
            width: 600,
            height: 500,
            modal:  true,
            open:   function (event,ui) {
                $("input[name='url']").val($('body').data('value2'));


            }
        });

    $link.click(function() {
        $dialog.dialog('open');
        $( "#accordion" ).accordion({
            collapsible: true,
            active: false
        });
        return false;
    });
});
});
</script>
</body>
</html>

Feedback Form Feedback Form

<link rel="stylesheet" type="text/css" href="../_assets/scripts/black-tie/jquery-ui-1.8.4.custom.css" />
</head>

<body>



<?php
$browser = get_browser(null, true);
?>
<!-- ajax form next? -->
<script type="text/javascript">
$(document).ready(function() {
var options = {
    target : '#output1',
    url:    'comments.php',
    clearForm:  'true'
};
// bind 'myForm' and provide a simple callback function 
$('#myform').ajaxForm(options);
return false;
});
</script>
<!-- Script to execute text prompts in the fields -->
<!-- optional name -->
<script type="text/javascript" id="demoscript">
$(document).ready(function(){
  //Optionsal Name
    $("#textTagDemo").fieldtag();
  //Textarea
    $("#area").fieldtag();
});
</script>







<div id="accordion">
<h3><a href="#">Instructions</a></h3>
    <div>
        <p>
        Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
        ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
        amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
        odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.
        </p>
    </div>
<h3><a href="#">Broken Links</a></h3>
<div>
<form action="comments.php" method="post" name="broken_Links" id="myform" >
                <fieldset>
                    <p>
                        <input name="name" type="text" size="50" id="textTagDemo" title="OPTIONAL: Add your name" />

                    </p>
                    <p>
                        <input name="nowhere" type="radio" value="linknowhere" />Link is
                        broken and doesn't go anywhere
                    </p>
                    <p>
                        <input name="wrong_url" type="radio" value="linktowrongurl" />Link
                        goes to an unexpected destination
                    </p>
                    <p>
                        <input name="other" type="radio" value="linkother" />Other -
                        Please explain in the description box below
                    </p>
                    <em>Description</em>
                    <p>Please add as much descripton as you can about the problem you
                        noticed</p>
                    <textarea name="description" id="area" cols="50" rows="10" title="Please add as much description as you can."></textarea>
                    <p>
                        Page Address: <br /> <input name="url" type="text" value=""
                            id="targetURL" size="100" title="Page Address" />
                    </p>
                    <p>
                        Browser<input name="browser" type="text"
                            value="<?php echo $browser['browser'] ?>" />
                    </p>
                    <p>
                        Operating System<input name="operating_system" type="text"
                            value="<?php echo $browser['platform'] ?>" />
                    </p>
                    <p>
                        <input type="submit" name="submit" id="button" value="Submit" />
                    </p>
                </fieldset>
            </form>
    <!-- server response -->
            <h2>Output Response</h2>
            <p id="output1">

            </p>
            <!--End form 4 broken links-->
</div>
<h3><a href="#">Errors In The Text</a></h3>
<div>
    <p>
    Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.
    Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero
    ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis
    lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.
    </p>
    <ul>
        <li>List item one</li>
        <li>List item two</li>
        <li>List item three</li>
    </ul>
</div>
<h3><a href="#">Confusing Layout</a></h3>
<div>
    <p>
    Cras dictum. Pellentesque habitant morbi tristique senectus et netus
    et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in
    faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia
    mauris vel est.
    </p>
    <p>
    Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus.
    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per
    inceptos himenaeos.
    </p>
</div>
</div>
</body>
</html>
dorich
  • 1,059
  • 1
  • 17
  • 25
  • Can you provide an example of the output you would like to see, and an example of the incorrect output that you currently receive? – George Cummins Jun 01 '11 at 18:38
  • Would it be possible maybe to simplify the issue a bit so users don't need to read your total application to help you? I, for one don't answer these '1000 liner' posts. – Stephane Gosselin Jun 01 '11 at 18:40
  • @ George Cummins: Thanks for your feedback. I apologize but the failure mode was an empty field, which I though I described, but reading it 24 hour later I see its unclear. – dorich Jun 02 '11 at 18:31
  • @ stefgosselin: Agreed. I had the same concern and gave it some thought before posting, however, I'm a novice (stumbling around in the dark) and my concern was that I didn't understand what interaction was causing the problem so it seemed I needed to show all the main elements. I suppose with hindsight I could have reduced some of the content on the form and taken out some of the extraneous elements in the html but all of the script was required - if only because I was "in the dark" as to what was happening. Any pointers to more effective posting would be appreciated. Thanks for your response. – dorich Jun 02 '11 at 18:44

1 Answers1

1

The problem I suppose is that you put the data onto the body without it being wrapped inside a $(document).ready() clause.

For a quick fix you can define the url just as a variable, and then access that variable inside your script.

example:

http://jsfiddle.net/LF2rs/1/

Ps: I would recommend reading into seperating your php code (using templates), your javascript (place them seperately in a .js file!). This will make it a lot easier and manageble to spot and prevent mistakes.

Arend
  • 3,741
  • 2
  • 27
  • 37
  • Thanks for your response. This solved the problem, although what I did was to simply replace the .val(.data) with .val(variable). I'm a bit puzzled by this - the variable is declared in a small script on the page that uses php to read the URL and then converts the result to a js variable. I would have thought that the scope of the variable would have meant it wasn't available to other scripts but perhaps I don't understand "variable scope". One question on your ps: I thought the way to get a variable from php to js was to embed the php in the js. Is that incorrect, is there another approach? – dorich Jun 02 '11 at 15:11
  • About why it did not work was that you triet to use jQuery before jQuery was loaded. I usually only use inline javascript for variables, but preferrable in a function or method that is defined outside the page, and rely on json for that. eg. on load: startMyPage({ ... json object or variable here here .. }); You are also correct about the variable scope: I'm not sure, but I believe that in general things defined in the document will be in the global scope (there's a hierarchy). See: http://stackoverflow.com/questions/500431/javascript-variable-scope – Arend Jun 02 '11 at 15:16
  • @ Arend. Thanks for the follow up very helpful. To reinforce your comments on global variables W3Schools say that if a variable is defined outside of a function then its available to any script or function on the webpage. I also found that global variables are attached to the window object see [this](http://snook.ca/archives/javascript/global_variable) as one example of the explanation. Thanks for the tip on JSON, I'll need to go study that to understand it but I sorta get the idea. – dorich Jun 02 '11 at 18:27