I have a WordPress page where the default login/signup page is disabled and I let users register via a WooCommerce login/signup page with a bunch of custom fields added through my theme's functions.php.
One of those fields is a dropdown field that lets users select their country.
If a user misses something in the registration form and the page reloads (with an error message telling the user what was missing), the text fields are pre-populated with their previous text. The dropdown menu, however, reverts back to its neutral option instead of remembering its previous value.
My code looks like this:
<?php add_filter( 'woocommerce_register_form', 'adding_custom_registration_fields' );
function adding_custom_registration_fields($fields) {
$countries_obj = new WC_Countries();
$countries = $countries_obj->__get('countries'); ?>
<div class="form-row form-row-wide">
<label for="reg_billing_country"><?php _e( 'Country', 'woocommerce' ); ?> <span class="required">*</span></label>
<select class="country_select sk-required" data-sk-tooltip="Required" name="billing_country" id="reg_billing_country">
<option value=""> <?php _e('Select country','my-theme'); ?></option>
<?php foreach ($countries as $key => $value): ?>
<option value="<?php echo $key?>"><?php echo $value?></option>
<?php endforeach; ?>
</select>
</div>
I want the dropdown field to remember its value if the page reloads, just like the text fields do. Can I use html to encourage the browser to cache the value?
I tried
var selectedItem = sessionStorage.getItem("country_select_session");
$('#reg_billing_country').val(selectedItem);
$('#reg_billing_country').change(function() {
var dropVal = $(this).val();
sessionStorage.setItem("country_select_session", dropVal);
});
However, the value is only retained if I manually reload the page using F5. If the page reloads by clicking the "submit" button with an incomplete form, the dropdown menu reverts back to its default value, ignoring the script
I got it to work - turns out the script was not placed properly and thus did not get executed. Thanks to #mplungjan for pointing it out.
I added the script mentioned above right before the </body> tag with this code in my functions.php:
add_action( 'wp_footer', function () { ?>
<script language="javascript" type="text/javascript">
var selectedItem = sessionStorage.getItem("country_select_session");
$('#reg_billing_country').val(selectedItem);
$('#reg_billing_country').change(function() {
var dropVal = $(this).val();
sessionStorage.setItem("country_select_session", dropVal);
});
</script>
<?php } );
With the wp_footer action hook, the script got placed and executed properly.
Related
This has been answered before, however I'm asking again for two reasons: I can't find any resources that utilize PDO, and regardless of that, all of the ones I've found consist of code without any comments or explanations, which makes it hard to interpret and adapt them to my use case.
I need to be able to make a dropdown dynamically update itself based on the selection of the previous one, and if I change that selection, it should re-update itself without having to submit the form or reload the page.
I've updated the code with what I've learned and found so far, but it's still not working properly. Everything works up to the point where the second dropdown should begin loading values.
HTML:
<div class="form-group row">
<label class="col-sm-2 form-control-label" onchange="productorInfo(this.value);">Codigo Productor (*)</label>
<div class="col-sm-4">
<select name="vendedor_codigo">
<?php foreach ($dd_productor_result as $dd_productor_display) : ?>
<option value="<?= $dd_productor_display['vendedor_codigo']; ?>">
<?= $dd_productor_display['vendedor_codigo']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
<label class="col-sm-2 form-control-label">Nombre (*)</label>
<div class="col-sm-4">
<select id="ajax-vendedor" name="vendedor_nombre">
<?php foreach ($ajax_productor_result as $dd_productor_display) : ?>
<option placeholder="Seleccione codigo" value="<?= $dd_productor_display['vendedor_nombre']; ?>">
<?= $dd_productor_display['vendedor_nombre']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
Ajax script:
function productorInfo(id) {
$.ajax({
type: "GET",
url: "/controller/produccion/db_ajax_update.php",
data: "mainid =" + id,
success: function (result) {
$("#ajax-vendedor").html(result);
}
});
};
First dropdown PHP code:
$dd_productor = "SELECT vendedor_codigo FROM lista_productores";
$productor_stmt = $pdo->prepare($dd_productor);
$productor_stmt->execute();
$dd_productor_result = $productor_stmt->fetchAll();
Second dropdown (ajax call):
if(isset($_GET['mainid'])){
productorInfo($_GET['mainid']);
$prod_value = productorInfo($_GET['mainid']);
}
$ajax_productor = "SELECT vendedor_nombre FROM lista_productores WHERE vendedor_codigo = {$prod_value}";
$productor_stmt = $pdo->prepare($ajax_productor);
$productor_stmt->execute();
$ajax_productor_result = $productor_stmt->fetchAll();
The onchange call should be on the select element not on the label
<label class="col-sm-2 form-control-label">Codigo Productor (*)</label>
<select name="vendedor_codigo onchange="productorInfo(this.value)">
But also it occurs to me you may not quite understand the process. Your ajax call won't be fired when the page loads so this bit:
<select id="ajax-vendedor" name="vendedor_nombre">
<?php foreach ($ajax_productor_result as $dd_productor_display) : ?>
<option placeholder="Seleccione codigo" value="<?= $dd_productor_display['vendedor_nombre']; ?>">
<?= $dd_productor_display['vendedor_nombre']; ?>
</option>
i would think is giving you undefined variable warnings (unless you are setting $ajax_productor_result initially in some way)
Responses from ajax are usually drawn in .js via success: function
(result) {
$("#ajax-vendedor").html(result);
}
from the looks of this though - unless there is more code that what has been posted, you are passing the .html() function an array or database rows so it's never going to display anything.
so you need to
1)draw a select with no options in it on pageload (or default options if you have them)
2)return a response that the success function can make use e.g. a json string which jquery can the parse
3)format the data in jquery into the <options> and then user the .html() function to update the select
4)if you want this to happen when the page initially loads then add in a document ready call to the productorInfo(id) function - this would be relevant if you are setting the initial select value in some way (so it may not be relevant to you)
I have a variable numbr forms I want a user to be able to choose to view via a drop down list. I have assigned each of the form content to array $forms & the associated form name to array $formnames
The idea was to display the variable number of form names as buttons in the drop down selection, and once selected it would display the form content.
I've tried the below code but this leads to the drop down selection immediately showing both the form content as well as name. Could someone point me in the right direction given my limited understanding?
<div class="dropdown">
<button onclick="dropdownfunction()" class="dropbtn">Available List</button>
<div id="avaiablelist" class="dropdown-content">
<?php
$keys = array_keys($forms);
$namekeys = array_keys($formnames);
$arraysize = count($forms);
for($i=0; $i<$arraysize;$i++) { ?>
<?php echo $formnames[$i]['formname']; ?>
<?php
}
?>
</div>
</div>
In this case i would use
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> method="post">
</form>
to send $forms[$i]['form'] via Post method
I am using a feature of popup box in my project. When a user come to the site a popup box apears on the top of the page hiding the rest of the content. In that popup form the user has to give a download key. if the user has the key he can go forward otherwise he cannot see anything else. When the user provide the key he goes to the main page.
Now the problem is once the user comes to the main page after providing the key and when he clicks again on the header again the page is reloaded and again tht popup form comes. How can I prevent it to apear again if some user has already given the download key . I am using php with code igniter. My code
<?php if($download_key != null && !isset($_POST['popup'])){?>
<script type="text/javascript">
$(document).ready(function(){
loadPopup();
});
</script>
<?php } ?>
downlaod key is database column and popup is a hidden input that is set when the form is submitted on the popup box.
The form that appears on popup box is as
<form name="form" method="post" onsubmit="return validateForm('<?php echo $download_key ?>')">
<div style="width:530px;">
<input style="display:none; height:25px;" id="downloadkey" name="downloadkey" type="text" />
<input style="display:none;" type="submit" id="submit" name="submit" value="<?php echo $variable['QUESTION_BUTTON']['value']?>"/>
</div>
</form>
Any ideas ?
Thanks
You should have a session_start() at the beginning of pageload
EDIT: changed a bit
session_start();
//check if key has already been seen:
if(isset($_SESSION['download_key']) && $_SESSION['download_key'] != null ...
// then if not check if the key is submitted
else if ( isset($_POST['popup']) ... // and other checks
// set session variable
$_SESSION['download_key'] = $key;
else
// load the ask for key page
Set a session variable, and check to see if it's present, as it will be on subsequent pageloads, and just skip the popup etc.
<?php
session_start();
if ($download_key != null && !isset($_POST['popup'])) {
if ($_SESSION['key_ok']!=true) { //you should check if it's set first with isset()
echo '<script type="text/javascript">';
echo '$(document).ready(function(){';
echo 'loadPopup();';
echo '});';
echo '</script>';
}
if (key_is_correct) {$_SESSION['key_ok']=true}
}
?>
I'm a complete beginner with jQuery and I have this bit of script here and I want to mix jQuery with PHP. I have Courses and in those Courses are Lessons. A Teacher is assigned to teach a Course. What I want is a link where if I press it a popup appears and in it shows the Lesson details or Course details. My problem is that I will be having multiple links and thus dialogs/modal windows in a page such that $l['id'] and $c['id'] will be different. How can I therefore use $l['id'] and $c['id'] in or with jQuery given that the jQuery script is inside the view file and I'm creating the actual content itself in the controller and passing it onto view. Sorry if I don't make sense cause I'm still quite confused about all this myself.
view.php
<script type="text/javascript">
$(function(){
// setup ul.tabs to work as tabs for each div directly under div.panes
$("#tabs").tabs();
$('#dialog').dialog({
modal: true
});
})
</script>
<h1>Student Hub: Courses for <?php echo $studentName;?></h1>
<div id="tabs">
<?php echo $content;?>
</div>
controller.php
This is in a foreach loop
<div class="lessonDetails">
<p>Lesson Details:<p>
<div id="lessonDialog'.$l['id'].'" title="Lesson Details">
'.$l['name'].'
</div>
</div>
<div class="courseDetails">
<p>Course Timetable & Resources<p>
<div id="courseDialog'.$c['id'].'" title="Course Details">
<p>'.$c['fullname'].'</p>
<p>'.$c['summary'].'</p>
<p>Upcoming Lessons: </p>
</div>
Technical answer is you don't as one is a server-side language and one is a client-side language; you can't access PHP variables via JavaScript (jQuery). You can, however, drop your PHP variables into your HTML page on generation, and then pick them up with JavaScript or jQuery.
Reading your scenario, I think your over-complicating things. Think of your application; don't think of the technical aspects, but more the way it should be laid out. I'm guessing you have a students controller, a lessons controller, and a courses controller. Those controllers will have actions, called view or similar, and then these actions will take an ID to display a particular student/course/lesson.
In your HTML page/view/template, you should have just vanilla URLs. JavaScript should then be used to enhance the website. So in your case, I would have mark-up it up similar to as follows:
<ul class="courses">
<?php foreach ($courses as $course): ?>
<li><?php echo $course->title; ?></li>
<?php endforeach; ?>
</ul>
I'd then, in an external JavaScript file, have a function that listens for a click on the <a> tag and instead of navigating to that URL, instead displays the page content in a pop-up/modal window.
<script>
$('.courses a').click(function(e) {
e.preventDefault();
// load external page and display it in a modal
});
</script>
This way, if for some reason JavaScript's not available then the user will be taken to the course details page. If they do have JavaScript, then they'll get a fancy modal pop-up.
Hope this helps. If you need anything clearing up then let me know, as I have wrote this in the early hours after a few JD and Cokes!
you can create in every link some extra attributes and using jQuery retrieve the information with the attr function $('a').attr('courses').
somethig like
<a href="#" class=".information" teacher="idTeacher" course="idCourse" >list </a>
then using jquery
$('.information').click(function(){
teacher= $(this).attr('teacher');
course=$(this).attr('course');
});
remember to use $('.information').live() if you are using some AJAX to get the data from the server and the parse it to create the links
You can place tags within your JavaScript code. Since that code is server side, it will "render" to your JavaScript client side code. So your JavaScript can access values stored by your PHP script.
Here's a solution using jQueryUI dialog. No ID's are required however should they be needed add them as a data attribute to that links
<p><a href="#courseInfo'.$c['id'].'" data-id="'.$c['id'].'" >Course Timetable & Resources</a><p>
This allows easily getting ID with jQuery data() method.
Dialog is created and destroyed each use. As noted in comments, no idea what content goes in dialog. I can easily adjust if it is ajax from href
$('.lessonDetails a, .courseDetails a').click(function(){
var $this=$(this);
/* if need the id associated to link*/
var id=$this.data('id');
var content= ''/* ??????? */
var title=$this.parent().next().attr('title')
loadDialog(title, content);
return false; /* stop browser following href*/
})
function loadDialog(title, content) {
var dialogOpts = {
modal: true,
title: title,
width: 800,
close: function() {
/* remove this dialog from DOM on close*/
$(this).remove()
}
};
$('<div>').append(content).dialog(dialogOpts);
}
Maybe you can create forms that have hidden values in it.
<?php foreach($lesson as $l): ?>
<form method="POST" action="">
<input type="hidden" name="lesson_id" value="<?php echo $l['id']; ?>" />
Click
</form>
<?php endforeach; ?>
javascript:
$(document).ready(function() {
$('.modal_window').click(function() {
var form = $(this).closest('form');
var lesson_id = $(form).find('input[name=lesson_id]').val();
// Do something with lesson_id
});
});
The idea is the same for courses.
****** Edit ********
Maybe you can try using input arrays. Assumming you have something like this
<input type="hidden" name="courses[]" value="1" />
<input type="hidden" name="courses[]" value="2" />
javascript:
var courses = $(form).find('input[name^=courses]');
$(courses).each(function() {
var course = $(this).val();
});
I'm using cake & have a web form for entering URLs to go into my db. There will be one input space (url1) and below that a link that says "add another URL" which, when clicked, generates a new form (url2) and reuses the "add another URL". So it would be like:
echo $form->input('name');
echo $form->input('id');
echo $form->input('url1');
echo $form->input('weight1');
echo 'add another URL';
and then, if XXX is clicked it would be like this:
echo $form->input('name');
echo $form->input('id');
echo $form->input('url1');
echo $form->input('weight1');
echo $form->input('url2');
echo $form->input('weight2');
echo 'add another URL';
Is there a jquery script I can use to do this or does cake have something built in?
Haven't try the code but i would do something like this:
<form>
<div id="mainData">
echo $form->input('name');
echo $form->input('id');
</div>
<div id="urlsHolder">
<div class="url">
echo $form->input('urls[]');
echo $form->input('weights[]');
</div>
</div>
add another URL
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#addUrl').click(function( event ){
event.preventDefault();
$('div.url').filter(':first').clone().appendTo('#urlsHolder');
});
});
</script>
When the form is submited do a foreach for $_POST['urls'] and $_POST['weights'].
There is room for improvement, It's just an inspirational example.
Hope it helps.
Actually I think it's not necessary to do your work like this.According to your description,I think you can change the add another URL to any other element such as a button,which will make a hidden div visible when clicked.Then it will be what you want.