Saving info on a server, and getting it back - php

On my website i take user input from a form, and add it to a query plugin to output on the screen. Its nice to get the users input, but as soon as i refresh the page, all the input is lost and reset. How can i save the user input so that even when the page is refreshed, the data will stay there for good? can u use my code to show me?
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="textualizer.min.js"></script>
</head>
<style type="text/css">
#txtlzr{color:#585856; font-size:50px; width:1200px; height:100px;
margin-left:10%;
margin-top:80px;
font-family:"futura";
position: fixed;
}
</style>
<body>
<div id="txtlzr"></div>
<form action="#" method="post"/>
<fieldset>
<label for="kwote">Comment:</label>
<input class="kwote" type="text" maxlength="40" id="kwote"
placeholder="Enter a something here."/>
<lable for="name">Name:</label>
<input class="name" type="text" maxlength="17" id="name"
placeholder="Enter your name."/>
<input class="post" type="button" value="Add comment"
onclick="add_comment();" />
</fieldset>
</form>
<script language="javascript">
var COMMENTS_FOR_DISPLAY = new Array('Thanks for the help: nick');
// Adds a new comment, name pair to the Array feeding textualizer.
function add_comment() {
// Retrieve values and add them to Array.
var new_comment = $('#kwote').val();
COMMENTS_FOR_DISPLAY.push(new_comment + ': ' + new_name);
// Reset <input> fields.
$('#kwote').val('');
$('#name').val('');
}
$(document).ready(function() {
var txt = $('#txtlzr'); // The container in which to render the list
var options = {
rearrangeDuration: 5, // Time a character takes to reach its position
effect: 'random', // Animation effect the characters use to appear
centered: true // Centers the text relative to its container
}
txt.textualizer(COMMENTS_FOR_DISPLAY); // textualize it!
txt.textualizer('start'); // start
});
</script>
</body>
</html>
</html>
Thanks to chris btw for helping me with the input.

There is a lot to it other than just the code on the page. You have to have a server-side language and write access into a database server, before you can do anything else.
You might take a look at the Flask tutorial or the Django tutorial if you've not picked out a language and platform. Both require that you set up a server, but use SQLite, a file-based database system, so you don't need to deal with figuring out database servers yet.

Related

How to change a text value by requesting a PHP file thanks to AJAX? (Without refreshing the page)

I'm learning AJAX and want to create a really simple web app to use my knowledge in the "real world".
I'm trying to calculte different percentages of a user input value, and make it appears on the webpage, without refreshing, thanks to AJAX.
Here is my HTML form:
<form id="warmupForm" class="form">
<label for="userWorkLoad">Work load (in kgs)</label><br>
<input type="text" name="userWorkLoad" id="userWorkLoad">
<button type="submit">Calculate</button>
</form>
<div id="#output">This is where I want the result to be shown with AJAX</div>
Here is some of my PHP code, for you to get the idea:
# Get the user input (work load in kgs)
if (isset($_POST['userWorkLoad'])) {
$workload = $_POST['userWorkLoad'];
# Avoid JS hacking
$workload = htmlspecialchars($workload);
}
# CALCULATION #
# Calculate 55% of the work load (1st warm up set)
$FirstWarmupSet = ($workload * 0.55);
# Calculate 70% of the work load (2nd warm up set)
$SecondWarmupSet = ($workload * 0.7);
# First Warmup set #
echo "<li>Do 8 reps with " . $FirstWarmupSet . " kgs, then take 1 minute rest.</li>";
echo "<br>";
# Second Warmup set #
echo "<li>Do 5 reps with " . $SecondWarmupSet . " kgs, then take 1 minute rest.</li>";
echo "<br>";
// etc etc...
I'd like the different variables values from PHP to be shown in my "#output" div when the user click on the submit button.
I've tried a lot of different things (AJAX without jQuery, AJAX with jQuery), but didn't manage to get what I want.
I'm sure I'm doing something wrong, but I don't know what. I'm sure my PHP script is working, since I used it without AJAX without any problem.
I would be very grateful if someone could help me on that.
As mentioned above, the easiest way to make an AJAX request for you is probably to try jQuery:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<!-- Add jQuery on your HTML page -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<!-- Add some custom JavaScript file -->
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form id="warmupForm" class="form">
<label for="userWorkLoad">Work load (in kgs)</label><br>
<input type="text" name="userWorkLoad" id="userWorkLoad">
<button id="btn" type="submit">Calculate</button>
</form>
<div id="output">This is where I want the result to be shown with AJAX</div>
</body>
</html>
The script.js content:
$(function() {
// Process a button click
$("#btn").click(function() {
event.preventDefault();
// Get input field
var userWorkLoadInput = $("#userWorkLoad");
// Build some request parameters
var params = {
userWorkLoad: userWorkLoadInput.val()
};
// Let's name your PHP script file as "server.php"
// And send POST request with those parameters
$.post("server.php", params, function(response) {
// Response text we're going to put into the `output`
$("#output").html(response);
});
});
});
You can simply do it using Jquery instead of using Ajax (using PHP you should add method="POST" to the form).
Here's an example:
$(document).ready(function(){
$("#send").click(function(){
// your calculates
$("#output").html(...);
});
});
...
<button type="submit" id="send">Calculate</button>

Submit content of div in database on button click

I have a WYSIWYG tool where I can create a content. At the bottom, I have a form where I can submit a value (from an input text) to a database. That works fine. Now, I am trying to submit the content that has been created in the WYSIWYG in the database.
I am thinking of using a value in the input as shown below:
<input name="videoLink" type="text" value="John" required/>
and use javascript to make the value dynamic. But there must be an easier way. To make the form submit the content of a div instead of having to type anything in the input box.
My code is shown below:
angular.module("textAngularTest", ['textAngular']);
function wysiwygeditor($scope) {
$scope.orightml = '<h2>Put Your Text Here</h2>';
$scope.htmlcontent = $scope.orightml;
$scope.disabled = false;
};
.ta-editor {
min-height: 80px;
height: auto;
overflow: auto;
font-family: inherit;
font-size: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular-sanitize.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/textAngular/1.1.2/textAngular.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.min.css" rel="stylesheet" />
<div ng-app="textAngularTest" ng-controller="wysiwygeditor" class="container app">
<h3>WYSIWYG Editor</h3>
<div text-angular="text-angular" name="htmlcontent" ng-model="htmlcontent" ta-disabled='disabled'></div>
<!--<h3>Raw HTML in a text area</h3>
<textarea ng-model="htmlcontent" style="width: 100%"></textarea>-->
<h3>Preview</h3>
<div ng-bind-html="htmlcontent"></div>
<!--<h3>Bound with ta-bind, our internal html-binding directive</h3>
<div ta-bind="text" ng-model="htmlcontent" ta-readonly='disabled'></div>-->
<button type="button" ng-click="htmlcontent = orightml">Reset</button>
<form action="Insert.php" method='POST' enctype='multipart/form-data'>
<label><input name="videoLink" type="text" required/></label>
<input id="button" type="submit" name="log">
</form>
</div>
Use placeholder instead of value.
Set value =" " but the placeholder="Put text here" ... otherwise you could get a lot of Johns.. I presume that's what you want to avoid? I don't think you can avoid php/ passing values to php from html [using javascript] to enter values into a database.
Your form isn't that big. You don't need that amount of js unless your site is using angular/is included in all pages of the CMS. So if the question is really how to pass variables to php with minimal javascript, then comment.
You should still use placeholder instead of value. Otherwise if people don't change the text / maybe just press enter/submit.. your required error message won't fire. That's a lot of Johns in the db! :)
Hope this helps

Taking values from form, pulling results from MySQL, and using AJAX for results

I am having a bit of trouble figuring out how exactly to make a certain connection. It's a project I thought might be simple enough for me to do on my own without help, but I've hit a wall unfortunately. It's an 'exercise generator' that basically asks a few basic questions, and based on your answers, it outputs a recommended workout routine. I've constructed the MySQL database with plenty of exercises, have successfully connected the database, and have made the form.
What I am having trouble though, however, is storing those form results into variables, and based on those variables (if workout days is 3, for example, there would only be 3 groups of workouts printed instead of 5) output a routine into the same div as the form, effectively replacing it with the answer instead of placing it underneath the submitted form.
Index.php
<!DOCTYPE html>
<html>
<?php $page_title = "Workout Generator"; ?>
<link rel="stylesheet" type="text/css" href="style.css">
<head>
<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" ></script>
</head>
<body>
<?php include("header.php"); ?>
<?php include("connect.php"); ?>
<div id="appWindow">
<h3>Please answer the following questions and click 'Submit' to generate your workout routine.</h3>
<form id="homeForm" method="post" >
<label for="name">Name: </label>
<input type="text" name="name"><br>
<label for="age">Age: </label>
<input type="number" name="age"><br>
<label for="workoutdays">How many days a week can you workout?</label>
<select name="workoutdays">>
<option value="1">3</option>
<option value="2">5</option>
</select><br>
<label for="workoutstyle">Do you prefer a gym, or bodyweight exercises?</label>
<select name="workoutstyle">>
<option value="1">Gym</option>
<option value="2">Bodyweight</option>
</select><br>
<button type="submit" name="submit">Submit</button>
<button type="reset" name="reset">Reset</button>
<div class="form_result"></div>
</form>
<?php
$age = $_POST['age'];
$workoutdays = $_POST['workoutdays'];
$workoutstyle = $_POST['workoutstyle'];
?>
</div>
<br><br><br>
<?php include("footer.php"); ?>
</body>
</html>
I don't necessarily want an answer giving me the exact code to enter, but would appreciate being pointed in the right direction to get that form pulling data from MySQL, and using AJAX to print in the same window without refreshing.
THANK YOU
First of all, you need to post your request. With $.ajax this
//Do this thing on page load
$(function() {
//handle submit
$("#homeForm").submit(function(e) {
//customize your submit
e.preventDefault();
$.ajax({
type: "POST",
url: youURL, //maybe an url pointing to index.php
data: yourData, //attach everything you want to pass
success: function(response) {
$("#appWindow").html(response);
}
});
});
});
code should help. You need to make sure you pass the necessary elements and you provide the correct url. On server side, generate the desired html and send back as response.
In the script file
$(document).ready(function(){
$(document).on('click','#submit_btn',function(){
var url = '/xyz.php'; //full path of the function where you have written the db queries.
var data = '';//any data that you would like to send to the function.
$.post(url,{data: data}, function(result){
var arr = JSON.parse(result);
});
});
});
in your php file once your database query has been executed and you get the result. for example
$result = //result of your mysql query.
echo json_encode($result);
exit;

PHP - Getting the value from a div based bootstrap element

I am fine getting the value of a form controls such as radio and select for example but with all of the additional non form based controls available for Bootstrap i haven't really seen many PHP examples how to use these.
So my main question is with pure PHP how would you retrieve the current selected item from a div and li based dropdown?
http://www.bootply.com/b4NKREUPkN
or a custom color picker plugin?
http://bootstrapformhelpers.com/colorpicker/#jquery-plugins
If you are submitting a form and handling the request using PHP, you will not be able to access the DOM in PHP (client vs server). If you can pull out the bits that you need using javascript, you can set the values on hidden form elements and submit.
<?php
// print out the value when the post is submitted
if (isset($_POST["extraInput"])) {
echo "hidden input is: " + $_POST["extraInput"];
}
?>
<html>
<head>
<script type="text/javascript">
function doSubmit () {
var extraValue = document.getElementById("extra").innerHTML;
var form = document.forms["myForm"];
form.elements["extraInput"].value = extraValue;
form.submit();
}
</script>
</head>
<div id="extra">Hello world</div>
<body>
<form id="myForm" action="" method="post">
<input type="hidden" name="extraInput" />
<input type="text" name="textInput" />
<button onclick="javascript:doSubmit()">Submit</button>
</form>
</body>
</html>

How to get ajax commenting system to work from different directory?

I have a page and I am trying to add an ajax commenting system to it. When I put all the code in the /comment directory into root, my new pages can implement the script. However, if I make another directory, say /books, then link to the pages inside the /comment directory, It will not post the comments. I can display them and access the javascript page, but I can't not make new comments. What is causing it to fail. I think it is somewhere in the javascript file... I didn't want to include so much code if you need to see anything else, let me know and I will post it. I will include the php file and the javascript file up one directory, and into another... Any tips would be great. Here is my page:
<?php
// Error reporting:
error_reporting(E_ALL^E_NOTICE);
include('../comments/connect.php');
include($_SERVER['DOCUMENT_ROOT'] . '/comments/comment.class.php');
/*
/ Select all the comments and populate the $comments array with objects
*/
$comments = array();
$result = mysql_query("SELECT * FROM comments ORDER BY id ASC");
while($row = mysql_fetch_assoc($result))
{
$comments[] = new Comment($row);
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../style.css" />
</head>
<body>
<ul id="nav">
<li class="current">Home</li>
<li>
<ul>
<li></li>
</ul>
<div id="container">
<div id="content">
<?php
/*
/ Output the comments one by one:
*/
foreach($comments as $c){
echo $c->markup();
}
?>
<div id="addCommentContainer">
<p>Add a Comment</p>
<form id="addCommentForm" method="post" action="">
<div>
<label for="name">Your Name</label>
<input type="text" name="name" id="name" />
<label for="email">Your Email</label>
<input type="text" name="email" id="email" />
<label for="url">Website (not required)</label>
<input type="text" name="url" id="url" />
<label for="body">Comment Body</label>
<textarea name="body" id="body" cols="20" rows="5"></textarea>
<input type="submit" id="submit" value="Submit" />
</div>
</form>
</div>
</p>
</div>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="../comments/script.js"></script>
</body>
</html>
and the javascript...
$(document).ready(function(){
/* The following code is executed once the DOM is loaded */
/* This flag will prevent multiple comment submits: */
var working = false;
/* Listening for the submit event of the form: */
$('#addCommentForm').submit(function(e){
e.preventDefault();
if(working) return false;
working = true;
$('#submit').val('Working..');
$('span.error').remove();
/* Sending the form fileds to submit.php: */
$.post('submit.php',$(this).serialize(),function(msg){
working = false;
$('#submit').val('Submit');
if(msg.status){
/*
/ If the insert was successful, add the comment
/ below the last one on the page with a slideDown effect
/*/
$(msg.html).hide().insertBefore('#addCommentContainer').slideDown();
$('#body').val('');
}
else {
/*
/ If there were errors, loop through the
/ msg.errors object and display them on the page
/*/
$.each(msg.errors,function(k,v){
$('label[for='+k+']').append('<span class="error">'+v+'</span>');
});
}
},'json');
});
});
It seems you are connecting to your database with an include, using a relative path:
include('../comments/connect.php');
That would be the first thing to change, it could be something like:
include($_SERVER['DOCUMENT_ROOT'] . '/comments/connect.php');
In general, look for relative paths and see if you can change them to absolute paths, either relative to the root of your server for php files or relative to the web-root for javascript files.
You would normally have your comment script at a URL that doesn't change, i.e. www.domain.com/comments. Then, you can either fetch comments for a page with a GET request (specifying the page, URL or other unique identifier via a query string parameter), and then the ability to post a comment with, well, a POST request.
This way, your comments module is completely separate from your application and you don't need to go through every script it's included in if you need to say, change your database details or a file path.
At it's simplest, you could have a PHP file that looks like this for your comments script:
<?php
header('Content-Type: application/json');
switch (strtolower($_SERVER['REQUEST_METHOD'])) {
case 'get':
// return comments for page in JSON format
break;
case 'post':
// post new comment; return result in JSON format
break;
}
And then in your HTML view files:
<!DOCTYPE html>
<html>
<body>
<div id="comments"></div>
<form action="http://domain.com/comments.php" method="post" id="new-comment">
<!--rest of your form here-->
</form>
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
$.getJSON('http://domain.com/comments.php?page_id=YOUR_PAGE_ID', function(comments) {
$.each(comments, function(index, comment) {
// add comment to #comments div
});
});
$('#new-comment').submit(function() {
$.post('http://domain.com/comments.php', $(this).serialize(), function(response) {
// act on your form depending is response was success or not
});
return false;
});
});
</script>
</body>
</html>
You could also wrap the above in a plugin, and then just add your comments widget to your page with a one-liner, i.e. $('#comments').nameOfYourCommentsPlugin();.
Hopefully that's helpful enough for you to build a working solution.
I think problem is on the javascript side, your post goes to a relative url you should replace it with an absolute url:
/* Sending the form fileds to submit.php: */
$.post('submit.php',$(this).serialize(),function(msg){//<- replace submit.php with absolute url
...

Categories