Ajax loaded page refreshing when clicking on button - javascript

I load a page in a div through AJAX. This works great.
On this ajax loaded page there are some buttons (generally created with javascript). When I click on one of these buttons the page refreshes. Weird thing is; no where I stated the page SHOULD refresh. Afterall; that's why I use ajax.
This is the javascript that's executed on the AJAX loaded page:
function buttonClicked(id){
var page = id;
photoPage = page*10;
if(cur_button < id)
{
minCount += 10;
maxCount += 10;
}
else
{
minCount -= 10;
maxCount -= 10;
}
cur_button = id;
jQuery("#imagesDiv").html("");
$( "#imagesDiv" ).append( " <br/>");
executePage();
}
function createButtons() {
var i = 1;
var button = "";
while(i <= photoCount)
{
var button = document.createElement("BUTTON");
var buttonName = document.createTextNode(i);
button.appendChild(buttonName);
button.id = i;
jQuery(button).bind('click', { id: i}, function(event) {
var data = event.data;
buttonClicked(data.id);
});
imagesDivJS.appendChild(button);
i++;
}
}
function executePage()
{
setImagesDivID();
createButtons();
$( ids ).append( " <br/>");
populateDiv();
}
function populateDiv() {
for(var i = minCount;i < maxCount; i++)
{
if(i < total_count)
{
create_image("../"+photos[i],photoAlts[i]);
$("#"+ids).append( "<p style=\"display:inline; padding-left:10px;\">" + photoTags[i] + "</p><br/>" );
}
}
}
Help will be appreciated. I've been breaking my neck around this thing!

The button is refreshing the page because it is a submit button. You need to add an attribute of type="button" to the button. For example:
function createButtons() {
var i = 1;
var button = "";
while(i <= photoCount)
{
var button = document.createElement("BUTTON");
var buttonName = document.createTextNode(i);
button.appendChild(buttonName);
button.id = i;
// Add type="button"
button.setAttribute("type", "button");
jQuery(button).bind('click', { id: i}, function(event) {
var data = event.data;
buttonClicked(data.id);
});
imagesDivJS.appendChild(button);
i++;
}
}

Related

How to use local storage on append child

<button id="showlinks" onclick="myFunction">show</button>
<div id="buttonlinks"></div>
function myFunction() {
var button = document.createElement("button");
document.getElementById("buttonlinks").appendChild(button);
}
I used This Code to create buttons on clicking a button. when clicking the show button the buttons appear but after refresh they are gone.
can I store the buttons with localStorage?
You can store the information about your buttons in the localStorage whenever you create a button, and add an eventListener to window.onload to read the buttons from localStorage and append it to the page when page has loaded, in the below exmpale to keep it simple, I just store the length of buttons.
<button id="showlinks" onclick="myFunction">show</button> <div id="buttonlinks"></div>
js:
let buttonsLength = 0;
document.getElementById('showlinks').addEventListener('click', function () {
createButton();
buttonsLength++;
localStorage.setItem('buttonsLength', buttonsLength)
});
function createButton() {
var button = document.createElement('button');
button.innerHTML = 'click me';
document.getElementById('buttonlinks').appendChild(button);
}
window.addEventListener('load', (event) => {
buttonsLength = Number(localStorage.getItem('buttonsLength')) || 0;
for (let i = 0; i < buttonsLength; i++) {
createButton();
}
});
const showlinks = document.getElementById('showlinks')
showlinks.addEventListener("click", function () {
localStorage.setItem("showClicked", true)
displayButtonInDom()
})
function displayButtonInDom() {
const showClicked = localStorage.getItem("showClicked")
if (showClicked) {
const button = document.createElement("button");
button.innerText = "click me"
document.getElementById("buttonlinks").appendChild(button);
}
}
displayButtonInDom()
<button id="showlinks">show</button>
<div id="buttonlinks"></div>
Foreache button created you have to add the button information to the localstorage. And on page load you execute an init function that rebuild all button created from the localstorage
<button id="showlinks" onclick="createButton('')">show</button>
<div id="buttonlinks"></div>
<script>
function Initbutton() {
//on load check if the button has been already add using the localStorage
var buttons = getButtonInformationFromLocalStorage();
if(buttons != null){
buttons.forEach(function(btnName){
createButton(btnName);
})
}
}
// fo the purpose of having different button name
// i have picket this function here https://www.codegrepper.com/code-examples/javascript/find+random+name+javascript
function getRandomString(length) {
var randomChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var result = '';
for ( var i = 0; i < length; i++ ) {
result += randomChars.charAt(Math.floor(Math.random() * randomChars.length));
}
return result;
}
function createButton(btnName){
if(btnName == undefined || btnName == ""){
btnName = "button" + getRandomString(10);
updateButtonInformationToLocalStorage(btnName);
}
var button = document.createElement("button");
button.innerHTML = btnName;
document.getElementById("buttonlinks").appendChild(button);
}
function updateButtonInformationToLocalStorage(name){
var lstrg = localStorage.getItem("alreadyaddbuttontobuttonlinks");
if(lstrg == null){
localStorage.setItem("alreadyaddbuttontobuttonlinks", name);
return name;
}else{
var nLstrg = lstrg + "|" + name;
localStorage.setItem("alreadyaddbuttontobuttonlinks", nLstrg);
return nLstrg;
}
}
function getButtonInformationFromLocalStorage(){
var lstrg = localStorage.getItem("alreadyaddbuttontobuttonlinks");
if(lstrg == null){
return null;
}else{
return lstrg.split("|");
}
}
window.onload = Initbutton();
</script>

how do i add functionality to each of the buttons?

The first part of the code is working correctly, but now that each button appears, how do i add functionality to each of them? currently the only button which does something when pressed is always the last one, the rest do nothing.
Change it to
{
var output = "";
var data = JSON.parse(e.target.responseText);
for(var i=0; i<data.length; i++)
{
output = data[i].title + ' ';
var p = document.createElement("p");
var div = document.getElementById("response");
var textNode = document.createTextNode(output);
p.appendChild(textNode);
var button = document.createElement("button");
button.innerHTML = "Download";
p.appendChild(button);
div.appendChild(p);
button.addEventListener ("click", () =>
{
alert("Test");
});
}
}
You are adding the below code out side the for loop
button.addEventListener ("click", () =>
{
alert("Test");
} );
Keep the above code inside the for loop. So that for each button the event listener will be added.
Another way to approach this would be to add the callback function to the onclick variable of the elements prototype:
function doStuff() {
var output = "";
var data = JSON.parse(e.target.responseText);
for (var i = 0; i < data.length; i++) {
output = data[i].title + ' ';
var p = document.createElement("p");
var div = document.getElementById("response");
var textNode = document.createTextNode(output);
p.appendChild(textNode);
var button = document.createElement("button");
button.innerHTML = "Download";
// Adds the callback function here
button.onclick = () => {
// fill in your arrow function here...
alert("Test");
};
p.appendChild(button);
div.appendChild(p);
};
}
doStuff();
Here is a jsFiddle
You should use event delegation for dynamically added elements
// sample data
var data = [{
title: 'one'
}, {
title: 'two'
},{
title: 'three'
}];
var output = "";
for (var i = 0; i < data.length; i++) {
var output = data[i].title + " ";
var p = document.createElement("p");
var div = document.getElementById("response");
var textNode = document.createTextNode(output);
p.appendChild(textNode);
var button = document.createElement("button");
// added output to button text for identification
button.innerHTML = output + " Download";
p.appendChild(button);
div.appendChild(p);
}
// Get the parent element, add a click listener
document.getElementById("response").addEventListener("click", function(e) {
// e.target is the clicked element!
// If it was a button
if (e.target && e.target.nodeName == "BUTTON") {
// Button found! Output the identifying data!
// do other work on click
document.getElementById("display").innerHTML = e.target.innerHTML + " Clicked";
}
});
<div id="response"></div>
<div id="display">Display</div>

Javascript-created Form sending empty values

I am creating a HTML table and I want it to be editable. so I created javascript like this:
<script>
var buttons = document.getElementsByClassName("clicker");
var buttonclicked = function(e){
if(e.target.textContent == "Edit")
{
e.target.textContent = "Cancel";
var id = e.target.id;
var table = document.getElementById("tr"+id);
var editable_elements = document.querySelectorAll("[contenteditable=false]");
var sub = document.getElementById("sub"+id);
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"edit.php");
table.appendChild(f);
var j = document.createElement("input");
j.setAttribute("type", "text");
j.setAttribute("name", "subject");
j.setAttribute("value", sub.textContent);
j.setAttribute("placeholder", sub.textContent);
j.setAttribute("disabled", true);
j.setAttribute("style", "width: 150px");
j.textContent = sub.textContent;
sub.innerHTML = "";
f.appendChild(j);
sub.appendChild(j);
for(var k = (id*6); k < (id*6)+6; k++){
var l = k;
var index = k -(k*id) + 1;
l = document.createElement("input");
l.setAttribute('type',"number");
l.setAttribute("style", "width: 75px");
l.setAttribute("step", "0.01");
if(index <= 4){
l.setAttribute('name',"g"+index);
l.setAttribute('placeholder',"G"+index);
l.setAttribute("value", editable_elements[k].textContent);
}
else if(index == 5){
l.setAttribute('name',"creditos");
l.setAttribute('placeholder',"credits");
l.setAttribute("value", editable_elements[k].textContent);
}
else if(index == 6){
l.setAttribute('name',"criteria");
l.setAttribute('placeholder',"criteria");
l.setAttribute("value", editable_elements[k].textContent);
}
editable_elements[k].innerHTML = "";
f.appendChild(l);
editable_elements[k].appendChild(l);}
var s = document.createElement("button");
s.textContent = "Save";
s.setAttribute('type',"submit");
s.setAttribute('value',"update");
s.setAttribute("id", id);
s.setAttribute("name", "action");
var clickbutton = document.getElementById("save"+id);
f.appendChild(s);
}
else //save button has been clicked
{
//nothing
}
};
for(var j = 0; j < buttons.length; j++)
{
buttons[j].addEventListener('click', buttonclicked);
}
</script>
This creates a lot of input forms in the table cells (check the image: http://imgur.com/z5DRRZz) and a submit button and try to send it to my PHP file (edit.php), all seems to work well, but when it submits to the PHP file, it submits an empty string in the place of "Subject". I dont know why. I know that bracause as soon as I press "save" button it tells me I have accessed this appologize function:
else if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if($_POST['action'] == ["update"])
{
//validate submission
if(empty($_POST["subject"]))
apologize("You must provide what subject to change");
...
}
...
}

addEventListener does not work on dynamically created button

I'm creating 3 buttons dynamically. Now I need to add an onclick event. How can I make the onclick work?
var btns='';
var category = ["fur_", "fts_", "fas_"];
for(i = 1; i < category.length; i++){
btns +='<button type="button" class='+category[i]+' id= "myBtn'+i+'">Button</button>';
}
document.getElementById('div').innerHTML = btns;
var button = document.getElementById('myBtn1');
button.addEventListener('click', function () {
alert('Clicked');
}, false);
You can get all the button elements and add the click event handler using a loop
var btns = '';
var category = ["fur_", "fts_", "fas_"];
for (i = 1; i < category.length; i++) {
btns += '<button type="button" class=' + category[i] + ' id= "myBtn' + i + '">.....</button>';
}
var div = document.getElementById('div');
div.innerHTML = btns;
var handler = function () {
alert('Clicked');
};
var buttons = div.querySelectorAll('button');
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', handler, false);
}
Demo: Fiddle
Another approach is to create a button element in the loop
var div = document.getElementById('div');
var btn;
var category = ["fur_", "fts_", "fas_"];
var handler = function () {
alert('Clicked');
};
for (var i = 1; i < category.length; i++) {
btn = document.createElement('button');
btn.cassName = category[i];
btn.cassName = 'myBtn' + i;
btn.innerHTML = '....';
btn.addEventListener('click', handler, false);
div.appendChild(btn);
}
Demo: Fiddle

Passing an argument to a event listener from dynamically created buttons

I'm dynamically creating 3 buttons. How can I pass an argument tohandlerX?
So basically I want the values in the category Array to be passed on to the handlerX eventListener.
Example:
When myBtn1 is clicked, I want the alert to be "fur_",
When myBtn3 is clicked, I want the alert to be "fas_"
var btns = '';
var category = ["fur_", "fts_", "fas_"];
for (i = 1; i < category.length; i++) {
btns += '<button type="button" class=' + category[i] + ' id= "myBtn' + i + '">.....</button>';
}
var div = document.getElementById('div');
div.innerHTML = btns;
var handlerX = function () {
alert('Clicked'); //get value from the 'category' Array
};
var buttons = div.querySelectorAll('button');
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', handlerX, false);
}
The answers given so far are good and should solve your problem. Just thought I'd add this one because I think it's a solution more in line with what you were asking for: Make your handlerX return a function like so:
var handlerX = function (param) {
return function() {alert(param);};
};
var buttons = div.querySelectorAll('button');
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', handlerX(category[i]), false);
}
Edit: Here's a Fiddle
If you're willing to extract it from the class attribute, then:
var handlerX = function () {
alert(this.getAttribute('class'));
};
Or you better associate it with some data- attribute. For example:
for (i = 1; i < category.length; i++) {
btns += '<button type="button" data-category="' + category[i] + '" class=' + category[i] + ' id= "myBtn' + i + '">.....</button>';
}
Then:
var handlerX = function () {
alert(this.getAttribute('data-category'));
};
See Fiddle
EDIT:
then i would reccomend adding an attibute: data-category="fur_" for example, and access that from your event handler:
this.getAttribute('data-category')
in hadlerX there is a "this" that is the element that was clicked. You can access its getAttribute("class") to get the class EDIT:this, not self
var fragment = document.createDocumentFragment(),
categories = ["fur_", "fts_", "fas_"],
btn;
function onClickBtn() {
alert(this.getAttribute("data-category"));
}
for (var i = 0; i < categories.length; i++) {
btn = document.createElement("button");
btn.id = "myBtn" + string(i);
btn.setAttribute("data-category", category[i]);
btn.addEventListener("click", onClickBtn);
fragment.appendChild(btn);
}
var div = document.getElementById('div');
div.appendChild(fragment);

Categories