Preventing HTTP REQUEST on javascript DOM update - dom

I am getting re-execution of imported js files upon a hitting a form button which calls a function to insert a DOM element into page ( in simulation to exe of an ajx callback function). The DOM insertion causes a page refresh which re-requests all files from server.
Nothing big on the function call:
var addFashionVideo = function() {
var nodeContainer = document.getElementById('vidList');
var mytitle = document.forms.addVideo.newVidName.value;
var addTextNode = document.createTextNode(mytitle);
var newLI = document.createElement('LI');
newLI.appendChild(addTextNode);
nodeContainer.appendChild(newLI);
return this;
};
TARGET DIV for DOM update code is :
<div id="ajParent" class="aj" style="width:325px;background-color:blue;color:white;">
<ul id="vidList">
<li>Watch Fashion Paris Video</li>
</ul>
</div>
I place an alert on this page and after the function attempts to insert the new LI
[ oddly the LI appears for a split second then disappears ] a page refresh is triggered
and my alert on the page re-executes.
// Perhaps Maybe I have a browser issue on this computer or I am just to new of a scripter
// to not see the problem...any comment appreciated.

The minute you hit submit on a form, the page will reload since you have made a GET request with the form. In order to stop the form from submitting you would have to make it return false on submit. e.g.
document.getElementById('formname').onsubmit = function {
return false;
};
You would have to make sure to disable form submission so the page doesn't reload, then you could run your ajax request on submission and do what you must on success in the ajax function.
I really doubt your dom insertion is causing the reload.

Related

Squarespace + PayPal - custom form with fee added issue with displaying total

I'm helping with a Squarespace site and it has a custom form added in code on a particular page. The form collects the payer's info, then can enter any amount in the "Total to charge" field, then it is supposed to display the 2.7% fee. However, I can ONLY get the fee to display if I refresh the page (chrome, safari, either one). Click here to see the page...let me know
here is a snippet of code:
<script>
$(document).ready(function () {
var $amount = $('input[name="amount_1"]');
var $fee = $("#fee");
var $total = $("#total");
var $amount_2 = $("input[name='amount_2']");
var processing_fee = .027;
var isCurrency = function (inval) {
var regex = /^[1-9]\d*(((,\d{3}){1})?(\.\d{0,2})?)$/;
if (regex.test(inval)) {
return true;
}
return false;
};
$amount.on('input propertychange', function () {
if (isCurrency($amount.val())) {
var fee = ($amount.val() * processing_fee).toFixed(2);
var total = (Number(fee) + Number($amount.val())).toFixed(2);
$fee.text('$' + fee);
$amount_2.val(fee);
$total.text('$' + total);
}
});
$amount.on('blur', function () {
$amount.val($amount.val().replace("$", ""));
$amount.val(Number($amount.val()).toFixed(2));
if (!isCurrency($amount.val())) {
$amount.val("");
}
});
$("#paymentform").validate({
submitHandler: function (form) {
form.submit();
}
});
});
</script>
When a custom script only runs on page refresh, the cause is likely to be Squarespace's AJAX loading:
Occasionally, Ajax may conflict with embedded custom code or anchor
links. Ajax can also interfere with site analytics, logging hits on
the first page only.
Disabling AJAX is often a simple solution:
You can disable Ajax in the Style Editor, with some exceptions:
Ajax can't be disabled in Skye, Foundry, or Tudor.
Ajax can't be disabled on the blog landing page for Farro and Haute. If you uncheck Enable Ajax Loading in these templates, they
will still use Ajax to load the Blog Page.
To enable or disable Ajax:
In the Home Menu, click Design, and then click Style Editor.
Scroll down to Site: Loading.
Check or uncheck Enable Ajax Loading.
If you do not want to disable AJAX, then see "Option 2" here for how to write your code so that it will work on initial page load and on AJAX page loads.

Register new event listeners in Polymer 1.0 after initial page load

In my Polymer 1.0 app, I have an on-tap function which dynamically adds another button into the page based on a few parameters in the form. The problem is that after adding the element and its event listener to the page, the new button won't actually fire the on-tap event.
JSFiddle for testing: https://jsfiddle.net/dme6tb7z/
index.html
<template is="dom-bind" id="app">
<div id="output"></div>
<paper-button id="myButton" on-tap="_addButton">Add Button</paper-button>
</template>
<script src="app.js"></script>
Here is where I create the new button and give it a listener in JS. Is there some kind of extra step I need to take so that Polymer can "see" the new on-tap event listener?
app.js
app._addButton = function(e) {
var el = document.createElement('paper-button');
el.innerHTML = "New Button";
el.id = "newbutton";
el.addEventListener('on-tap', '_testEvent');
this.$.output.appendChild(el);
// I also tried adding the event listener after appending
// the element to the page, like so...
// this.$.newButton.addEventListener('on-tap', '_testEvent');
};
app._testEvent = function(e) {
console.log(e);
};
EDIT
I'm thinking maybe I need to use something like Polymer.dom(parent).appendChild(node) to keep the two DOMs in sync. I did this in my app.js like so, but the event still doesn't fire.
app.js scope
(function(document) {
'use strict';
var app = document.querySelector('#app');
...
app._addButton = function(e) {
var el = document.createElement('paper-button');
el.innerHTML = "New Button";
el.id = "newbutton";
el.addEventListener('on-tap', '_testEvent');
var parentNode = document.getElementById('output');
Polymer.dom(parentNode).appendChild(el);
};
...
})(document);
Surely, there must be some way to add event listeners after initial page load? I've done this same thing countless times in other setups, but there's something weird going on with Polymer... I understand there are two DOMs to update, but I'm using the Polymer.dom method, so what in the world is preventing this from happening?
More Info
I noticed that after appending the new button to the page, I can successfully run this:
document.getElementById('newbutton').innerHTML = 'Hello World';
whereas this:
document.getElementById('newbutton').addEventListener('on-tap', '_testEvent');
has no effect (and no errors). Isn't that bizarre? Is there some sort of reinvented registration process in Polymer to add event listeners?
Okay, I think I figured it out.
First of all, on-tap in this context should be tap.
Second, the function name from JS should be formatted like this: this.functionName, or app.functionName if your template has an id of "app" and app is defined as var app = document.querySelector('#app');
All together, it looks like this:
var newElement = document.getElementById('newbutton');
newElement.addEventListener('tap', this._testEvent );
This doesn't work in the JS Fiddle for some reason, but does work in a real Polymer environment.

Issue with document.ready function in jQuery

I am having one issue with document.ready jQuery function.
On load the document.ready function is working fine. When I click on the button or href link, I want to reconnect with the document.ready function where I have set of code in JavaScript file.
Here is the actual scenario. Please find below sample JS code:
$(document).ready(function() {
var title = "This is your title";
var shortText = jQuery.trim(title).substring(0, 10).split(" ").slice(0, -1).join(" ") + "...";
alert(shortText );
});
After clicking submit button i am adding the input fields data in the below table row. In which description texts are also added in one of table row columns. If description field has more than 100 character, I am pushing the above mentioned JavaScript code from external .JS file. How can i refresh the Java script function without refreshing the page? Anyone have idea?
Please share your opinion.
Create a function, that you can call both in document.ready, and also anywhere else, such as a buttons click event:
function myfunc(){
var title = "This is your title";
var shortText = jQuery.trim(title).substring(0, 10).split(" ").slice(0, -1).join(" ") + "...";
alert(shortText );
}
$(document).ready(function() {
//call when document is ready
myfunc();
//call again when button is clicked
$('#button').click(myfunc());
});

jquery / ajax form not passing button data

I thought the HTML spec stated that buttons click in a form pass their value, and button "not clicked" did not get passed. Like check boxes... I always check for the button value and sometimes I'll do different processing depending on which button was used to submit..
I have started using AJAX (specifically jquery) to submit my form data - but the button data is NEVER passed - is there something I'm missing? is there soemthing I can do to pass that data?
simple code might look like this
<form id="frmPost" method="post" action="page.php" class="bbForm" >
<input type="text" name="heading" id="heading" />
<input type="submit" name="btnA" value="Process It!" />
<input type="submit" name="btnB" value="Re-rout it somewhere Else!" />
</form>
<script>
$( function() { //once the doc has loaded
//handle the forms
$( '.bbForm' ).live( 'submit', function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $( this ).serialize(), // get the form data
type: $( this ).attr( 'method' ), // GET or POST
url: $( this ).attr( 'action' ), // the file to call
success: function( response ) { // on success..
$('#ui-tabs-1').html( response );
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
On the processing page - ONLY the "heading" field appears, neither the btnA or btnB regardless of whichever is clicked...
if it can't be 'fixed' can someone explain why the Ajax call doesn't follow "standard" form behavior?
thx
I found this to be an interesting issue so I figured I would do a bit of digging into the jquery source code and api documentation.
My findings:
Your issue has nothing to do with an ajax call and everything to do with the $.serialize() function. It simply is not coded to return <input type="submit"> or even <button type="submit"> I tried both. There is a regex expression that is run against the set of elements in the form to be serialized and it arbitrarily excludes the submit button unfortunately.
jQuery source code (I modified for debugging purposes but everything is still semantically intact):
serialize: function() {
var data = jQuery.param( this.serializeArray() );
return data;
},
serializeArray: function() {
var elementMap = this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
});
var filtered = elementMap.filter(function(){
var regexTest1= rselectTextarea.test( this.nodeName );
var regexTest2 = rinput.test( this.type ); //input submit will fail here thus never serialized as part of the form
var output = this.name && !this.disabled &&
( this.checked || regexTest2|| regexTest2);
return output;
});
var output = filtered.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
return output;
}
Now examining the jQuery documentation, you meet all the requirements for it to behave as expected (http://api.jquery.com/serialize/):
Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
the "successful controls link branches out to the W3 spec and you definitely nailed the expected behavior on the spec.
Short lame answer: I think it is teh broken! Report for bug fix!!!
I've run into a rather unusual issue with this. I'm working on a project and have two separate php pages where one has html on the page separate from the php code and one is echoing html from inside php code. When I use the .serialize on the one that has the separate html code it works correctly. It sends my submit button value in its ajax call to another php page. But in the one with the html echoed from the php script I try to do the same thing and get completely different results. It will send all of the other info in the form but not the value of the submit button. All I need it to do is send whether or not I pushed "Delete" or "Update". I'm not asking for help (violating the rules of asking for help on another persons post) but I thought this info might be helpful in figuring out where the break down is occurring. I'll be looking for a solution and will post back here if I figure anything out.

jQuery - Refresh Contents of a DIV

I have a form in a jQuery popup on a webpage. The jQuery popup is a div named .vote-form and the form inside it has the name "#form".
When the form is submitted, the content inside the jQuery popup changes to a success message. I need to make it so that when the jQuery popup is closed, the success message is removed and the form is refreshed back to the original form, so that when the jQuery popup is opened again, the form is showing again and NOT the success message.
My feeble attempt to get this result involved refreshing the ENTIRE page when the jQuery popup is closed. This PARTLY has the desired result, but when the page is refreshed, most browsers get a popup asking if the user wants to resubmit the form content. I need to avoid this.
This was my code handling the closing of the .vote-form:
$('.vote-form-close').click(function(event) {
event.stopPropagation();
$(".vote-form").fadeOut("normal");
$("#the-lights").fadeTo("slow",0);
$("#the-lights").css({'display' : 'none'});
window.location.reload();
});
I suspect that its possible to refresh ONLY the div, and not the entire page, but I do not know how to accomplish it.
Can someone assist me?
EDIT: Based on one of the answers below, I modified my code. I also wanted to show the code used to open the form up too:
$('.vote').click(function() {
$(this).parent().find(".vote-form").fadeIn("normal");
$("#the-lights").css({'display' : 'block'});
$("#the-lights").fadeTo("slow",0.7);
});
$('.vote-form-close').click(function(event) {
event.stopPropagation();
$(".vote-form").fadeOut("normal");
$("#the-lights").fadeTo("slow",0);
$("#the-lights").css({'display' : 'none'});
$(".vote-form").load(window.location.href + " .vote-form-container");
});
Here is the problem - I have 3 forms on the page. When "vote-form-container" is loaded, its loading ALL THREE forms into the .vote-form box - how do I modify the code to only load the .vote-form-container that is part of the specific .vote-form - I suspect I have to use $(this) but I tried modifying the code to this and it didnt work:
$(".vote-form")(this).load(window.location.href + " .vote-form-container");
I am thinking I did it wrong.
EDIT 2: Now the "Close" button dosen't work after the form is reloaded the first time:
$('.vote').click(function() {
$(this).parent().find(".vote-form").fadeIn("normal");
$("#the-lights").css({'display' : 'block'});
$("#the-lights").fadeTo("slow",0.7);
});
$('.vote-form-close').click(function(event) {
event.stopPropagation();
$(".vote-form").fadeOut("normal");
$("#the-lights").fadeTo("slow",0);
$("#the-lights").css({'display' : 'none'});
var current_form = $(this).closest('.vote-form'),
index = $('.vote-form').index(current_form)
current_form.load(window.location.href + " .vote-form-container:eq(" + index + ")");
});
Don't reload the page but redirect your user:
window.location.href = window.location.href.toString()
Or load the new form with ajax:
$(".vote-form").load(window.location.href + " .vote-form");
For more information on the ajax approach see api.jquery.com/load/#loading-page-fragments
Update:
Using jQuery the index function you are able to replace only the current form.
// I asume your button is in the form
var current_form = $(this).closest('.vote-form'),
index = $('.vote-form').index(current_form)
current_form.load(window.location.href + " .vote-form:eq(" + index + ")");
... I need to make it so that when the jQuery popup is closed, the success message is removed and the form is refreshed back to the original form...
So, if I well understood:
$('.vote-form-close').click(function(event) {
event.stopPropagation();
var vf = $(".vote-form");
/* fadeout and remove inner content of the popup */
vf.fadeOut("normal", function() { vf.empty(); });
/* reset the form */
document.getElementById('form').reset();
...
});