Creating a scalable modify button on my website - javascript

I'm looking to create a button for my website which allows the user to edit information on both the website and the database. To put it into context, I sell cars and when I would like to make changes to a vehicle's details, I would like it to update the information on the website, not just the database.
The function below represents what happens when the update button is clicked - I have narrowed it to just the car colour. The content piece represents the form which appears when the modify button is clicked. The cars.colour represents the colour of the car as per the DB. When the update button is clicked, this value will appear in the text field. The #carList is displayed on a different HTML page.
Catalogue.js:
function update(key){
database.ref('car').once('value', function(snapshot){
if(snapshot.exists()){
snapshot.forEach(function(data){
var cars = data.val();
console.log(cars);
if(data.key === key){
var content = '';
content += '
<form id="car_update">
<div class="container">
<h1>Vehicle Details</h1>
<div class="row">
<input id="colour"
type="colour" placeholder="Colour..."
value="'**+cars.colour+**'" style="width: 150px;"/>
</div>
<button class="test"
onclick="updateCar(\''**+key+**'\')">Submit</button>'
}
$('#carList').append(content);
})
}
}
}
Item1.html:
<label>Colour: </label></br>
<script type="text/javascript">
document.getElementById('colour').innerHTML;
</script>

I not sure I quite understand, it sounds like you want to make a call and update the database and you also want to the page display the user is seeing to update and you already have the call to the database working.
It looks like you have an inline javascript method in the html which is only called when the page is rendered by the browser:
<label>Colour: </label></br>
<script type="text/javascript">
document.getElementById('colour').innerHTML;
</script>
If you want to also update the page from user input, I think you need to have the page refresh after the user submits so the html is called again from the server with the latest content that was updated in the database, or change the html to be setup in a way that it can be updated from the javascript, something like:
<label>Colour: </label></br>
<span id="colorLabel">
and then in the javascript, after cars.colour has the updated value, have something like:
document.getElementById('colorLabel').innerHTML = cars.colour;

Related

How to run a PHP function due to a button click (with button 'data' passed)?

I know that AJAX could solve my issue. I need help how I can solve it in my specific case however. I manage some sortiment items on a page, they get displayed with a PHP script (checks the database, if the item is available, and if so, it gets displayed). I now want an admin page where I can kind of "toggle" via a sortiment table to display or not display an item (set it as available or non available.
What I need is: if the button is clicked, I would like to start a php-skript. There should be an value passed to that script (the button id). The script itself should open an SQL connection, change a DB value based on the passed ID of the button. Then close the connection. Optionally also refresh the table (or one value) from where the button was clicked.
Can someone help me, at least telling me what I need to do this? (jQuery, Ajax?). The passing of the ID would be important, else I'd need to do function for every button.
An table entry looks like this:
<tr>
<td>Himbeerhonig</td>
<td id="himbeerhonig">Ja</td>
<td><button type="button" id="himbeerhonig" onclick="function()">press me to execute function</button></td>
</tr>```
(possible PHP pseudocode)
open SQL connection
look for database entry based on the passed ID
change the value of the found entry (!currentValue)
close SQL connection
*optionally*
refresh the <td id="himbeerhonig"> with the updated value.
I appreciate any help very much! Just need some hints as to how to do it properly. It's just a concept that currenty is hard to grasp for me so far.
1- If you want to do this with ajax (without browser refresh), you should create a separate php file, and put your php scripts in there. it's called api (api has special format for output, so search create api in php if you want to do this). then on javascript, you should do an ajax call to that php address, on onclick event of button. and then javascript will return data and you can create elements based on that data.
2- however you can do this without ajax(it will refresh browser). just write your inline phps as you wrote :
<html>
<!-- your html codes-->
<?php
if($_GET['buttonClicked']){
//put your php codes here to run when button clicked
?>
<!-- you can even put html here, even it can be on php loop. -->
<?
}
<!-- your html codes-->
<!-- turn your button to a form-->
<form action="/" method="get">
<input name="buttonClicked" hidden value='1'>
<input type="submit" value="Submit">
</form>
</html>
it's as easy as this. when button clicked, a get request will send to current page, and php will handle it, for example it will render additional html elements to the page.

store 2 websites in 1 file and dynamically change between them

so this is a very vague question but say I had a single .html file and I wanted to store essentially 2 websites in the one file and swap to the 2nd page when a condition became true on the first page(preferably a onclick javascript event) kind of like an if statement(if condition A becomes true on page one: show page 2 else: continue to show page 1) would this be possible in just javascript or would I need the aid of other programming languages and what would be the most optimum way of going about this? I would want the data entered in an input feild on page 1 also available on page 2.
sorry for vague question and horrible formatting, this is my first ever question.
Joel, I don't have enough reputation to comment and so I must type an answer.
Local storage allows you to store a value (page number to display) within the user's local browser memory. This value can be tested for existence (useful for true/false conditions) and can be read (for meaningful values).
All you need to do is bind the creation of a simple local storage object (the page number to display). Bind the code to create the storage object to whichever event you want (such as a button click).
localStorage.setItem('entryPage', '2');
You will also need some code to read within the HTML file to decide what to display (via scroll, hidden and displayed DIV elements or whatever technique you are using).
if(localStorage.getItem('entryPage')) {
//show page two code
}
Check here for a full tutorial set:
https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
Below is a chrome-tested one-page solution just demonstrating the concept of the local storage part. You'll always be within the same HTML file, but load will show content one until you click the button and set local storage to display page 2, then any future load will be page two until you clear local storage.
<!DOCTYPE html>
<html>
<body>
<div id="main-container">
<div id="content-one" style="display:block;">
<p>This is page one content</p>
<button id="showTwo">Show Page 2</button>
</div>
<div id="content-two" style="display:none">
<p>this is content for page 2</div>
</div>
</div>
<script>
//this function actually swaps display
function swapper(){
document.getElementById('content-one').style.display = 'none';
document.getElementById('content-two').style.display = 'block';
}
//if the value exists in storage, swap them
if(localStorage.getItem('entryPage')) {
swapper();
}
//when button clicked, swap them and store value
var btn = document.getElementById("showTwo");
btn.addEventListener("click", function(){swapper();localStorage.setItem('entryPage', '2');}, false);
</script>
</body>
</html>
To clear local storage on Chrome, see LOCAL AND SESSION section here:
https://developer.chrome.com/devtools/docs/resource-panel#local-and-session-storage
And below is a version including a text-box which simply used the value of the local storage object to hold the data you wish to carry to content page 2. (Remember, if you have tested the first example above you must clear local storage to use this example below because otherwise it will never show you the first content pane).
<!DOCTYPE html>
<html>
<body>
<div id="main-container">
<div id="content-one" style="display:block;">
<p>This is page one content</p>
<input type="text" id="theInput"></input>
<button id="showTwo">Show Page 2</button>
</div>
<div id="content-two" style="display:none">
<p>this is content for page 2</div>
<p id="theOutput"></p>
</div>
</div>
<script>
//this function actually swaps display and shows the value from page 1 textbox
function swapper(theValue){
document.getElementById('content-one').style.display = 'none';
document.getElementById('content-two').style.display = 'block';
document.getElementById('theOutput').innerText = theValue;
}
//if the value exists in storage, swap them and pass on the value of textbox
if(localStorage.getItem('entryPage')) {
swapper(localStorage.getItem('entryPage'));
}
//when button clicked, swap them and store value
var btn = document.getElementById("showTwo");
btn.addEventListener("click", function(){
var theData = document.getElementById("theInput").value;
swapper();
localStorage.setItem('entryPage', theData);
}, false);
</script>
</body>
</html>

Updating DOM elements using jQuery

I'm looking for a way to update the webpage I'm working on to act as a report for several different people to pass back and forth. I'm using forms to take in several pieces of data and am wondering how I can make it so that it just immediately adds the content to the divs under the right heading. I'm currently using jquery and append and it looks like it adds the desired input and then immediately removes it. I tried using .live as well and it did not show up at all. Is there a way to make form inputs post to the page without submitting to another page?
Here is my code so far, testing just the element that will be the heading for the issue:
<div class="IssueDiv">
</div>
<form id="newIssue">
<fieldset>
<legend>Add a new important issue:</legend>
<input type="text" id="issue" placeholder="Issue Summary...">
<input type="text" id="issue-client" placeholder="Client...">
<input class="ticket" type="text" id="issueParent" placeholder="Parent ticket..."><br>
<textarea placeholder="Issue details..."></textarea><br>
<button id="addIssue">Add Issue</button>
</fieldset>
</form>
And the jquery:
<script>
$(function(){
$("#addIssue").click(function() {
var $issue = $("#issue").val();
var $issueSum = $("<h3></h3>").text($issue);
$(".IssueDiv").append($issueSum);
});
});
</script>
edit: I'm looking into using AJAX but I'm not sure how to make it so that all of the input data will persist. I am basically looking to make a webpage-style-report that will allow myself and my team to update the entries on the report and they will stay on the report until we are able to take them off by removing a div that encapsulates the individual issue.
I would also like to be able to format the individual pieces here separately, so, for instance, I could add a check-box that says the issue is urgent and format the heading of those to be red. What is the easiest way to have data that persists, can be added into new (div/h/p) elements, and is shown on the main webpage, while also allowing me to update formatting?
Your code appears to add the text and then immediately remove it because your form gets posted and the page reloads, effectively resetting the page to its initial state.
If you just want to add the text to the page without posting the form or executing any server-side processing, you can prevent the form from posting using jQuery's preventDefault(). Note that I have created a submit listener on the form itself, rather than a click listener on the submit button.
$("#newIssue").on('submit', function(e) {
e.preventDefault();
...
});
$(function () {
$("#newIssue").on('submit',function (e) {
e.preventDefault();
var $issue = $("#issue").val();
var $issueSum = $("<h3></h3>").text($issue);
$(".IssueDiv").append($issueSum);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="IssueDiv"></div>
<form id="newIssue">
<fieldset>
<legend>Add a new important issue:</legend>
<input type="text" id="issue" placeholder="Issue Summary...">
<input type="text" id="issue-client" placeholder="Client...">
<input class="ticket" type="text" id="issueParent" placeholder="Parent ticket...">
<br>
<textarea placeholder="Issue details..."></textarea>
<br>
<button id="addIssue">Add Issue</button>
</fieldset>
</form>
However, keep in mind that if you're using this to share reports between computers, this will not work. This is only updating the DOM in the current browser and is not doing any data storage or retrieval. If you need the reports to update online, consider using AJAX to post your data to a server-side script without refreshing the page. Then include some sort of timer that refreshes the content (also using AJAX) on a schedule (e.g. every 10 seconds).

Dynamically and Permanently Adding an Element to Your Page - Javascript/jQuery

I'm working on a website project from scratch. The content section of the main page has a form and a div of class "blog". When the user is logged in on the admin account, the form shows up. This allows you to pick a title and content to post in the blog. The current code works well, except for the fact that the posts are removed when the page is refreshed. How I can permanently add this to the page?
Here's my code:
<script type="text/javascript">
function addtext() {
var title = document.blogform.title.value;
var content = document.blogform.content.value;
var $blogTitle = $('<div class="blogtitle">' + title + '</div>');
var $blogContent = $('<div class="blogbody">' + content + '</div>');
$('#blog').prepend($blogContent);
$('#blog').prepend($blogTitle);
}
</script>
<h2>Submit New Blog Post</h2>
<div class="blogtitle">Submit a new blog post:</div>
<div class="blogbody">
<form name="blogform">
<fieldset class="fieldsetoffset"><legend>Post</legend>
<div>Title of Post:</div>
<input type="text" name="title">
<div>Content of Post:</div>
<textarea name="content" class="comment" rows="6" cols="88"></textarea>
<hr>
<input type="button" value="Add New Text" onClick="addtext();">
</fieldset>
</form>
</div>
<div id="blog"></div>
You should use a database (or flat-files, but not recommended..) to store those extra parts. On your page, create a database connection (php.net/PDO), fetch any existing records from the database and when the admin stores it you should insert it into your database.
HTML is flat, you can add and delete elements dynamically by altering the DOM but that's only on your screen and nobody elses :)
I assume that this is a static HTML page. Otherwise you would be refreshing from a server-based data source. If you are going to be doing this, then the only other way would be to store the data as client-side cookies.
You can't do this by Javascript or jQuery because they are client side languages.
for this which you want to achieve you have to use a Server Side Language and database
Javascript is client side, meaning when you add content to the page with jQuery it's local to your browser only, not on the server-side (it's not actually changing the website, it's just changing what your browser is rendering).
You will need to either use cookies (there is a great jQuery cookies plugin that's incredibly simple to use) or, preferably, have some kind of server-side script store it in the database and retrieve the values later, i.e. with PHP/mySQL, since cookies are still going to be specific to you rather than anyone who might visit the website. If nothing else you could use PHP to write it to a text/html file on the server that is then displayed later but that's a really ugly solution and a database is really where you should be going here.
I would probably use jQuery's AJAX functions to call a PHP function when addtext() is triggered that passes it the content and title values to write to the database. Then add a bit of php code on the page to check the database for existing posts and display them.

Jquery change <p> text programmatically

EDIT: The solution was to add this to the profile page instead of the gender page.
$('#profile').live( 'pageinit',function(event){
$('p#pTest').text(localStorage.getItem('gender'));
});
I have a paragraph with som text in a listview that I want to change programatically from another page after clikcing save.
EDIT: This is my listview in profile.html. When you click on the item you get to another page where you can save your gender. I want to change the paragraph in this listview to the gender that was changed from the other page.
<ul data-role="listview" >
<li><a href="gender.html">
<img src="images/gender2.jpg" />
<h3>Gender</h3>
<p id="pTest">Male</p>
</a></li> </ul>
The gender html page is just basic stuff with two radio buttons and a save button.
Here is my javascript code(in a seperate file):
$('#gender').live('pageinit', function(event) {
var gender = localStorage.getItem('gender');
var boolMale = true;
if (gender == "female") boolMale = false;
$('#radio-choice-male').attr("checked",boolMale).checkboxradio("refresh");
$('#radio-choice-female').attr("checked",!boolMale).checkboxradio("refresh");
$('#saveGenderButton').click(function() {
if ($('#radio-choice-male').is(':checked'))
localStorage.setItem('gender', "male");
else localStorage.setItem('gender', "female");
$('#pTest').html('test'); //does not work
//$('p#pTest').text('test'); //does not work
//$('#pTest').text('test'); //does not work
$.mobile.changePage("profile.html");
});
});
I have tried this with javascript: $('p#pTest').text('test');
The text does not change however. (I know that the save button works). Is this possible?
Try the following, note that when the user refreshes the page, the value is "Male" again, data should be stored on a database.
$('button').click(function(){
$('#pTest').text('test')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<p id="pTest">Male</p>
<button>change</button>
"saving" is something wholly different from changing paragraph content with jquery.
If you need to save changes you will have to write them to your server somehow (likely form submission along with all the security and input sanitizing that entails). If you have information that is saved on the server then you are no longer changing the content of a paragraph, you are drawing a paragraph with dynamic content (either from a database or a file which your server altered when you did the "saving").
Judging by your question, this is a topic on which you will have to do MUCH more research.
Input page (input.html):
<form action="/saveMyParagraph.php">
<input name="pContent" type="text"></input>
</form>
Saving page (saveMyParagraph.php) and Ouput page (output.php):
Inserting Data Into a MySQL Database using PHP
It seems you have the click event wrapped around a custom event name "pageinit", are you sure you're triggered the event before you click the button?
something like this:
$("#gender").trigger("pageinit");

Categories

Resources