Jquery problem with wordpress theme

Jquery problem with wordpress theme
0.0 0

#1

Hi

I am having a problem with some code i am using on my home page which is not working correctly on wordpress theme Publisher. I have tried other themes and the code is working also with Twenty Fifteen theme without any problems. Inspecting the problems with chrome console log i see the following errors below:

Uncaught SyntaxError: Unexpected token class (index):1248

Uncaught ReferenceError: getPrayerTimings is not defined
at Object.success (main.js:166)
at i (jquery.js?ver=1.12.4:2)
at Object.fireWith [as resolveWith] (jquery.js?ver=1.12.4:2)
at y (jquery.js?ver=1.12.4:4)
at XMLHttpRequest.c (jquery.js?ver=1.12.4:4)

The jquey version my local wordpress and theme usses is 1.12.4
https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js

some screenshot i made of the errors
screenshot

i have tried other jquery versions problem still shows up and code is not working as it should.

The html code i am using:

<html>

<head>

	<link href="/wp-content/uploads/prayertimes/css/stylo.css" rel="stylesheet" type="text/css" />
	<link href="/wp-content/uploads/prayertimes/css/searchy.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="/wp-content/uploads/prayertimes/js/PrayTimes.js"></script> 

</head>

<body>
<script language="JavaScript">

function date_time(id)
{
        date = new Date;
        h = date.getHours();
        if(h<10)
        {
                h = "0"+h;
        }
        m = date.getMinutes();
        if(m<10)
        {
                m = "0"+m;
        }
        s = date.getSeconds();
        if(s<10)
        {
                s = "0"+s;
        }
        result = ''+h+':'+m+':'+s;
        document.getElementById(id).innerHTML = result;
        setTimeout('date_time("'+id+'");','1000');
        return true;
}
		</script>


<script type="text/javascript">
       /*Daily Prayer Timing Code Starts*/
	   function getPrayerTimings(latitude, longitude, tzoffset, isdst) {
		prayTimes.setMethod('MWL');
		prayTimes.adjust( {asr: 'Standard', isha: '90 min'} );
		prayTimes.tune( {fajr: -90, shoroeq: 0, dhuhr: 0, asr: 0, maghrib: 0, isha: 0} );
		
           	var todayDate = new Date(); // today
            function prayerTimings(offset) {
                todayDate.setDate(todayDate.getDate() + offset);
                var times = prayTimes.getTimes(todayDate, [latitude, longitude], tzoffset, isdst);
                var list = ['Fajr', 'Sunrise', 'Dhuhr', 'Asr', 'Maghrib', 'Isha'];
                var html = '<table id="dailyTimeTable">';
                html += '<tr class="qibla_map_bg_h"><td><span class="fajri"></span><br />Fajr</td><td><span class="shoroeqi"></span><br />Shoroeq</td><td><span class="dhuhri"></span><br />Dhuhr</td><td><span class="asri"></span><br />Asr</td><td><span class="maghribi"></span><br />Maghrib</td><td><span class="ishai"></span><br />Isha</td></tr>';
                for (var i in list) {
                    html += '<td id="qibla_map_bg_tr">' + times[list[i].toLowerCase()] + '</td>';
                }
                html += '</tr></table>';
                document.getElementById('dailyTimeTable-Container').innerHTML = html;

                function jQuery(id) {
                    return document.getElementById(id);
                }
            }

            function highlight() {
                var date = new Date();
                var thisminutes = date.getHours() * 60 + date.getMinutes();
                //thisminutes = 1119;
                var tbl = document.getElementById("dailyTimeTable")
                var cells0 = tbl.rows[0].cells;
                var cells1 = tbl.rows[1].cells;
                var help = [];
                for (var i = 0; i < cells1.length; i++) {
                    var currenttime = cells1[i].innerHTML.match(/([0-9][0-9]):([0-9][0-9])/);
                    if (currenttime) currentminutes = parseInt(currenttime[1]) * 60 + parseInt(currenttime[2]);
                    entry = {
                        currentminutes: currentminutes,
                        currentidx: i
                    };
                    help.push(entry);
                }
                help.sort(function (a, b) {
                    return a.currentminutes - b.currentminutes;
                });
                var foundnext = foundcurrent = false;
                var inext = icurrent = -1;
                for (var i = 0; i < help.length; i++) {
                    currentminutes = help[i].currentminutes;
                    currentidx = help[i].currentidx;
                    if (!foundnext && currentminutes > thisminutes) {
                        foundnext = true;
                        inext = currentidx;
                    }
                    if (currentminutes <= thisminutes) {
                        foundcurrent = true;
                        icurrent = currentidx;
                    }
                }
                if (!foundnext) inext = help[0].currentidx;
                if (!foundcurrent) icurrent = help[help.length - 1].currentidx;
                for (var i = 0; i < cells1.length; i++) {
                    if (i == inext) {
                        cells0[i].className = "next";
                        cells1[i].className = "next";
                    } else if (i == icurrent) {
                        cells0[i].className = "current";
                        cells1[i].className = "current";
                    } else {
                        cells0[i].className = "";
                        cells1[i].className = "";
                    }
                }
                window.setTimeout(highlight, 0)
            }

            prayerTimings(0);
            highlight();
        }
		/*Daily Prayer Timing Code Ends*/
	</script>
	

		
						<div class="qibla_map_bg">
						<div id="map-html"></div>
						
						<div class="dateback">
						<div class="time"><span id="date_time"></span><script type="text/javascript">window.onload = date_time('date_time');</script></div>
						<div class="date">
						<script language="JavaScript">
	var fixd;

	var tod=new Date();
	var weekday=new Array("Zondag","Maandag","Dinsdag","Woensdag","Donderdag","Vrijdag","Zaterdag");
	var monthname=new Array("Januari","Februari","Maart","April","Mei","Juni","Juli","Augustus","September","Oktober","November","December");

	var y = tod.getFullYear();
	var m = tod.getMonth();
	var d = tod.getDate();
	var dow = tod.getDay();
	document.write(weekday[dow] + " " + d + " " + monthname[m] + " " + y);

      </script></div>
	  
			<div class="idate">
			<script type="text/javascript">
document.write(writeIslamicDate(-2));
</script></div></div>

					
						<form id="formy" name="search_form" method="get" action="">
							<input id="search" name="search" placeholder="Zoek uw loacatie..." type="text">
						</form>
			

						<div id="dailyTimeTable-Container"></div>
				
          <script id="map-tmpl" type="text/x-jquery-tmpl">
             <h4>{{city}}</h4>
          </script>
			 
    </div> 
    <!-- Placed at the end of the document so the pages load faster -->

    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&key="></script>


    <script src="/wp-content/uploads/prayertimes/js/utils.js"></script>
    <script src="/wp-content/uploads/prayertimes/js/utils-geo.js"></script>
    <script src="/wp-content/uploads/prayertimes/js/mustache.js"></script>
    <script src="/wp-content/uploads/prayertimes/js/main.js"></script>
    <script>
        var city = localStorage.getItem("city");
        var lat = localStorage.getItem("latitude");
        var lng = localStorage.getItem("longitude");
        if (!city) {
            city = "Maastricht";
            lat = 50.8514;
            lng = 5.6910;
        }
        updateMap(city, lat, lng);
        jQuery("#selectcity").on("change", function() {
            var city = jQuery("#selectcity option:selected").text();
            getLatlngFromCity(city);
            jQuery("#search").val(city);            
        })
		
    </script>
<script type="text/javascript">
jQuery("#search").on('change keyup', function(e){if(e.keyCode && e.keyCode !== 13){return;}setTimeout(function(){jQuery('#search').attr('placeholder', jQuery.trim(jQuery('#map-html').text()));}, 200);}).
trigger('change');
jQuery('#geo').on('click keyup', function(e){if(e.keyCode && e.keyCode !== 13){return;}jQuery("#search").trigger('change');});
</script>
</body>
</html>

and my main.js file

/**
 * Created with JetBrains WebStorm.
 * User: bilelz
 * Date: 17/04/13
 * Time: 22:24
 * To change this template use File | Settings | File Templates.
 */

var isAutocompleted = false;

jQuery(document).ready(function() {
    autocompleteInit();
                       log("init");
    /* search 
    jQuery('div').submit(function() {
        if(!isAutocompleted){
            jQuery("#search").blur();
            getLatlngFromCity(jQuery("#search").val());
            log("typed from input search");
        }

        isAutocompleted = false; /* reset boolean value 
        return false;
    }); */


	/* geo localisation */
	
	// script for print geo link when focus in searchbox
	// jQuery("#search").focus(function() {
		// jQuery("#geo").addClass("show");
	// });	
	// jQuery("#search").blur(function() {
		// jQuery("#geo").removeClass("show");
	// });

	jQuery("#geo").click(function(e) {
		jQuery("#geo").removeClass("show");
		jQuery("#container").removeClass("blur");

		infoGeo("");
		if(navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
		} else {
			infoGeo("Votre navigateur ne prend pas en compte la géolocalisation HTML5");
		}

		function successCallback(position) {
			
			getCityFromCoord(position.coords.latitude, position.coords.longitude);
			
			infoGeo("Géolocalisation réussie :-)");
			infoHide();
			jQuery("#search").trigger('change');
		};

		function errorCallback(error) {
			// if(getStorage("lastId") != undefined){
				// id = getStorage("lastId");
			// }else{		
				// id = "2988507" // Paris;
			// }			
			// getWeatherById(id);
			
			switch(error.code) {
				case error.PERMISSION_DENIED:
					infoGeo("L'utilisateur n'a pas autorisé l'accès à sa position");
					break;
				case error.POSITION_UNAVAILABLE:
					infoGeo("L'emplacement de l'utilisateur n'a pas pu être déterminé");
					break;
				case error.TIMEOUT:
					infoGeo("Le service n'a pas répondu à temps");
					break;
			}			
		};
		
		return false;
	});
	
	/* geo localisation */

    /* print on not  #cityClearSearch button */
    jQuery("#search").keyup(function() {
        if (jQuery.trim(jQuery(this).val()) != "") {
            jQuery("#cityClearSearch").removeClass("hide");
        } else {
            jQuery("#cityClearSearch").addClass("hide");
            jQuery(this).val(""); // trim space
        }
    });

    jQuery("#search").on("blur", function (){
        jQuery("#search").keyup();
    });

    jQuery("#search").on("focus", function (){
        jQuery("#search").keyup();
    });

    /* end : print on not #cityClearSearch button */



    jQuery("#multiCityList").on("click", "a", function (){
        jQuery('#multiCityList').html("").hide();
        updateMap(jQuery.trim(jQuery(this).text()), jQuery(this).attr("lat"), jQuery(this).attr("lng"));
        return false;
    });

    jQuery("#multiCityList").on("click",".removeCityList", function (){
        jQuery('#multiCityList').html("").hide();
    });

    jQuery("*[type=reset]").on("click",function (){
        jQuery('#multiCityList').html("").hide();
    });
});
function autocompleteInit() {


    var map;
    var geocoder;
    var input = document.getElementById('search');
    var options = {
        types : ['(cities)']
    };

    var autocomplete = new google.maps.places.Autocomplete(input, options);

    google.maps.event.addListener(autocomplete, 'place_changed', function() {
        try {

            var placeLat = getLatFromStr(autocomplete.getPlace().geometry.location.toString());
            var placeLng = getLngFromStr(autocomplete.getPlace().geometry.location.toString());
            updateMap(jQuery("#search").val(), placeLat, placeLng)
            jQuery("#search").val("").blur();
            jQuery('#multiCityList').html("").hide();
            log("autocomplete");
            isAutocompleted = true;
        } catch(e) {
            isAutocompleted = false;
            jQuery('div').submit();
            log("catch maps autocomplete");
            log(e);
        }
    });

    google.maps.event.addDomListener(input, 'keydown', function(e) {
        if (e.keyCode == 13) {
            if (e.preventDefault) {
                e.preventDefault();
            } else {
                /* nothing */
            }
        }
    });
}

function updateMap(city, lat, lng){
    var time = (new Date()).getTime() / 1000;
    jQuery.getJSON("https://maps.googleapis.com/maps/api/timezone/json?location=" + lat + "," + lng + "&timestamp=" + time + "&key=", function (data) {
        var tzinfo = data;
        var offsethours = tzinfo.rawOffset / 3600;
        if (tzinfo.dstOffset == 0) isdst = 0; else isdst = 1;
        getPrayerTimings(lat, lng, offsethours, isdst)
    });

    localStorage.setItem("city", city);
    localStorage.setItem("latitude", lat);
    localStorage.setItem("longitude", lng);

    var tmpl = jQuery("#map-tmpl").html();
    var html = Mustache.render(tmpl, {city:city, lat:lat, lng:lng});
    jQuery("#map-html").html("").append(html);
}

Hope someone can help me out.
Thanks in advance


#2

Hi!

The first error you are getting is because to the variable ‘html’ you only can add text.

The second error says “getPrayingTime is not defined”. That means that, at the time the function is called (in line main.js:166 as detailed on the console), it is not defined; For some reason you are calling code that it’s not loaded. You can try put all your code (the scripts inside the html) inside the jquery.ready function and check if the bug solves.