简体   繁体   中英

jQuery reloading function on same page causing error

I'm making a search bar with a select box and an input field. The input field uses the jQuery predictive search. The select box has 2 options; Location and Archive, the Location is default. When the Archive is selected it replaces the input field with the jQuery datepicker function and another input field to replace the one that was removed.

Now, all this works fine when you select each of the options once. If you go back and select one of the options again it stops functioning and generates an error in the console.

Uncaught TypeError: $ is not a function

... when Archive is selected again, and...

Uncaught TypeError: Cannot read property 'noConflict' of undefined

... when Location is selected again.

I actually have another similar search bar on another site that works just fine. It's just on this site there is an old jQuery version loaded at the end of the page that I can't touch.

So basically how do I resolve these errors/conflicts if the user selects the same option more than once?

Search bar file:

<html>
<head>
<meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="http://www.example.com/css/foundation3.css">

  <script src="http://www.example.com/javascripts/modernizr.foundation.js"></script>

    </head>
<body>  


<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">


<form id="form1" name="form1" method="post" action="http://www.example.com/search/" >

<div class="row">  
<div class="two columns" style="padding: 0;">
    <select name="drop_list_menu" id="drop_list_menu" class="drop">
        <option value="1">Location</option>
        <option value="2">Archive</option>
    </select>
</div>

<span id="result_menu">
<div class="eight columns" style="padding: 0;">

        <input type="text" name="search" id="search" size="35" style="height: 37px; max-width: 250px; display: inline;" placeholder="Example: New York, NY"/>

</div>  

<div class="two columns" style="padding: 0;">
    <input type="submit" name="submit" id="submit" value="Search" class="button" style="width: 120px;" />
</div>  

</span>

</div>  

</form>



 <script>

jQuery( document ).ready(function( $ ) {

        var n;
        var u;
        var username = '<?php echo $user_name_global;?>';
        var tab = '1';



            // if user chooses an option from the select box...
             $(".drop").change(function (e) {
            var SelectId = "#"+e.target.id
            //alert(SelectId);

                //var element = document.getElementsByClassName('drop').id;
                //var changedElement = this;
        var i = SelectId.split('menu_')[1];
        var sbox_menu = '#sbox_menu';
        var result_menu = '#result_menu';

        var slot = i;
        //alert(result_menu);


                // get selected value from selectbox with id #drop_list
                var selectedDepartment = $(this).val();
                //alert(selectedDepartment);    

                $.ajax({

                    url: "http://www.example.com/search/get_dept_search.php",
                    data: "q="+selectedDepartment,
                    dataType: "json",

                    // if successful
                    success: function (response, textStatus, jqXHR) {

                            var list = $("#result_menu");

                            $.each(response.teacherNames, function (i, val) {
                                $(result_menu).html(val);
                            });

                    }});

            });



                    var availableTags = "http://www.example.com/search/get_pred_results.php";

                      $( "#search" ).autocomplete({
                        source: availableTags,
                        select: function (event, ui) {
                                window.location = ui.item.url;
                                }
                      });
                    //predsearch.stopPropagation();


        });

    </script>

  <script src="http://www.example.com/javascripts/foundation.min.js"></script>

  <!-- Initialize JS Plugins -->
  <script src="http://www.example.com/javascripts/app.js"></script>
</body>
</html>

File containing the replacement code:

<?php

$q = $_GET["q"];

if(stripos($q, '1') !== FALSE)
{
$y = array();
$y[] = '<script>
jQuery.noConflict();
jQuery(document).ready(function($){
  $(function() {
    var availableTags = "http://www.example.com/search/get_pred_results.php";

                      $( "#search" ).autocomplete({
                        source: availableTags,
                        select: function (event, ui) {
                                window.location = ui.item.url;
                                }
                      });   
});
});
  </script>
 <div class="six columns" style="padding: 0;">
    <input  type="text" id="search" name="search"/>
    <input type="hidden" name="search_url"  id="search_url">
    </div>
  <div class="two columns" style="padding: 0;">
    <input type="submit" value="Search" class="button tiny" style="height: 3.4em;">
    </div>';
}

if(stripos($q, '2') !== FALSE)
{
$y = array();
$y[] = '<script>
jQuery.noConflict(true);
(function( $ ) {
  $(function() {
    $( "#datepicker" ).datepicker();

    var availableTags = "http://www.example.com/search/get_pred_results.php";

                      $( "#search" ).autocomplete({
                        source: availableTags,
                        select: function (event, ui) {
                                window.location = ui.item.url;
                                }
                      });
     });
})(jQuery);
  </script>
  <div class="six columns" style="padding: 0;">
  <div class="four columns" style="padding: 0;"><input type="hidden" name="search_url" id="search_url"><input type="text" id="datepicker" name="datepicker" placeholder="Pick a date"></div><div class="eight columns" style="padding: 0;"><input  type="text" id="search" name="search"/ placeholder="Choose a location"></div>
  </div>
  <div class="two columns" style="padding: 0;">
    <input type="submit" value="Search" class="button tiny " style="height: 3.3em;">
    </div>
  ';
}

 print json_encode(array(
            "teacherNames" => $y,
            "anotherReturnValue" => "just a demo how to return more stuff")
    );
?>

Any help appreciated.

Well, I fixed it. Not proud of how I did it, but if it works... it works.

Basically all I did was load jQuery again when the replacement code is called.

All I did was add:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

The new replacement code:

<?php

$q = $_GET["q"];

if(stripos($q, '1') !== FALSE)
{
$y = array();
$y[] = '
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script>
jQuery.noConflict();
jQuery(document).ready(function($){
  $(function() {
    var availableTags = "http://www.friendlyforecast.com/search/get_pred_results.php";

                      $( "#search" ).autocomplete({
                        source: availableTags,
                        select: function (event, ui) {
                                window.location = ui.item.url;
                                }
                      });   
});
});
  </script>
 <div class="six columns" style="padding: 0;">
    <input  type="text" id="search" name="search"/>
    <input type="hidden" name="search_url"  id="search_url">
    </div>
  <div class="two columns" style="padding: 0;">
    <input type="submit" value="Search" class="button tiny" style="height: 3.4em;">
    </div>';
}

if(stripos($q, '2') !== FALSE)
{
$y = array();
$y[] = '<script>
jQuery.noConflict(true);
(function( $ ) {
  $(function() {
    $( "#datepicker" ).datepicker();

    var availableTags = "http://www.friendlyforecast.com/search/get_pred_results.php";

                      $( "#search" ).autocomplete({
                        source: availableTags,
                        select: function (event, ui) {
                                window.location = ui.item.url;
                                }
                      });
     });
})(jQuery);
  </script>
  <div class="six columns" style="padding: 0;">
  <div class="four columns" style="padding: 0;"><input type="hidden" name="search_url" id="search_url"><input type="text" id="datepicker" name="datepicker" placeholder="Pick a date"></div><div class="eight columns" style="padding: 0;"><input  type="text" id="search" name="search"/ placeholder="Choose a location or publication"></div>
  </div>
  <div class="two columns" style="padding: 0;">
    <input type="submit" value="Search" class="button tiny " style="height: 3.3em;">
    </div>
  ';
}

 print json_encode(array(
            "teacherNames" => $y,
            "anotherReturnValue" => "just a demo how to return more stuff")
    );
?>

I was hoping for a better solution, and if you have one I would still like to hear it. I'll wait a couple of days before I mark my answer as the correct one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM