Toastr is not defined, javascript error - javascript

In my php project i'm trying to implement toastr notifications.
When i just use the toastr setup with the hardcoded cdn resources it works fine.
But now i'm using bower etc to included toastr into my bundles.
I am using the latest version of toastr that has a fix to use with Jquery 3+
At this point all the needed resources are included in my bundle.js and bundle.css
In my head:
<link defer="defer" src="http://localhost:8080/GiveaDay/design/css/gad.bundle.css"></script>
<script defer="defer" src="http://localhost:8080/GiveaDay/design/js/gad.bundle.js"></script>
Part of my bundle.js where toast is included:
(not pasting the entire toast code)
/*
* Toastr
* Copyright 2012-2015
* Authors: John Papa, Hans Fjällemark, and Tim Ferrell.
* All Rights Reserved.
* Use, reproduction, distribution, and modification of this code is subject to the terms and
* conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php
*
* ARIA Support: Greta Krafsig
*
* Project: https://github.com/CodeSeven/toastr
*/
/* global define */
(function (define) {
define(['jquery'], function ($) {
return (function () {
var $container;
var listener;
var toastId = 0;
var toastType = {
error: 'error',
info: 'info',
success: 'success',
warning: 'warning'
};
var toastr = {
clear: clear,
remove: remove,
error: error,
getContainer: getContainer,
info: info,
options: {},
subscribe: subscribe,
success: success,
version: '2.1.3',
warning: warning
};
var previousToast;
return toastr;
But now I get the error "toastr is not defined" on following code:
<script>
window.addEventListener('DOMContentLoaded', function() {
(function($) {
$(document).ready(function() {
toastr.options = {
"closeButton": false,
"debug": false,
"newestOnTop": false,
"progressBar": true,
"positionClass": "toast-top-center",
"preventDuplicates": false,
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "5000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
}
});
})(jQuery);
});
<?php if($feedback['type'] == "alert-success"){ ?>
toastr.success("<?php echo $feedback['text']; ?>");
<?php }else if($feedback['type'] == "alert-danger"){ ?>
toastr.error("<?php echo $feedback['text']; ?>");
<?php } ?>
</script>
What am i missing here?
Thanks in advance

Related

owl carousel on localhost wordpress site Uncaught TypeError

I am at a loss, I have tried multiple solutions on other stackoverflow posts about the error but none have worked. I am new to JavaScript and do not work with WordPress often. Any insight is greatly appreciated! Please do not suggest to use the OWL plugin on wordpress.
If there is somewhere else I should put the content of jquer.js (and not have duplicate navigation arrows as mentioned below, please tell me!!)
Things I've already tried:
putting the jQuery(".owl-carousel").owlCarousel({...}); block inside the document.ready block. This gave the same error, and additional error and made the carousel disappear entirely.
changing the order of the enqueued scripts in functions.php
(sometimes the error does go away but then I have two sets of navigation arrows?)
replacing every '$' in jquer.js with jQuery
adding the contents of jquer.js to functions.php and then using
add_action in wp_footer
changing document.ready to window.load
renaming jquer.js to owl.carousel.js (and changing all it's references to match)
The error from the browser console:
Uncaught TypeError: jQuery(...).owlCarousel is not a function
<anonymous> http://localhost/stagingsite/wp-content/themes/strawberry/assets/js/jquer.js?ver=5.4.6:1
jquer.js:1:25
In my functions.php file:
function strawberry_register()
{
$version_css = wp_get_theme()->get('Version');
wp_enqueue_style('strawberry-style', get_template_directory_uri() . "/style.css", array(), $version_css, 'all');
wp_enqueue_script('strawberry-owl-carousel', get_template_directory_uri() . "/assets/js/owl.carousel.min.js", array( 'jquery' ), false, true);
wp_enqueue_script('strawberry-jquery-3.4.1', get_template_directory_uri() . "/assets/js/jquery-3.4.1.min.js", array( 'jquery' ), false, true);
wp_enqueue_style('strawberry-owl-min', get_stylesheet_directory_uri() . "/assets/css/owl.carousel.min.css");
wp_enqueue_style('strawberry-owl-def', get_stylesheet_directory_uri() . "/assets/css/owl.theme.default.min.css");
wp_enqueue_script('strawberry-jquer', get_template_directory_uri() . "/assets/js/jquer.js", array( 'jquery' ), false, true);
}
add_action('wp_enqueue_scripts', 'strawberry_register');
jquer.js:
jQuery(".owl-carousel").owlCarousel({
loop: true,
nav: true,
dots: false,
autoplay: 5000,
stagePadding: 0,
autoplayHoverPause: true,
margin: 0,
responsiveClass: true,
responsive: {
0: {
items: 2,
},
768: {
items: 2,
},
1025: {
items: 4,
},
},
});
jQuery(document).ready(function ($) {
$(".owl-carousel").each(function (index, el) {
var containerHeight = $(el).height();
$(el)
.find("img")
.each(function (index, img) {
var w = $(img).prop("naturalWidth");
var h = $(img).prop("naturalHeight");
$(img).css({
width: Math.round((containerHeight * w) / h) + "px",
height: containerHeight + "px",
});
}),
$(el).owlCarousel({
autoWidth: true,
});
});
});
Relevant from front-page.php:
<script src="<?php bloginfo('template_directory'); ?>/assets/js/jquery-3.4.1.min.js"></script>
<script src="<?php bloginfo('template_directory'); ?>/assets/js/owl.carousel.min.js"></script>
<script src="<?php bloginfo('template_directory'); ?>/assets/js/jquer.js"></script>
Edit*********
Also in my functions.php file, is called with add_action in wp footer:
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>

Change style programmatically ionic toast

I have the following ionicToast into my popup:
onTap: function(e) {
var nombre = scope.data.nombre;
var telefono = scope.data.telefono;
if (nombre.length > 0 && telefono.toString().length > 0) {
scope.data.nombre = nombre;
scope.data.telefono = telefono;
return scope.data;
} else {
ionicToast.show('Debe completar todos los campos.', 'bottom', true, 2500);
e.preventDefault();
}
}
The toast works perfect. But I wanna differentiate when the toast is an error or a success message.
The question is: ¿How can I change the style of the toast programmatically?
Because Sometimes I need the background red (for error message) and sometimes i need it green (for success message).
Also I don't have this toast in my .HTML file, so I can't set a specific style
This is my style that I defined:
.toast-container-error{
background-color: red;
}
.toast-container-success{
background-color: green;
}
Thanks for helping me!
//EDIT//
Using toastr for my custom toast, it not showing on Android devices
index.html
<link href="bower_components/toastr/toastr.css" rel="stylesheet">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js" ></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet" />
Agenda.service (where I wanna use it)
agendaService.$inject = ['remoteDataService','$q', '$ionicPopup', '$rootScope', 'ionicDatePicker'];
/* #ngInject */
function agendaService(remoteDataService,$q, $ionicPopup, $rootScope, ionicDatePicker){
var agendaComplejo = [];
var service = {
obtenerAgenda: obtenerAgenda,
cargarNuevoTurno: cargarNuevoTurno,
abrirAgenda: abrirAgenda
};
toastr.options = {
"closeButton": true,
"debug": true,
"newestOnTop": false,
"progressBar": false,
"positionClass": "toast-bottom-full-width",
"preventDuplicates": false,
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "5000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
}
return service;
function cargarNuevoTurnoPopup() {
var scope = $rootScope.$new();
scope.data = {
nombre: '',
telefono: ''
};
return {
templateUrl: 'scripts/complejo/agenda/nuevo-turno.html',
title: "Nuevo Turno",
scope: scope,
buttons: [{
text: 'Cancelar',
onTap: function(e) {
scope.data.canceled = true;
return scope.data;
}
}, {
text: '<b>Guardar</b>',
type: 'button-positive',
onTap: function(e) {
var nombre = scope.data.nombre;
var telefono = scope.data.telefono;
if (nombre.length > 0 && telefono.toString().length > 0) {
scope.data.nombre = nombre;
scope.data.telefono = telefono;
return scope.data;
} else {
toastr["error"]("Debe completar todos los campos.")
e.preventDefault();
}
}
}]
};
}
Also, I generate the apk with the following command:
ionic build android --debug
It is possible but you have to overide the native style of the component to do this. In our project we use Toastr that give you standard method to display an error or an info and that can be overide more easily.
To include it in your project only include the js and the css
<script src="toastr.js"></script>
<link href="toastr.css" rel="stylesheet"/>
Then the api allow you to raise an info or an error
toastr.info('yourmessage')
toastr.error('your message')
toastr.success('your message')
You can found a demo here:
http://codeseven.github.io/toastr/demo.html

Returning json object from javascript

I'm working with fullcalendar, and the google calendar api where I get my events out and want to deliver them to my fullcalendar as json since the fullcalendar event accept that as a datasource and automatically renders them into the calendar.
I have my html file which includes a number of ressources and a jQuery script that creates the calendar:
<html>
<head>
<link rel='stylesheet' href='fullcalendar/fullcalendar.css' />
<script src='fullcalendar/lib/jquery.min.js'></script>
<script src='fullcalendar/lib/moment.min.js'></script>
<script src='fullcalendar/fullcalendar.js'></script>
<script type='text/javascript' src='fullcalendar/gcal.js'></script>
<script src='fullcalendar/lang/da.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$('#calendar').fullCalendar({
defaultView: 'agendaWeek',
weekends: false,
lang: 'da',
header: false,
allDaySlot: false,
allDayText: '',
height: 695,
minTime: '06:00:00',
maxTime: '20:00:00',
events: 'calendarData.js'
});
});
</script>
</head>
<body>
<div id="calendar"></div>
</body>
</html>
Notice the events: that takes the json object in. I have a json file with identical hardcoded json object as the one i'm trying to create and that works fine. But something fails/is wrong in the following javascript file.
calendarData.js
var CLIENT_ID = 'id';
var SCOPES = ["https://www.googleapis.com/auth/calendar.readonly"];
/**
* Check if current user has authorized this application.
*/
function checkAuth() {
gapi.auth.authorize(
{
'client_id': CLIENT_ID,
'scope': SCOPES.join(' '),
'immediate': true
}, handleAuthResult);
}
/**
* Handle response from authorization server.
*
* #param {Object} authResult Authorization result.
*/
function handleAuthResult(authResult) {
var authorizeDiv = document.getElementById('authorize-div');
if (authResult && !authResult.error) {
// Hide auth UI, then load client library.
authorizeDiv.style.display = 'none';
loadCalendarApi();
} else {
// Show auth UI, allowing the user to initiate authorization by
// clicking authorize button.
authorizeDiv.style.display = 'inline';
}
}
/**
* Initiate auth flow in response to user clicking authorize button.
*
* #param {Event} event Button click event.
*/
function handleAuthClick(event) {
gapi.auth.authorize(
{client_id: CLIENT_ID, scope: SCOPES, immediate: false},
handleAuthResult);
return false;
}
/**
* Load Google Calendar client library. List upcoming events
* once client library is loaded.
*/
function loadCalendarApi() {
gapi.client.load('calendar', 'v3', listUpcomingEvents);
}
/**
* Print the summary and start datetime/date of the next ten events in
* the authorized user's calendar. If no events are found an
* appropriate message is printed.
*/
function listUpcomingEvents() {
var request = gapi.client.calendar.events.list({
'calendarId': 'primary',
'timeMin': (new Date()).toISOString(),
'showDeleted': false,
'singleEvents': true,
'maxResults': 10,
'orderBy': 'startTime'
});
var json = {};
request.execute(function(resp) {
var events = resp.items;
json.json = [];
if (events.length > 0) {
for (i = 0; i < events.length; i++) {
var event = events[i];
var when = event.start.dateTime;
if (!when) {
when = event.start.date;
}
json.json.push({id : i+1, title : event.summary, start : event.start.dateTime, end : event.end.dateTime, desc : event.description});
}
}
});
return json;
}
As you might see this is very close to the api calendar javascript quickstart apart from the json at the end. I would like the script to return a json object to the fullcalendar but this doesn't work, so how could I change this if possible?
When i stringify and alert the object I can see that the object created is the same as the previously mentioned json file that does work.
Edit:
The json file i'm talking about and which data can be used looks like this:
[{"id":"1","title":"Test 1","start":"2016-05-26","end":"2016-05-26T16:30:00","allDay":false},{"id":"2","title":"Test 2","start":"2016-05-26","end":"2016-05-26T17:00:00","allDay":false},{"id":"3","title":"Test 3","start":"2016-05-27T08:00:00","end":"","allDay":false}]
When I stringify and alert the object it looks like this:
var myObject = JSON.stringify(json);
alert(myObject);
{"json":[{"id":1,"title":"ghhgfgh","start":"2016-05-26T14:30:00+02:00","end":"2016-05-26T15:30:00+02:00"}]}
Your problem is here:
$(document).ready(function () {
$('#calendar').fullCalendar({
defaultView: 'agendaWeek',
weekends: false,
lang: 'da',
header: false,
allDaySlot: false,
allDayText: '',
height: 695,
minTime: '06:00:00',
maxTime: '20:00:00',
events: 'calendarData.js'
});
});
The "events" can't get a javascript file as an input nor as a direct json string. You can give it an array of events, a URL or a function.
I guess you intended to feed the "events" with the results of listUpcomingEvents() function.
You can do it that way (just make sure your you add the calendarData.js as script src in your HTML file as well):
$(document).ready(function () {
$('#calendar').fullCalendar({
defaultView: 'agendaWeek',
weekends: false,
lang: 'da',
header: false,
allDaySlot: false,
allDayText: '',
height: 695,
minTime: '06:00:00',
maxTime: '20:00:00',
events: function(start, end, timezone, callback){
callback(listUpcomingEvents());
},
});
});
To interract between JS / JSON object you've to use:
JSON.stringify()
JSON.parse()
Reference are here and here
For example: JS > JSON > JS
var x = {
y: 'hello',
z: 1
};
console.log(JSON.parse(JSON.stringify(x)));
convert it into JSON object like this:
var Jobj = JSON.parse(your_string_data);

i18next jquery help migrating to i18next jquery v3.0.0

Good day all,
i need a little bit of help migrating from i18next jquery 1.11.1 to version 3.0.0
currently this is my setup
<!-- Core JS files -->
<script type="text/javascript" src="../js/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="../js/i18next.min.js"></script> (v1.11.1)
$(function(){
// i18next Configuration
// -------------------------
var namespaces = ["nav" ,"common" ];
var options = {
ns: {
namespaces: namespaces,
defaultNs: namespaces[0]
},
resGetPath: '../assets/locales/__ns__/__lng__.json',
debug: false,
load: 'unspecific',
detectLngQS: 'lang',
fallbackLng : 'en',
cookieName: 'applang',
//cookieExpirationTime : ,
useLocalStorage: false,
cookieDomain: '*.mydomain.com',
useCookie: true,
lngWhitelist: ['en','es', 'de', 'fr']
};
i18n.init(options ,function (err,t) {
$('body').i18n(); // Init 18n
});
})
and when i want to load additional namespace i do this
var namespaces = ["newFile"];
i18n.loadNamespaces(namespaces, function (err, t) {
// init i18n
$('body').i18n();
.............. other stuff in here
})
but when i try to use the latest i18next v3 with the jquery-i18next (https://github.com/i18next/jquery-i18next) keeping the same logic i get errors on the loadNamespaces function (Uncaught TypeError: namespaces.forEach is not a function), below is the new setup
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/i18next/3.0.0/i18next.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-i18next/0.0.2/i18next-jquery.min.js" ></script>
i18next
.use(i18nextXHRBackend)
.init({
lng: 'de',
backend: {
loadPath: '../assets/locales/{{lng}}/{{ns}}.json'
}
}, function(err, t) {
jqueryI18next.init(i18next, $);
$('.body').localize();
});
var namespaces = ["newFile"];
i18n.loadNamespaces(namespaces, function (err, t) {
// init i18n
$('body').localize();
.............. other stuff in here
})
For anyone interested here is my solution
<script type="text/javascript" src="../assets/js/core/libraries/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="../assets/js/plugins/internationalization/i18next.min-v3.3.1.js"></script>
<script type="text/javascript" src="../assets/js/plugins/internationalization/jquery-i18next.js"></script>
<script type="text/javascript" src="../assets/js/plugins/internationalization/i18nextXHRBackend.min.js"></script>
<script type="text/javascript" src="../assets/js/plugins/internationalization/i18nextBrowserLanguageDetector.min.js"></script>
<script type="text/javascript" src="../assets/js/plugins/internationalization/i18nextLocalStorageCache.min.js"></script>
<script type="text/javascript" src="../assets/js/plugins/internationalization/i18nextIntervalPluralPostProcessor.min.js"></script>
$(function(){
// i18next Configuration
// -------------------------
var namespaces = ["nameSpace1" ,"NameSpace2" ],
cacheOptions = {
// turn on or off
enabled: true, // prefix for stored languages
prefix: 'i18next_res_',
expirationTime: 1*24*60*60*1000 // expiration
},
lngDetectionOption = {
//order and from where user language should be detected
order: ['querystring', 'cookie', 'localStorage', 'navigator', 'htmlTag'],
//keys or params to lookup language from
lookupQuerystring: 'lng',
lookupCookie: 'i18next',
lookupLocalStorage: 'i18nextLocalStorage',
//cache user language on
caches: ['localStorage','cookie'],
// optional expire and domain for set cookie
cookieMinutes: 365*24*60, // 1 year
cookieDomain: 'myDomain',
// optional htmlTag with lang attribute, the default is:
htmlTag: document.documentElement
},
i18nextoptions = {
compatibilityJSON: 'v2',
debug: true,
whitelist : ['en','es', 'de', 'fr'],
ns: namespaces,
load: 'unspecific',
fallbackLng : 'en',
detection: lngDetectionOption,
backend: {loadPath: '../assets/locales/{{ns}}/{{lng}}.json'},
//cache : cacheOptions
};
i18next
.use(i18nextBrowserLanguageDetector)
.use(i18nextXHRBackend)
.use(Cache)
.use(i18nextIntervalPluralPostProcessor)
.init(i18nextoptions, function (err, t) {
var options = $().jqueryI18nextOptions;
//init jquery-i18next
jqueryI18next.init(i18next, $,options);
$('body').i18n(); // Init 18n
})
})

AngularJS Toastr fadeIn fadeOut

i have a service code like ;
<script>
var pop = function (type, message, callbackfn,duration) {
toaster.pop({
type: type,
body: message,
showCloseButton: true,
timeout: duration,
positionClass: "toast-top-full-width",
onHideCallback: callbackfn,
hideDuration : 1000,
hideMethod: 'slideUp'
});
</script>
but my toaster is not fading in or fading out.
My AngularJS toastr version is : 0.4.15 which option should i add in pop method to get fadeOut feature ?
I'm not familiar with the Angular port, but the original can be played with here . This would suggest the properties your concerned with are:
"showMethod": "fadeIn"
"hideMethod": "fadeOut"
"showDuration": "300"
"hideDuration": "3000"
"timeOut": "2000"
Is your toast showing at all?
Have you confirmed that your type, message, and duration variables are populated at the point of calling?

Categories