Use get_option in WordPress to create new JavaScript variable - javascript

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.

Related

How to make an input value permanent in wordpress or work with global variables

I currently make my first Wordpress website using Java script snippets for a countdown that refreshes itself constantly and allows me to click a button once every 6 hours. So I managed that the time refreshes itself but I need one permanent variable that tells me if I already clicked the button or not (since it should work wether I refresh the page, go to another side or even log in with another user).
Basically I just want one variable that changes between 0 and 1.
I implemented a hidden input field and it works just fine as long as I stay on the side (refreshing the side works as well) but as soon as I change the page it sets the variable back. I tried to implement a global variable in the function.php of my theme (and a function as well) but it still doesn't work.
I tried it like this:
global $x;
echo $x;
And this:
function displayX() {
global $x;
$x = "0";
echo $x;
}
The thing is I don't want to set a value because the variable needs to be changeable any time.
That's my current html:
<input type="text" id="id1" value="<?php echo $x; ?>" <="" input="">
But it just doesn't work.
My second approach was to make the input field permanent (but updateable) - again this approach works as long as I don't change the side.
I tried it like this:
<span id="00">
<input type="text" id="id1">
</span>
Can anybody please help me? Also please specifiy where I have to set the global variable since there are so many function.php files.
THANK YOU!
Easiest way to do that is using of update_option and get_option.
update_option is for save data to database that will be permanent.
get_option is for fetching data from database.
<form method="post">
<input type="text" name="permanent" id="permanent" value="<?php echo get_option('permanent_data'); ?>"/>
<input type="submit" name="save" value="submit"/>
</form>
You can catch form data in backend using an action like this:
in functions.php
add_action('init','save_permanent');
function save_permanent(){
if(isset($_POST['save'])){
update_option('permanent_data', $_POST['permanent']);
}
}
Below code checks that if form is submitted:
if(isset($_POST['save'])){
update_option('permanent_data', $_POST['permanent']);
}
If form submitted it gets value of input text that named permanent
Mentioned code permanent the data in database as name of permanent_data
If you want to fetch stored data you just call get_option(option name) like this:
<?php echo get_option('permanent_data'); ?>
For first question you can do it in such way:
in functions.php
<?php
if(if(isset($_POST['save']))){
update_option('already_clicked', '1');
}
And for fetch stored data you can use:
<?php
if(get_option('already_clicked') == '1'){
//do somthing
}
?>

Advantage in sending a value defined with PHP in a form

EDIT: This code isnt for debugging, it is written only as an example and doesnt need completion as the point of it is just seeing the advantages of using a HIDDEN input in a form to retrieve some value. The answers may also be quick and graphic or metaphorical. I dont want a working code, just the advantages of using each methodology. I also fixed an imaginary condition to the while loop and a value for $record_id and placed them so you can understand.
<?php
if (isset($_POST['delete_action'])) {
$deletedRow = $_POST['row_to_be_deleted'];
mysqli_query($connection, "DELETE FROM table_name WHERE record_id = " . $deletedRow);
//Here is where hidden field value is used
}
$someSQL = "SELECT * FROM comments_tbl WHERE postID=$PostRetrievedID";
while ($someFetch = mysqli_fetch_array($con, $someSQL)) {
$record_id = $someFetch['comment_ID'];
$record_content = $someFetch['comment_Content'];
?>
<span>
<?php echo $record_content; ?>
</span>
<form method="post">
<input type="hidden" name="row_to_be_deleted" value="<?php echo $record_id; ?>"/>
<input type="submit" name="delete_action" value="Delete comment"/>
</form>
<?php
}
?>
If your question is about why hidden fields even exists, then I have to say that they are used on lots of websites for the exact reason you show in the example.
Lots of times, when you have a form and the user submits it, you need some extra data that the user should not see so that you can manage the data the user submitted. Like in you example, one common use is to atach the ID of the row.

How to generate a link for every row/record found in a database to use as a way to populate a form when clicked on?

I have a website with members and when members are logged in they have access to a page with a form that they can use to submit information. This form has a hidden input “user_email” with a pre loaded defualt value that is equal to the logged in members email address on file.
<form action="xxx.php" class="well" id="xxx" name"xxx" method="post">
<input type="hidden" id="user_email" name="user_email" value="xxx#email.com">
<input type="text" id="invoice_id" name="invoice_id">
<input type="text" id="other1" name="other1">
<input type="submit" value="Submit">
</form>
I need a script that will take that pre filled value of a forms input named “user_email” and search and fetch every row/record of data in my database that have that same value under the “user_email” column.
Then For every row/record matched/found I'm trying to have a link generated
When any generated link is clicked, It needs a function to pre fill the form with its corresponding fetched row/record data.
I cant imagine how much time it would take for one to posses the skills required to compose the code it takes to achieve the above...Any point of direction or any help is greatly appreciated...thanks for your time.
You could make a request to a PHP script that reads the email, finds the and returns associated data as an array of objects, and outputs the HTML links, with each link containing the data in custom 'data-x' attributes. For example:
//email_details.php
<?php
//your function that returns an array of objects
$rows = find_the_data($_GET['user_email']);
foreach($rows as $row) { ?>
<a class="email_data_link" href="#" data-invoice-id="<?php echo $row->invoice_id ?>" data-other1="<?php echo $row->other1 ?>">A link</a>
<?php } ?>
You could then use a tool like jquery to modify the form when a link is clicked
$('.email_data_link').on('click', function() {
//copy the data embedded in the clicked link to the form
$('#invoice_id').val($(this).data('invoice-id'));
$('#other1').val($(this).data('other1');
});
Without additional context and understanding your level of expertise, it's hard to create a truly helpful example, but this may at least give you some food for thought.
Best of luck

How can i pass a variable from one page to another?

I am creating a website, that has many pages. You can change the number of posts shown in each page through a drop down menu. My problem starts if i change the amount of posts move to the next page it comes back to default.
e.x default posts shown is 30, and then i change it to 40. The moment i change page it comes down to 30 again on the next page.
I have tried something like that but unfortunately doesn't work.
<form method="get" name="SkipPage">
<select name="results_no" onChange="document.forms['SkipPage'].submit()"> `
<?php
....
?>
</select>
</form>
$reults_no = isset($_GET['results_no']) ? $_GET['results_no'] : 30;
try to use hidden intput
<input type="hidden" name="myHiddenVar" value="<?php echo $myVar ?>"
Then you can use your var with $_POST["myHiddenVar"];
But if you want a persistent choice use sessions.
session_start(); on each page and access/edit your var with $_SESSION['myVar'];
If you want to make a user choice persistent, the usual solution is to save it in a cookie.
EDIT: or in SESSION but my point is that you don't have to pass the value as a GET parameter for each link followed by the user. You set it once and test if set on each page that need it.

Filling form fields with jquery

So I have a form that will be used for both inserting and editing data from MySQL.
I thought that instead of writing two forms, I'd write just one, that will be used for both purposes. So when it's for inserting new data, its fields (inputs etc) are obsiously empty. But when it's for editing existing data, I have Jquery for filling the fields with .val().
Like this:
function formSetup(form_name, array_fields)
{
$(document).ready(function(){
var selector;
for(var key in array_fields)
{
selector = "form[name=" + form_name + "] [name=" + key + "]";
//alert(selector);
$(selector).val(array_fields[key]);
}
});
}
And then:
var fieldsArray = new Array();
fieldsArray["field1"] = "data read from Myqsl php";
fieldsArray["field2"] = "data read from Myqsl php";
//etc
Btw, PHP does the job of telling my page whether this form is supposed to insert or edit data, so this javascript function will only be called by php when there is $_GET["action"]=="edit".
What I want to know is, is this the best approach for doing that kind of thing?
Is there a standard way for doing this?
Me to. I'm making the same form for two actions - inserting and editing.
If you using some kind of ajax technology and trying to fill up the form without page refresh you are going right way. But better is just to add values with php by echo'ing data in to the fields values.
There is no such standards for that. Accept you.
You are right, it is nice to have only one form.
Values usualyy filled on the server side (by PHP in your case) but this depends on the project architecture - you may use jQuery. Example for PHP:
<input type="text" name="email" id="email" value="<?=$data['email']?:''?>" />
Example with jQuery:
$.get("getData.php", function(data){
$("input#id").val(data['id']);
$("input#email").val(data['email']);
});
To find out whether the form is used to insert or update data use hidden field with the database record's primary key (usually id):
<input type="hidden" name="id" id="id" value="<?=$data['id']?:''?>" />
When this field is empty - create a new record. When it is containing some value - update a record having the primary key containing in it.
I would do this serverside.
In raw PHP, that is one without a support framework like Yii, Cake, etc. I would implement a light weight MVC framework.
Create a Business Object class.
class MyData
{
$field1;
$field2;
..
}
Then fill your Business Object from your datasource.
$data = new MyData();
$data->field1 = "Something";
$data->field2 = "Other stuff...";
or if it's new data.
$data = new MyData();
Create a form template.
Contents of form.tmp.php
<form ...>
<input type="text" name="field1" value="<?= $data->field1; ?>" />
<input type="text" name="field2" value="<?= $data->field2; ?>" />
</form>
Then use a light wrapper around your template.
ob_start();
include('form.tmp.php');
$html = ob_get_contents();
ob_end_clean();
It's been a while since I've done anything like this. There are a TON of PHP frameworks that take care of this for you though. Some lightweight ones, some heavy enterprise ones.
I didn't test this, but this should get you started.
Instead of populating your form with javascript the better approach would be to handle this server side.
In your php template you can do populate the inputs like this
<input name="field1" type="text" value="<?php echo $fieldValues['field1']; ?>" />
<input name="field2" type="text" value="<?php echo $fieldValues['field2']; ?>" />
If there is no value for each variable the field will be blank otherwise the data you retrieved from the database will be inserted.

Categories

Resources