JS not working in Rails - javascript

I am familiar with the Turbolinks issue, but it seems my fix is not working.
I have this:
var ready = function () {
$('.add_to_cart').click(function (e) {
e.preventDefault();
var pid = $(this).attr('data-pid');
$.post('/cart/'+ pid, function(data){
var data = JSON.parse(JSON.stringify(data));
$('#items-in-cart').text(data['cart_size']);
console.log(data);
});
});
};
$(document).ready(ready);
$(document).on('page:load', ready);
My javascript won't trigger on document load. I have to refresh. I have done this fix on other pages, and it worked. What else should I try / look for?
EDIT:
I am using jquery (through the jquery-rails gem, 3.1.2)
I found this error in jquery:
Uncaught TypeError: undefined is not a function
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
Found a reference to this 'bug' here.
Edit 2:
Here is my html.slim:
=link_to "Add to Cart", "#", class: 'add_to_cart', data: {pid: #product.id}
If I get rid of that line, the rest of my javascript functions work in the ready block on page load. If I keep it, I get the Uncaught TypeError.
Edit 3:
I removed turbolinks from my app and it works fine. I'd like to keep turbolinks, but at this point it's my only solution.

You need to bind the click event since the content is loading via ajax, do this
$('body').on('click', '.add_to_cart', function(e){
// js code
});

Related

how to use Jquery getScript caching using dynamically generated url

I am looking for a way cache script with dynamically generated url I am currently using Octobercms that combines all scripts into one file on render I have seen in the past people using php but October cms uses blade the script I have looked at is this one
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
console.log( textStatus );
});
the problem I have is that the url the combined script is different on ever installation.
I have figured out how to stop the problem with the "Velocity is already loaded" error by using the following
$("#loader").load(href, function(){
delete jQuery.Velocity;
$.getScript( "http://yoursite.com/test/combine/b075f6a5b111b3375ecc553c0d813ee5-1534701438", function() {
// Call custom function defined
});
just need to figure out how to replace "http://yoursite.com/test/combine/b075f6a5b111b3375ecc553c0d813ee5-1534701438" as this alters any help with this part of the code would be great I have tried user2033464 code but when I console.log(path); after $.getScript I get "ReferenceError: path is not defined"
I have solved my problem as follows
var path= $("script[src]:eq(1)").attr('src'); //needs to be globle to work in getScript
$(document).ready(function() {
$("#loader").load(href, function(){
delete jQuery.Velocity; // stops Velocity reloading error
$.getScript( path, function() { // loads script into newly loaded page into existing page
// Call custom function defined
});
});
I hope the helps someone with similar problem thank user2033464 for your assistance

Ajax method does not fire on initial page load

Note: Please see edit at the bottom after reading this question.
This issue is only happening in IE 11, and only started occurring after a recent Windows update. There were 5 updates, one of which was specific to IE, so I uninstalled that one. However, the issue still exists. Before I consider rolling back the remaining updates, is there something inherently wrong in my code? The following is inside the document ready function:
$('#leftmenu>li').click(function () {
var clickedId = this.id;
$.ajax({
url: "Session/Index/",
cache: false,
success: function (result) {
if (result.length > 0)
{
performListItemAction(clickedId);
}
else
{
window.location.href = 'Home/Index/'
}
}
});
});
And the following is the performListItemAction method (a separate function not in document.ready):
function performListItemAction(item)
{
alert("clicked");
$(".tabui").each(function ()
{
$(this).hide();
});
$(".listitem").each(function ()
{
$(this).css("background", "transparent");
});
$(document.getElementById(item)).css("background-color", "#C8C8C8");
var targetId = $(document.getElementById(item)).data('target');
var target = $(document.getElementById(targetId));
target.show();
}
The alert clicked never appears when this problem happens, and that is how I concluded the ajax call is not working.
A few other notes:
This issue isn't happening on Firefox.
This only happens if I directly login to the page with a direct URL. If I log in via the application's home screen, and then go to the page that uses the above javascript, the issue doesn't occur.
Thank you.
EDIT: I just now see that the same issue is now occurring in Firefox as well. It's just much less frequent.
After trial and error, I think I fixed the issue by adding a forward slash to the beginning of each of the URLs, and added the type: "POST", to the ajax call. I don't know why it was working fine before, but now this works in all my attempts.

Selecting DOM elements with inAppBrowser - Cordova

It seems I can't select DOM elements from a website I've loaded using the inAppBrowser plugin. When I log document.getElementById("input") it's null. The resources I've read on this have treated selecting elements as trivial, but I seem unable.
Here's the code I'm using:
var obj = {
link: "https://www.foolink.com",
input: "barInput",
func: function(obj) {
document.getElementById("input").value = obj.input;
}
}
var ref = cordova.InAppBrowser.open(obj.link, "_blank");
ref.addEventListener('loadstop', function() {
ref.executeScript({code:obj.func(obj)})
})
Has anyone else encountered this before? Using jquery to get selectors on gives me selectors from the index.html file, not the inAppBrowser window.
*edit: currently using inAppBrowser 1.4.0 and cordova 6.0.0
Frix33 got the gears turning with his answer, but I don't think it specifically identifies the problem so posting my own. The script injected into the page must be a STRING or else it is just executed by the app, which is a different document hence the null result before. It works if you replace {code: obj.func(obj)} with:
var codePass = "document.getElementById('input').value = '"+ obj.input +"';"
var ref = cordova.InAppBrowser.open(obj.link, "_blank", "location=yes");
ref.addEventListener('loadstop', function(event) {
ref.executeScript({code:codePass})
});
You can pass as many script lines as needed using that format.
This work for me (cordova 6.1.1, inappbrowser 1.4.0, platform Android):
...
ref.addEventListener('loadstop', function () {
ref.executeScript(
{ code: "document.getElementById('inputID')" },
function (values) {
alert(values[0]);
}
);
...

JS not running until second refresh of page

Just what it says. I'm trying to do some simple drop down filtering with jquery, and my function doesn't get executed on page load. Here's what I've checked:
added a console.log to verify
used document.ready to call function
It's getting loaded through sprockets in app.js
it's listed in dev console, and I don't get any resource not found errors
Here's the crazy part : everything works perfectly after one refresh. Console.log comes back and reports the listener has been attached to the select element and everything is roses.
Any ideas why?
EDIT here's the entirety of the js (there may be a better way of doing this, also open to suggestions):
//unrelated JS
$(document).ready(function(){
$("#user_state_code option").unwrap();
$state_copy = $("#user_state_code").children().clone(true);
$("#user_country_code").change(function(){
console.log("state filter called");
filterStates($("#user_country_code").val());
});
$("#user_country_code").change();
});
function filterStates(countryCode){
$("#user_state_code").html(
$state_copy.get().filter(function(d){
var currCountry = String(d.value);
return currCountry.slice(0,2) == countryCode;
})
);
}
Epilogue
Here's what needed to be fixed (thanks to #Rain who put me in the right track, and prompted me to find this amazing resource: Rails 4 turbo-link prevents jQuery scripts from working
var ready = function() {
$("#user_state_code option").unwrap();
$state_copy = $("#user_state_code").children().clone(true);
$("#user_country_code").change(function(){
console.log("state filter called");
filterStates($("#user_country_code").val());
});
filterStates($("#user_country_code").val());
};
function filterStates(countryCode){
$("#user_state_code").html(
$state_copy.get().filter(function(d){
var currCountry = String(d.value);
return currCountry.slice(0,2) == countryCode;
})
);
}
$(document).ready(ready);
$(document).on('page:load', ready);

Jquery script not working with IE

I written this script, to add JavaScript functionality to my online shop, the script works fine with Firefox and Chrome, but will not run on ie, and i am not sure why?
i am using jQuery(function( $ ){ instead of .ready due to script conflicts, i have tested the script using .ready and it still does not work with ie.
if anyone has an ideas they would be much appreciated.
jQuery(function( $ ){
setInterval(function(){ updatecart(); },8000);
$('.addtobag').on('click', function(){
event.preventDefault();
var postdata = new Object();
var action = $(this).closest('form').attr('action');
$(':input',$(this).closest('form')).each(function(evt){
var L = $(this).attr('name')
postdata[L] = $(this).val();
});
$.post(action, postdata);
generate('success'); //display banner
updatecart(); //update cart
});
var postdata = new Object();
postdata['basket'] = phpbasket;
function updatecart() {
$.post("/get_cart_details.php", postdata, function (data) {
var obj = $.parseJSON(data);
$('#qty_js').text(obj.items_qty);
$('#amt_js').text(obj.items_value);
});
}
function generate(type) {
var n = noty({
text: 'The item(s) have been added to your basket.',
type: type,
dismissQueue: true,
layout: 'topCenter',
theme: 'defaultTheme'
});
console.log('html: '+n.options.id);
setTimeout(function() {
$.noty.closeAll();
}, 5000);
}
});
Get rid of the console.log() statement. IE < 9 chokes on it and 9 only works if the console is open.
Try adding an event parameter in your click callback
$('.addtobag').on('click', function(event){
A couple things that might be tolerated in some browsers and not IE are that line 12 is missing a semicolon at the end, and the variable phpbasket is not defined (although if you defined it outside of the closure with 'var phpbasket' then you should be ok. If you debug it in IE 9 or higher, you should be able to see line numbers of errors in the console.
Not a complete answer, but it may point you in the right direction. I was actually about to ask a similar question - I found how to get IE 11 to load the jquery, but it required the user to hit "f12" and then "run activex" because apparently IE considered my code potentially unsafe. But when the user tells the activex to run, it works fine.
I am trying to learn how to use jquery to make touchscreen-friendly dropdown menus, so my code was basic - no css, no doctype, just basic html and js. If anyone else could shed some light on this it would be great.

Categories

Resources