WordPress.org

Ready to get started?Download WordPress

Forums

Adding Javascript to WP from old site (29 posts)

  1. geothom
    Member
    Posted 8 months ago #

    Hi - I am a newbie here and have very limited knowledge of Javascript, php etc but do have a programming b/ground. I want to use existing code from a page on our existing site http://www.poncesuites.net/reservation/selectroom.php in a page on the site I am developing using WP 3.7.1 http://www.poncesuiteshotel.com/check-availability.
    Below is an extract of the code (there are 1000+ lines in total).
    I have looked at many posts and sites regarding this but am unsure where to start. Can someone please point me in the right direction!!

    <link href="css/styles.css" rel="stylesheet" type="text/css" />
    <script src="datetimepicker_css.js"></script>
    
    <!--sa minus date-->
    <script type="text/javascript">
    	//============ LEAVE PAGE CONFIRMATION ===============
    	var stay_flag = true;
    	window.onbeforeunload = function (e) {
    	  if (stay_flag){
    	  var message = "You are about to reserve room/s.",
    	  e = e || window.event;
    	  // For IE and Firefox
    	  if (e) {
    		e.returnValue = message;
    	  }
    
    	  // For Safari
    	  return message;
    	}
    	};
    </script>
    <script type="text/javascript">
    	// Error checking kept to a minimum for brevity
    
    	function setDifference(frm) {
    	var dtElem1 = frm.elements['start'];
    	var dtElem2 = frm.elements['end'];
    	var resultElem = frm.elements['result'];
    
    // Return if no such element exists
    	if(!dtElem1 || !dtElem2 || !resultElem) {
    return;
    	}
    
    	//assuming that the delimiter for dt time picker is a '/'.
    	var x = dtElem1.value;
    	var y = dtElem2.value;
    	var arr1 = x.split('/');
    	var arr2 = y.split('/');
    
    // If any problem with input exists, return with an error msg
    if(!arr1 || !arr2 || arr1.length != 3 || arr2.length != 3) {
    resultElem.value = "Invalid Input";
    return;
    	}
    
    var dt1 = new Date();
    dt1.setFullYear(arr1[2], arr1[1], arr1[0]);
    var dt2 = new Date();
    dt2.setFullYear(arr2[2], arr2[1], arr2[0]);
    
    resultElem.value = (dt2.getTime() - dt1.getTime()) / (60 * 60 * 24 * 1000);
    }
    </script>
    <!--sa minus date// <script type="text/javascript"> -->
    <!--sa input that accept number only-->
    <SCRIPT language=Javascript>
          <!--
          function isNumberKey(evt)
          {
             var charCode = (evt.which) ? evt.which : event.keyCode
             if (charCode > 31 && (charCode < 48 || charCode > 57))
                return false;
    
             return true;
          }
          //-->
    </SCRIPT>
    
    <script type="text/javascript">
    function GetInternetExplorerVersion()
      // Returns the version of Internet Explorer or a -1 for other browsers.
      {
        var rv = -1;
        if(navigator.appName == 'Microsoft Internet Explorer')
        {
          var ua = navigator.userAgent;
          varre  = newRegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
          if(re.exec(ua) != null)
          rv = parseFloat( RegExp.$1 );
        }
        return rv;
      }
      function functiononLoad()
      {
        var version = GetInternetExplorerVersion()
        if (version <= 7 && version > -1)
        {
          // Code to run in Internet Explorer 7 or earlier.
    	  // document.getElementById(para4).innerHTML="";
    	  $("#warning_message_for_browser").hide();
        }
      }
      functiononLoad();
    </script>
    
    <?php
    	$arival = $_POST['start'];
    	$departure = $_POST['end'];
    	$adults = $_POST['adult'];
    	$child = $_POST['child'];
    
    	// $date_para_start= str_split($arival,"/");
    
    	$date_start_day  =substr($arival,0,2);
    	$date_start_month=substr($arival,3,2);
    	$date_start_year =substr($arival,6,4);
    
    	$date_end_day  =substr($departure,0,2);
    	$date_end_month=substr($departure,3,2);
    	$date_end_year =substr($departure,6,4);
    
    	$_SESSION['date_started'] = $date_start_day."/".$date_start_month."/".$date_start_year;
    	$_SESSION['date_ended'] = $date_end_day."/".$date_end_month."/".$date_end_year;
    	$_SESSION['adultNum'] = "";
    	$_SESSION['childNum'] = "";
    	//Java Variables
    
    	echo "<script type=\"text/javascript\">";
    
    	echo "var date_start_day=". $date_start_day .";";
    	echo "var date_start_month=". $date_start_month .";";
    	echo "var date_start_year=". $date_start_year .";";
    
    	echo "var date_end_day=". $date_end_day .";";
    	echo "var date_end_month=". $date_end_month .";";
    	echo "var date_end_year=". $date_end_year .";";
    
    	echo "var original_adultNum=". $adults .";";
    	echo "var adultNum=Number(". $adults .");";
    	echo "var childNum=Number(". $child .");";
    
    	echo "</script>";
    
    ?>
  2. WPyogi
    Volunteer Moderator
    Posted 8 months ago #

  3. geothom
    Member
    Posted 8 months ago #

    Thanks for the quick reply Wpyogi. I already have this link bookmarked and 'sort of' understand some of it. Any chance of an example using the code I attached? ---- PLEASE!

  4. Andrew
    Forum Moderator
    Posted 8 months ago #

    Are you using your own theme?

  5. geothom
    Member
    Posted 8 months ago #

    I am using Cusomizr theme (sorry, should have said). Any help will be much appreciated. If someone can give me an example of how to 'convert' at least one of the javascript references in the existing code, I can probably do the rest (hopefully). Sorry to be asking this but I cannot get anyone local who knows WordPress and as stated, have VERY limited knowledge of web based languages.
    THANKS in advance.

  6. Andrew
    Forum Moderator
    Posted 8 months ago #

    Have you created a Child Theme?

  7. geothom
    Member
    Posted 8 months ago #

    Yes I have Andrew. Boy! Quick response - thanks. You can tell I'm a newbie!

  8. Andrew
    Forum Moderator
    Posted 8 months ago #

    What folders (if any) do you have in your Child Theme?

  9. geothom
    Member
    Posted 8 months ago #

    OK, I copied some of the folders from the old site 'reservation' folder to the child theme folder - namely folders:
    js, libs, scripts, src.

    Also have a css folder containing:
    style.css,
    styles.css,
    datepicker.css.

    In the js folder the files are:
    application.js
    datepicker.js
    form_validation.js
    jquery.js

  10. Andrew
    Forum Moderator
    Posted 8 months ago #

    Cool, which JS file do you want to start with?

  11. geothom
    Member
    Posted 8 months ago #

    Thanks!!! Well I guess the datepicker. Don't know if you looked at the old site page http://www.poncesuites.net/reservation/selectroom.php but it is driven by the visitor entering a 'check-in' date and a check-out date. REALLY appreciate the help Andrew!

  12. Andrew
    Forum Moderator
    Posted 8 months ago #

    We can help you load the JavaScript into your WordPress theme, if that's what you're asking.

  13. geothom
    Member
    Posted 8 months ago #

    Sure ok - what's involved?

  14. Andrew
    Forum Moderator
    Posted 8 months ago #

    You'd need to create a file named "functions.php" into your Child Theme root directory.

    Then in that file you'd enqueue the JavaScript file so that WordPress can load it properly and here is an example of doing that:

    function mainScripts() {
        wp_enqueue_script( 'datepicker', get_stylesheet_directory_uri() . '/js/datepicker.js', '', '1.0', true );
    }
    
    add_action( 'wp_enqueue_scripts', 'mainScripts' );

    In that example you can also enqueue more scripts by simply adding them within the mainScripts function, e.g;

    function mainScripts() {
        wp_enqueue_script( 'datepicker', get_stylesheet_directory_uri() . '/js/datepicker.js', '', '1.0', true );
        wp_enqueue_script( 'form_validation', get_stylesheet_directory_uri() . '/js/form_validation.js', '', '1.0', true );
    }
    
    add_action( 'wp_enqueue_scripts', 'mainScripts' );

    You may want to avoid loading "jquery.js" if that file contains the jQuery library. The jQuery library is already loaded in WordPress and you don't need to load it again.

    Note that you need to add the opening and closing PHP tags when you've created functions.php, e.g

    <?php
    ?>
  15. geothom
    Member
    Posted 8 months ago #

    Thank you very much Andrew! I will give this a try maybe later tonight (I am in the Philippines but orig. from Scotland). Is there some way I can get in touch if I run into problems as I am sure you don't have eyes on this thread forever!

  16. Is there some way I can get in touch if I run into problems

    Just reply on this thread if you have more questions. Andrew's a regular and I am sure he'll see your topic. ;)

  17. geothom
    Member
    Posted 8 months ago #

    Cool! Thank Jan.

  18. geothom
    Member
    Posted 8 months ago #

    Back again!! I created the 'functions.php' file in the root of the child theme folder as directed. I copied your first code piece and put the PHP tags but maybe did not get them in the correct place:

    <?php
    function mainScripts() {
      wp_enqueue_script( 'datepicker', get_stylesheet_directory_uri() . '/js/datepicker.js', '', '1.0', true );
    
    }
    
    add_action( 'wp_enqueue_scripts', 'mainScripts' );
    ?>

    Anyway, when I preview the page I get a mix of code and partly formatted areas but the datepickers do not show (just like an outline) and the first column is all messed up. Since typing the above I have added most of the functions to the 'functions.php' file but with little/no change.
    Below is extract of code on the page:

    <link href="css/styles.css" rel="stylesheet" type="text/css" />
    
    <script type="text/javascript" src="datetimepicker.js"></script>
    
    <!--sa error trapping-->
    <!--sa nivo slider-->
     
    <!--sa calendar-->
    <script type="ext/javascript" src="js/datepicker.js"></script>
    <link href="css/datepicker.css" rel="stylesheet" type="text/css" />
    
    <script type="text/javascript">//
    <![CDATA[
    function makeTwoChars(inp) {
            return String(inp).length < 2 ? "0" + inp : inp;
    }
    
    function initialiseInputs() {
            // Clear any old values from the inputs (that might be cached by the browser after a page reload)
            document.getElementById("sd").value = "";
            document.getElementById("ed").value = "";
    
            // Add the onchange event handler to the start date input
            datePickerController.addEvent(document.getElementById("sd"), "change", setReservationDates);

    What am I missing?

  19. Andrew
    Forum Moderator
    Posted 8 months ago #

    Are you getting anything instructive of what's happening in your browser's console? I would assume your JS files cannot be found.

  20. geothom
    Member
    Posted 8 months ago #

    No - nothing. Page loads, no errors, just not right. I will give up soon for tonight as it is late and will try a cut-down version with only the date-pickers (if I can figure out the correct code to extract) tomorrow. Thanks again for your time and advice.

  21. geothom
    Member
    Posted 8 months ago #

    OK I'm back. Tried using code from 'index.php which is basically a page displaying only a frame with two datepickers plus one drop-down list. I am completely stuck here as I really don't understand how WP sequences things and I have also read that depending on where you are calling javascript, the path should be different. Sorry if this is not the 'done thing' but below is all the code I copied (with a few mods to delete unwanted text). I have tried changing the path referencing the javascript but makes no difference. I feel I am missing something very basic here.
    The page loads with the frame but the datepickers are not showing nor are their labels. Please can someone assist and get me in the right direction.
    My site structure is:
    Root
    ~
    js
    scripts
    wp-content
    themes
    customizr
    ~
    functions.php
    header.php
    style.css

    customizr-child-01
    css
    js
    lib
    scripts
    src
    functions.php
    style.css

    Extract from the 'functions.php' file in child theme

    <?php
    function mainScripts() {
      wp_enqueue_script( 'datepicker', get_stylesheet_directory_uri() . '/js/datepicker.js', '', '1.0', true );
      wp_enqueue_script( 'view_calendar', get_stylesheet_directory_uri() . '/js/datepicker.js', '', '1.0', true );
    }
    
    add_action( 'wp_enqueue_scripts', 'mainScripts' );
    ?>

    Code copied from index.php on old site:

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    	<link href="/wp-content/themes/customizr-child-01/css/styles.css" rel="stylesheet" type="text/css" /> <!--sa nivo slider-->
    <!--sa calendar-->
    <script type="text/javascript" src="js/datepicker.js"></script>	<link href="/wp-content/themes/customizr-child-01/css/datepicker.css" rel="stylesheet" type="text/css" /><script type="text/javascript">// <![CDATA[
    function makeTwoChars(inp) {
            return String(inp).length < 2 ? "0" + inp : inp;
    }
    
    function initialiseInputs() {
            // Clear any old values from the inputs (that might be cached by the browser after a page reload)
    echo "TEST"
            document.getElementById("sd").value = "";
            document.getElementById("ed").value = "";
    
            // Add the onchange event handler to the start date input
            datePickerController.addEvent(document.getElementById("sd"), "change", setReservationDates);
    }
    
    var initAttempts = 0;
    
    function setReservationDates(e) {
            // Internet Explorer will not have created the datePickers yet so we poll the datePickerController Object using a setTimeout
            // until they become available (a maximum of ten times in case something has gone horribly wrong)
    
            try {
                    var sd = datePickerController.getDatePicker("sd");
                    var ed = datePickerController.getDatePicker("ed");
            } catch (err) {
                    if(initAttempts++ < 10) setTimeout("setReservationDates()", 50);
                    return;
            }
    
            // Check the value of the input is a date of the correct format
            var dt = datePickerController.dateFormat(this.value, sd.format.charAt(0) == "m");
    
            // If the input's value cannot be parsed as a valid date then return
            if(dt == 0) return;
    
            // At this stage we have a valid YYYYMMDD date
    
            // Grab the value set within the endDate input and parse it using the dateFormat method
            // N.B: The second parameter to the dateFormat function, if TRUE, tells the function to favour the m-d-y date format
            var edv = datePickerController.dateFormat(document.getElementById("ed").value, ed.format.charAt(0) == "m");
    
            // Set the low range of the second datePicker to be the date parsed from the first
            ed.setRangeLow( dt );
    
            // If theres a value already present within the end date input and it's smaller than the start date
            // then clear the end date value
            if(edv < dt) {                 document.getElementById("ed").value = "";         } } function removeInputEvents() {         // Remove the onchange event handler set within the function initialiseInputs         datePickerController.removeEvent(document.getElementById("sd"), "change", setReservationDates); } datePickerController.addEvent(window, 'load', initialiseInputs); datePickerController.addEvent(window, 'unload', removeInputEvents);
    // ]]></script>
    <script type="text/javascript">// <![CDATA[
    var stay_flag = true; 	window.onbeforeunload = function (e) { 	  if (stay_flag){ 	  var message = "Do you want to continue on reservation?", 	  e = e || window.event; 	  // For IE and Firefox 	  if (e) { 		e.returnValue = message; 	  } 	  // For Safari 	  return message; 	} 	};
    // ]]></script>
    <!--sa error trapping-->
    <script type="text/javascript">// <![CDATA[
    function validateForm() { var x=document.forms["index"]["start"].value; if (x==null || x=="")   {   alert("you must enter your check in Date(click the calendar icon)");   return false;   } var y=document.forms["index"]["end"].value; if (y==null || y=="")   {   alert("you must enter your check out Date(click the calendar icon)");   return false;   } var childrenNum = document.forms["index"]["child"].value; if (!(IsNumeric(childrenNum))){ 	alert("Please enter a numeric value"); 	return false; } stay_flag = false; } function IsNumeric(input) { 	return (input - 0) == input && input.length > 0;
    }
    // ]]></script>
    <!--end sa nivo slider-->
    
    <style type="text/css"><!--
    
    --></style><!--sa poip up
    	<link href="src/facebox.css" media="screen" rel="stylesheet" type="text/css" />
    
    <script src="lib/jquery.js" type="text/javascript"></script>
      <script src="src/facebox.js" type="text/javascript"></script>
    <script type="text/javascript">
        jQuery(document).ready(function($) {
          $('a[rel*=facebox]').facebox({
            loadingImage : 'src/loading.gif',
            closeImage   : 'src/closelabel.png'
          })
        })
      </script>
    
    -->
    <!--?php <br ?--> if (isset($_SESSION['date_started']))
    {
    // echo "has value";
    // echo $_SESSION['date_started'];
    }
    else
    {
    // echo "
    
    no value
    
    ";
    }
    ?>
    <!-- TOP -->
    <div id="top1"></div>
    <div id="top"><!-- HEADER --></div>
     
    <div id="header">
    <div id="formPan">
    <h2 class="style2" style="text-align: center;">Check Availability</h2>
    <form action="selectroom.php" method="post" name="index" onsubmit="return validateForm()">
    <div style="margin: 15px 10px; padding: 10px 10px; border: 1px solid #fff;">
    <table border="0">
    <tbody>
    <tr>
    <td>
    <div align="right"><label>Check-in Date : </label></div></td>
    <td width="110"><input class="w8em format-d-m-y highlight-days-67 range-low-today" id="sd" style="height: 25px;" type="text" maxlength="10" name="start" readonly="readonly" value="" /></td>
    </tr>
    <tr>
    <td>
    <div align="right"><label>Check-out Date : </label></div></td>
    <td><input class="w8em format-d-m-y highlight-days-67 range-low-today" id="ed" style="height: 25px;" type="text" maxlength="10" name="end" readonly="readonly" value="" /></td>
    </tr>
    <tr>
    <td>
    <div align="right"><label>Adults : </label></div></td>
    <td><select class="ed" name="adult"><option>1</option><option>2</option><option>3</option><option>4</option><option>5</option><option>6</option><option>7</option><option>8</option><option>9</option><option>10</option><option>11</option><option>12</option><option>13</option><option>14</option><option>15</option><option>16</option></select></td>
    </tr>
    <tr>
    <td colspan="2">
    <div style="color: #fff;" align="right"><i>Adult = Persons 6yrs and older</i></div></td>
    </tr>
    <tr>
    <td>
    <div align="right">
    <div align="right"><label>Children : </label></div>
    </div></td>
    <td><input class="ed" id="child" style="width: 40px; padding: 5px 5px;" type="text" name="child" value="0" /></td>
    </tr>
    <tr>
    <td colspan="2"><input id="button1" type="submit" name="Input" value="Next" /></td>
    </tr>
    </tbody>
    </table>
    </div>
    </form></div>
    </div>
    <!-- FOOTER -->
    <div id="footer">
    
    <img alt="" src="images/call.jpg" width="156" height="37" />
    <p style="text-align: right;"><a href="http://www.poncesuites.net/index.html">HOME</a> |<a href="http://www.poncesuites.net/about.htm"> ABOUT US </a>|<a href="http://www.poncesuites.net/contact.htm"> CONTACTS </a>|<a href="http://www.poncesuites.net/gallery.htm"> GALLERY </a>|<a href="http://www.poncesuites.net/roomrates_3.htm"> ROOM RATES </a></p>
    
    </div>
    <!-- BOTTOM -->
    <div id="bottom"></div>
    <script type="text/javascript" src="scripts/jquery-1.4.3.min.js"></script><script type="text/javascript" src="jquery.nivo.slider.pack.js"></script>
    <script type="text/javascript">// <![CDATA[
    $(window).load(function() { 	$('#slider').nivoSlider(); });
    // ]]></script>
  22. Andrew
    Forum Moderator
    Posted 8 months ago #

    Can the JS files be found on your page, are they loaded?

  23. geothom
    Member
    Posted 8 months ago #

    Hi Andrew. Excuse the ignorance but how can I tell?

  24. Andrew
    Forum Moderator
    Posted 7 months ago #

    Open your website in Google Chrome, right click anywhere on the page and select "Inspect element".

    Then switch to the "Console" tab and see if anything is shown.

  25. geothom
    Member
    Posted 7 months ago #

    Ok thanks. Have seen that done but did not cross my mind!

    Now I have some clues. Can you throw light on the Invalid CSS property names and the path error for language (bottom extract below.
    Any general 'hints' will be appreciated. Meantime I will look at the js paths.
    Extract from console:

    shouldShowTB file Not Exist - default action show Toolbar
    DOMException
     compatibility.start.js:16
    chrome.tabs is not available: You do not have permission to access this API. Ensure that the required permission or manifest property is included in your manifest.json. binding:431
    Invalid CSS property name: -webkit-text-size-adjust blue.css:80
    Invalid CSS property name: transform blue.css:5764
    Invalid CSS property value: transform 3s ease blue.css:6081
    Invalid CSS property name: transform blue.css:6087
    Invalid CSS property value: linear-gradient(top, #f4f4f4, #e6e6e6) blue.css:6129
    Invalid CSS property name: transform blue.css:8901
    Failed to load resource chrome-extension://jgaanchmbkbjjjclkdlcjhhipijhndil/tb/al/state.html
    Invalid CSS property value: 0x styles.css:20
    Invalid CSS property declaration at: 4px styles.css:197
    Invalid CSS property declaration at: 4px styles.css:198
    Invalid CSS property declaration at: 4px styles.css:199
    Invalid CSS property declaration at: ; styles.css:233
    Invalid CSS property value: nonne styles.css:608
    Failed to load resource: the server responded with a status of 404 (Not Found) http://www.poncesuiteshotel.com/check-availability/js/datepicker.js
    Uncaught SyntaxError: Unexpected token < www.poncesuiteshotel.com/check-availability/:356
    Uncaught SyntaxError: Unexpected end of input www.poncesuiteshotel.com/check-availability/:392
    Uncaught SyntaxError: Unexpected token ILLEGAL www.poncesuiteshotel.com/check-availability/:395
    Failed to load resource: the server responded with a status of 404 (Not Found) http://www.poncesuiteshotel.com/lang/lang/lang/lang/lang/lang/lang/lang/lang/lang/lang/lang/lang/lang/en.js
    Failed to load resource: the server responded with a status of 404 (Not Found) http://www.poncesuiteshotel.com/lang/lang/lang/lang/lang/lang/lang/lang/lang/lang/lang/lang/en.js
  26. Andrew
    Forum Moderator
    Posted 7 months ago #

    Failed to load resource: the server responded with a status of 404 (Not Found) http://www.poncesuiteshotel.com/check-availability/js/datepicker.js

    To clarify, you are using this code specifically to enqueue the datepicker js (?):

    wp_enqueue_script( 'datepicker', get_stylesheet_directory_uri() . '/js/datepicker.js', '', '1.0', true );
  27. geothom
    Member
    Posted 7 months ago #

    To clarify - yes. So the path in the enqueue '/....' needs changed to point to the js folder in the child theme folder.

  28. geothom
    Member
    Posted 7 months ago #

    Posted b4 I was finished. I will pursue some mods and see how far I get but will be tomorrow now. Thanks yet again for dedicating some of your precious time to this. Come over to the hotel and I'll shout you a beer (or three)

  29. geothom
    Member
    Posted 7 months ago #

    Sorry, but back yet again but after a somewhat 'successful' day. Managed to reduce the errors from 107 to just 12 - some of which it transpires, appear on the original page. Anyway, my problem now is that the calenders do not show when I click on a datepicker. After looking at the code and the messages in console, perhaps I should reconsider approach!
    What I ultimately want is the ability for the visitor to enter 'Check-In' and 'Check-Out' dates on most pages with the datepickers in either a sidebar or page column and this data stored in session. Any thoughts on whether I should pursue with what I have or start fresh? If the former, why don't the calenders show?
    http://www.poncesuiteshotel.com/check-availability/

    Thanks in advance

Reply

You must log in to post.

About this Topic