I'm creating a website with the option to Login with an administrative account and I want to be able to edit different elements in the HTML set to javascript variables. When you log in, there will be an input box to take a value from the user and apply it to a widget on the page. I haven't yet found a way to save the input value by overwriting the variable set for the widget and have it save to the webhost (GoDaddy) and stay throughout all sessions for anyone who shall be looking. I don't want to use Cookies or localStorage because I would like for the value to not only save on that user's session but all looking at the site. Ideas?
(EDITED CONTENT BELOW)
Alright, I've used a database. I've gotten the code below:
<html>
<head>
<title>
MyAccount
</title>
</head>
<body>
<center>
<h1>
Welcome to your account!
</h1>
<input name="alertVal" type="text" placeholder="Alert Value">
<input type="button" text="Save" onclick="<?php saveAlert()?>">
<?php
// Connects to your Database
function saveAlert(){
mysql_connect("My IP is here. Not sharing that.", "adminLog", "Yeah, not putting my pass on a forum...") or die(mysql_error());
mysql_select_db("adminLog") or die(mysql_error());
$data = mysql_query("SELECT * FROM Alert")
or die(mysql_error());
while($info == mysql_fetch_array( $data ))
{
mysql_query("Update Alert SET Value = '$cleanURL'")
INSERT INTO Alert (Value);
VALUES ($_GET['alertVal']);
}
}
?>
</center>
</body>
</html>
And that doesn't work. Raises a T_STRING error. I don't really understand that. Help?
I don't want to use Cookies or localStorage because I would like for
the value to not only save on that user's session but all looking at
the site. Ideas?
If you don't want to use the various client-side stores stored (such as cookies or localStorage) you might consider storing this information on the server, in a database or a file. Depending on the server side language you are using there might be different approaches to achieve that.
You should use some sort of a database or just a simple text file. If you don't want to use a database, I recommend using Yaml.
BTW all GoDaddy plans include MySql. you can use that.
Related
This question already has an answer here:
Once I refresh the page that is getting data through a form , every thing will be gone
(1 answer)
Closed 10 months ago.
I am trying to populate data from a website to another wensite:
a.html:
<form action="b.php" method="post">
<textarea id="myProjects" name="mp"></textarea>
<input id="submit" type="submit" value="Submit" />
</form>
in b.php:
<?php $content=$_POST['mp'];
echo "you entered ".$content;
?>
This works in a very strange way, when I click submit button, I am directed to the b.php page, and I can see what I entered. But if I reload this page, not refresh, my contents disappear, and throwWarning: Undefined array key "mp" It looks like data received from $_POST is "temporarily" stored. I am new to PHP, so I am not sure how can I figure it out.
You can use the PHP SESSION feature to keep the data persistent:
in b.php:
<?php
// Start the session
session_start();
// save the input var as a SESSION property
if (isset($_POST['mp'])) {
$_SESSION['content'] = $_POST['mp'];
}
// display the property
echo "you entered " . $_SESSION['content'];
Generally speaking, what you want to do is to store the value of $_POST['mp'] into the $_SESSION variable so that it persists from one page request to the next.
However doing it by manipulating these variables directly is generally bad practice. Unless you sanitize the user input you are open to a myriad of scripting attacks. Although there is some learning involved, you are much better off using an established PHP framework (for example Laravel), which has a full set of validation functions, and manages the process of starting the session for you. A good framework will also help you in many other ways.
So I've been building my first WordPress plugin, and I've of course hit some roadblocks. I first wrote all this code as a page template, but now I'm converting it to a plugin so I can use it across several sites.
It's essentially a contact form that creates a price quote based on user selection. When it was a template, I just hardcoded the values and made everything work with an external jQuery file. Now, I'm wanting to take user input from the plugin admin settings page and use that value to make calculations rather than the values I hardcoded.
Here's what I had before with the jQuery:
(function($) {
$(document).ready(function(){
$("#carpet_cleaning).change(function () {
var bedrooms = $("#carpet_cleaning").val();
/*-------CHANGE RATES HERE--------*/
var total = (bedrooms * 39);
var totalPrice = "$" + total;
$("#output1").text(totalPrice).fadeIn();
});
}(jQuery));
So basically I want to use user input from the plugin admin settings instead of hardcoding a 39. That way prices can vary depending on what price the user wants to set.
Here's my HTML for my admin settings:
<h2>Display Settings</h2>
<form method="post" action="options.php">
<?php settings_fields( 'my-plugin-settings-group' ); ?>
<?php do_settings_sections( 'my-plugin-settings-group' ); ?>
<fieldset>
<input type="text" size="3" name="carpet_cleaning_price" value="<?php echo esc_attr( get_option('carpet_cleaning_price') ); ?>" /><label>Carpet Cleaning Price Per Room</label>
</fieldset>
<?php submit_button('Save all changes', 'primary','submit', TRUE); ?>
</form>
I was under the impression that I could use get_option to store the user input. If that's the best way to do that, how could I access that value in my jQuery variable?
Ideally I'd want to do something like:
var sectionalCleaning = carpet_cleaning_price;
And then just use carpet_cleaning_price instead of 39, which would give me the user value.
Is there some way I can do this easily? I'm also going to have to do this on the backend using PHP so that someone can't adjust the values in their browser and the calculation happens on the server, so if you have a solution for that as well, I'm open to that. Go easy on me, I'm a new developer! Thank you.
I am currently making a webpage where I want the user to view different database results depending on which result they pick. The results will either be picked through a button, or by a query typed in by hand into a textarea.
I have the connection to the database and everything set up in an external PHP script which I am currently linking in to my site using "require".
Within this PHP script I have a "query" variable.
I would like for this variable to be dependent on whatever value is entered by the user.
I suppose this should be doable using some sort of $query = $POST['entry'] and some kind of Ajax call in a javascript? I just don't know how this whole thing should be fitted together.
If we assume that my menu and container looks something like this, where getData.php is where the $query variable is and what returns the database data.
<div id="menu">
<textarea class="queryText" name="queryText" placeholder="Enter the query..."></textarea>
<input class="menuButt" type="button" value="Submit" onclick="JavaScript:ChangeDivVal();"/>
</div>
<div id="container">
<?php
require 'getData.php';
?>
</div>
Here is a picture if that helps my explanation of what I want to do.
I'm very grateful for any help I could possibly get!
//Ambrose
There are neat and simple mechanisms to pass the input of your textarea (the query string) to php and return the database output back to javascript. From there you then can easily attach it to any dom node you wish.
I personally do stuff with jQuery since its so handy. You might wanna use the load function for your simple purpose:
$( document ).ready(function() {
$('#querySubmitButton').click(function (evt)
{
evt.preventDefault(); // stops the submit taking place
var myQuery = $('#queryText').val(); // get the query value
// load data received from php script into the dom container
$('#container').load('getData.php', { query:myQuery, anotherVar:null });
});
});
The load function simply loads everything the desired script outputs into the given domnode. You can add as many parameters as you want in the second argument and could even use a callback to perform some more js after loading.
For details see http://api.jquery.com/load/.
Oh and by the way I changed your html to this:
<div id="menu">
<textarea id="queryText" name="queryText" placeholder="Enter the query..."></textarea>
<input id="querySubmitButton" type="button" value="Submit"/>
</div>
<div id="container"></div>
In your getData.php (which I assume produces plain html) you can then use php's $_POST var to get the query.
$query = $_POST['query'];
I got a bit stuck and would appreciate any help.
Intro
In short (I hope): I am creating a website (only local at the moment) which has stored city names and some important/interesting values (for example population, time, currency). I use a MySQL database to store the data. Three of these tables relevant to this case: Table 1. stores cities as values. table 2. stores the "title" of the relevant data (population, current time, currency). The third table the actual value (100 000, 12:30, Euro). I am using php to communicate between the database and the html.
Desired outcome:
A search box is used to find a city of interest. The web page prints the selected city in the top of the page and some relevant data of the city inside two divs.
Problem
How can I get the value of autocomplete back to php in order to make three different SQL queries on the same page depending on the selection?
I read that you could use a php -file as the source of the autocomplete (now on an array, values stored from the database) and somehow autocomplete could retrieve other data based on the users' selection. But will it work if I am not using any other jquery-ui component? How would it actually be written in code?
EDIT
I read shortly about:
Sending it as POST, but can it be done in the same page?
Use sessions
Use AJAX
What is the easiest/best to understand/use?
Any other suggestions?/help?/tips?
At this point my stack has overflown.
Summary
What is a easy to learn and correct way to handle communication from javascript/jQuery back to PHP while staying on the same page?
Code
<?php
require_once "dataPDO.php"; //All of the sql-queries
$databaseHandler = new dataPDO();
$list=$databaseHandler->allCities(); //a list of all the cities
?>
<!doctype html>
<html>
<head>
<title>Choose a city</title>
<meta charset="utf-8">
<!-- needed by autocomplete -->
<link rel="stylesheet" href="js/jquery.ui.all.css">
<script src="js/jquery-1.10.2.js"></script>
<script src="js/jquery.ui.core.js"></script>
<script src="js/jquery.ui.widget.js"></script>
<script src="js/jquery.ui.position.js"></script>
<script src="js/jquery.ui.menu.js"></script>
<script src="js/jquery.ui.autocomplete.js"></script>
<script>
$(function() {
var names=<?php echo json_encode($list); ?>;
$("#cities").autocomplete({
source: names, minLength: 2
});
});
$(document).ready(function () {
$('#cities').on('autocompletechange change', function () {
var data = $('#city').html('Chosen city: ' + this.value);
}).change();
});
</script>
</head>
<body>
<div>
<div class="ui-widget">
<label for="cities">Search for a city:</label>
<input id="cities">
<div id="city"></div>
</div>
</div>
<div>
<section class="left">
<?php
try {
$databaseHandler->information(1);//(hardcoded) information belonging to the first city
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
</section>
<section class="right">
<?php
try {
$databaseHandler->values(1);//(hardcoded) information values belonging to the first city
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
</section>
</div>
</body>
You certainly do not need to use JQuery or another framework, however, it sure does make it a lot easier to do these types of things. RyanS' comment about using JQuery makes a lot of sense for this reason. You'd just be reinventing the wheel.
Basically, the process will be to make a PHP file that takes some parameters through GET or POST and then uses those parameters to display the data. Once you have that file in place, you can use Javascript to trigger an event to call that PHP script. For instance, you can say when someone selects a value from a drop down menu, then pass these parameters to the PHP script and display the output from there into a div that you have on the same page as the drop down menu.
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.