how to stop refreshing page on onchange="this.form.submit()" - php

see my client site first to get an idea.
In above site, i have a giftfinder box in right side. There are 3 select boxes. currently I'm using 3 forms for these 3 select boxes which means each drop down select box is embedded into form. When you select the first drop down select box, it picks one and second select box's value will be determined which value is selected from first select box. So if you choose Man, then all athe related occasions of Man will be dispalyed into seconds drop down select box. Its working fine.
But the problem is it refreshes everytime you select the first drop down box.
I don't want to refresh page. it must select the value and pass the value so seconds select box can determine its related values.
so I'm thinking to us ajax. but no success.
So i included some code for the first drop down select box.
this is mix of html and php and wordpress.
<div class="select-one">
<form id="searrec" method="post" action="">
<select name="selectionRecipient" id="selectionRecipient" onchange="this.form.submit();">
<?php
$results_rec = get_option('current_recipient');
if(isset($_POST['selectionRecipient'])){
$results_rec = $_POST['selectionRecipient'];
update_option('current_recipient', $results_rec);
$results_rec = get_option('current_recipient');
}
?>
<?php
//asort($result_rec);
$t_name_arr = array();
foreach($result_rec as $rec):
$t_id = $rec->term_id;
$term = get_term($t_id , 'category' );
$t_name_arr[] = $term->name;
endforeach;
//print_r($t_name_arr);
rsort($t_name_arr);
foreach ($t_name_arr as $t_name):?><option class="rec_val"<?php if($results_rec==$t_name){ echo 'selected="selected"';}?>value="<?php echo $t_name;?>"><?php echo $t_name;?></option>
<?php endforeach;?>
</select>
<input type="hidden" id="submitrec" value="Search" />
</form> -->
</div>
So I'm am using form method post and using $_POST to retrieve the selected value and pass it to $results_rec variable.
Later in the code, I'm using if.. else to determine if $results_rec =='Man' then display certain items which are related to Man and so forth.
So what I want is not to refresh the page while I select item from first drop down select box.
Please help.

change this:
<select name="selectionRecipient" id="selectionRecipient" onchange="this.form.submit();">
to this:
<select name="selectionRecipient" id="selectionRecipient">
and the jquery:
$("#searrec").submit(function(e) {
e.preventDefault();
// your code
return false;
});
EDITED:
use this to get the selected index (number)
var index = $("#selectionRecipient")[0].selectedIndex;
or value:
var value = $("#selectionRecipient")[0].value;
Then you can call an ajax perhaps: (assuming the other selection box has "id=other_select"
$.ajax({url:"index.php",type:"POST",data {type:"populate",index:2,value:"option1"},dataType:"json",
success: function(data) {
// data (json) returned from server so populate other selection boxes with that..
// in this example 'data' is an array, coming directly from server (see below the .php)
$("#other_select")[0].selectedIndex = 0;
for(var x in data) {
$("#other_select")[0].options[x] = new Option(data[x]);
}
}
})
in your .php i assume you get a list (etc. database) to populate the other selection list (in client). This code could looks like:
if (isset($_POST["type"]) && $_POST["type"]=="populate") {
echo json_encode(array("option1","option2","option3"));
exit(1);
}

$('#searrec').submit(function () {
//do some form submit work here
return false;
});

You'll have to use an AJAX call to populate the other select boxes based on whatever you've selected in the first one without reloading the page.
I suggest you take a look at jQuery's AJAX functionality. Read up on $.ajax and $.post - with them you could submit the value that you've selected in the first listbox to a PHP script and then based on that value return and populate the other select boxes.

Use AJAX to update the other selects without refreshing the page. Use jQuery to make AJAX easy.
This question will help:
Change the selected value of a drop-down list with jQuery

$('#searrec').submit(function(e){
e.preventDefault();
});

You should delete event onchange="this.form.submit(); from combobox
And use ajax with jquery:
$("#searrec").onchange(function() {
$.ajax({
url:"",
success:function(response){
alert("success");
}
});
});

Guys its fixed.
Plz have a look at http://giftideasitems.com/.
See gift finder box and see how it works.
I used iframe and embedded the forms, drop down coding there. thats it.
Even I used onchange="this.form.submit()" and page doesnot referesh, actually page refresh .... but not the main page, only the iframe is refreshing which is fine. this is exactly what i wanted.
<div id="gift-finder">
<div class="gift-finder-form">
<iframe name="inlineframe" src="code.php" frameborder="0"
scrolling="auto" width="200" height="180"
marginwidth="0" marginheight="0" id="gift-iframe">
</iframe>
</div>
This is my iframe code and see src, i used code.php; so all code is in separate place.
Though I had to modify some css, but anyways this is fine.
Thanks everyone who contributed yesterday.

Related

Populate a drop-down list depending on what is selected from another drop-down list from two variables PHP

I have a question on how to populate a drop-down list depending on the value that is selected in another drop-down list.
I'm working with an MVC pattern and when the view loads, it already brings me two variables with the values I need. What are $tipohardware and $tiposoftware.
So I wouldn't need to call a .php file again to get the data, because it's already loaded.
My static drop-down list is:
<select id="producto" class="form-control" required>
<option value="">Seleccionar..</option>
<option value="1">Hardware</option>
<option value="2">Software</option>
</select>
And the dynamic drop-down list I want to populate depending on what is selected in the drop-down list "producto" is:
<select id="tipoproducto" name="tipoproducto" class="form-control">
</select>
I already have two variables that have the data of the tables, "tipo_hardware" and "tipo_software". What are $tipohardware and $tiposoftware.
So, for example, if I select the "Hardware" option in the drop-down list, the second drop-down list should be filled with the data of the variable $tipohardware.
On the other hand, if I select "Software" the drop-down list should be populate with the values of the variable $tiposoftware.
Here's my controller if you needed to.
<?php
namespace app\controllers;
use \app\models\Hardware;
use app\models\Software;
use app\models\TipoHardware;
use app\models\TipoSoftware;
use \Controller;
use \Response;
class IngresarProductoController extends Controller
{
public function actionIndex()
{
$softwares = Software::all();
$hardwares = Hardware::all();
$tiposoftware = TipoSoftware::all();
$tipohardware = TipoHardware::all();
Response::render("ingresarProducto", ["hardwares" => $hardwares,
"softwares" => $softwares, "tipohardware" => $tipohardware,
"tiposoftware" => $tiposoftware]);
}
}
I think I should call a php code in a javascript onchange function like:
$("#producto").on("change",function){
<?php
foreach($tipohardware as $tipohard) {
?>
<option value="<?php echo $tipohard->idtipo_hardware ?>"><?php echo
$tipohard->nombre_tipo_hardwarecol ?></option>
<?php
}
?>
}
});
But I dont know how I can continue with that,
Thanks for the help!
You are mixing frontend script with backend script, which does not work. Backend will build the entire page before the frontend starts doing it's thing. PHP creates the DOM and JavaScript manipulates the DOM after PHP spits it out. That is why your jQuery does not work/update.
For example, if you do this:
$('.button').on('click',function(){
var whatever = <?php echo rand() ?>;
alert('This value is'+whatever);
});
It will run the php first so you will end up with the random number off the bat:
$('.button').on('click',function(){
var whatever = 3241231;
alert('This value is'+whatever);
});
No matter how many times you click the button element, it will always say 3241231 until you reload the page when PHP will run the rand() function at load.
To make it load in real time, you need to create an ajax listener to receive a value from the target, send to the backend PHP, then when that backend page responds, you place the response back into your currently loaded page, altering the DOM.
A simple example would be:
/index.php
<?php
# Create the back end to listen for your front end ajax
if(!empty($_POST['test'])) {
# Do your code here to send back.
$rand = rand();
die('Ajax done! Here is a random number: '.$rand);
}
?>
<!-- CLICK ELEMENT -->
<div id="button">CLICK</div>
<!-- PLACEMENT ELEMENT -->
<div id="response"></div>
<script>
$(function(){
// When you click the div
$('#button').on('click',function(){
// Fire the ajax to the same page (you may want to do a
// different page in production). Note, I am referencing a new instance of
// of index.php in the background and sending $_POST['test'] = true as noted
// in the data section of the ajax below.
$.ajax({
'url': '/index.php',
'type': 'post',
// Send the data from the click or whatever
'data': {
'test':true
},
// If there are no server errors,
'success': function(response){
// place the phrase 'Ajax done! Here is a random number: 123124'
// back into the placement div
$('#response').text(response);
}
});
});
});
</script>
In this example, the random number will change each click of the div. Anyway hope this example was helpful.

php how to handle hyperlink like a POST instead of GET?

I will have a query that return a set of results, and these results will be in hyperlink form as shown below:
echo "<td><a href='abc.php?cif=" . $row['cif'] . "'>{$row['cif']}</td>";
Now user get to click on this hyperlink and get routed to abc.php?cif=$cif..
My question is, is it possible to only show abc.php to user, just like a POST method, and $cif remains available at abc.php?
As #Flosculus said above, the "best" solution to simulate a post request is doing something like proposed here: JavaScript post request like a form submit
However, despite it's surely a reliable solution, I'm wondering you just don't use sessions instead, something like:
From the page where you set the cif variable:
session_start();
$_SESSION['cif'] = $row['cif'];
In abc.php:
session_start();
if (isset($_SESSION['cif'])) {
// Do what you need
}
EDIT::
Another (possible) solution is setting an hidden input and silently submit a form when you click on an anchor, like this:
From your example, instead of:
echo "<td><a href='abc.php?cif=" . $row['cif'] . "'>{$row['cif']}</td>";
You do this:
When you print all the entries, please add this first (from PHP):
<?php
echo <<<HEADER
<form action="abc.php" method="post" id="submitAble">
<input type="hidden" name="cif" id="cif" value="{$row['cif']}">
<table>
HEADER;
// Get data from your query.. Here is an example:
while ($row = mysli_fetch_assoc($query)) {
echo <<<ENTRY
<tr>
<td>{$row['cif']}</td>
</tr>
ENTRY;
}
echo "</table> <!-- \table collapse --></form> <!-- \form collapse -->";
?>
Then, if you're using jQuery (thing that I'm recommending), simply add an event listener in javascript, like this:
$('.cifSetter').on('click', function(e) {
e.preventDefault();
$('#cif').val($(this).data('cif'));
$('#submitAble').submit();
});
If you don't have jQuery, use this instead:
var cifSetter = document.getElementsByClassName('cifSetter');
for (var i = 0; i < cifSetter.length; i++) {
cifSetter[i].addEventListener('click', function(e) {
e.preventDefault();
var cif = document.getElementById('cif');
cif.value = this.dataset.cif;
document.getElementById('submitAble').submit();
});
}
In both ways, whenever an anchor gets clicked, it will prevent its standard behavior (redirecting) and will instead set the value of an hidden field to the value of the CURRENT "cif" and submit the form with the desired value.
To retrieve the desired value from abc.php, just do this:
$cif = $_POST['cif'];
However, keep in mind that the hidden field is editable by the client (most persons won't be able to edit it, though), therefore you should also sanitize your data when you retrieve it.
Sessions could do it but I'd recommend to just use $_POST. I dont get why you wouldn't want to use POST.

Select box losing selected option when refreshed

I'm trying to create a select box that refreshes its options when selected by the user, but I'm encountering a problem that I can't figure ho to solve.
Being still a beginner with jquery I've already asked an advice for the same program: Keeping selected an option in select dropdown with jquery after refresh.
Following the suggestion now it works almost completely, but I'd like the dropdown to behave exactly as a non dynamic one, keeping the selected option when opened, except for having the options list also refreshed: now it “almost” keeps the value selected (it retains it in the dropdown) but resets to the first option when the element lose focus to others in the page and I don't know how to resolve the problem. I tried to pass a variable with ajax to the php page to have it selected on refresh, but it still resets when focus is change.
The JS code:
$(document).ready(function() {
$("#UsersDiv").focusin(function() {
var UsersSelect = $('#UsersList').val();
$.get(
"userlist.php",
{ UserSelect1: UsersSelect },
function(data) {
$('#UsersList').html(data);
}
);
})
$('#UsersList').val(UsersSelect);
});
The html page:
<div name="UsersDiv" id="UsersDiv">
<select name="UsersList" id="UsersList">
<option value="User1">User1</option>
<option value="User2">User2</option>
</select>
</div>
The php file (the “users” array is in place of the sql query, both work properly):
$UserSelect1 = $_GET['UserSelect1'];
$users=array( 'User1','User2','User3','User4','User5');
echo '<select name="UsersList" id="UsersList">';
foreach($users as $list):
echo '<option value="'.$list.'" ';
if ($UserSelect1 == $list) {
echo 'selected=selected';
}
echo '>'.$list.'</option>';
endforeach;
echo '</select>';
Thanks to everyone for the answers.
$("#UsersDiv")
than you assigning this
$select=$(this) // $select is $("#UsersDiv");
and than you are trying to get val from div
UsersSelect = $select.val() // $select.val() is undefined

Grab checkbox values before form submission

I have the following loop, which shows a checkbox along with an answer (which is grabbed from Wordpress):
$counter = 1;
foreach ($rows as $row){ ?>
<input type="checkbox" name="answer<?php echo $counter; ?>[]" value="<?php echo the_sub_field('answer'); ?>" />
<?php echo $row['answer'];
} ?>
This is part of a bigger loop that loops through a set of questions and for each question it loops through the answers (code above).
How can I grab the checkboxes that the user has checked and display the values within a div before the form is submitted?
I know I can use the following to check if the checkbox is checked:
$('form #mycheckbox').is(':checked');
I'm not sure where to start with all the looping!
You can use the selector :checked
$.each("#mycheckbox:checked", function() {
$("div").append(this.val());
});
You may do something like below:
var divContent = "";
$("form input[type=checkbox]:checked").each(function() {
divContent += this.value + "<br/>";
});
$("div").html(divContent);
Not completely clear to me when this should be executed. From your question it looks to me like that should happen when user clicks on submit button, in such case you just need to place that code into $("form").submit(function(){...});
var boxes = $('input[type="checkbox"][name^="answer"]');
$('#myDiv').empty();
boxes.on('change', function() {
boxes.filter(':checked').each(function(i, box) {
$('#myDiv').append(box.value);
});
});
Get all the matching checkboxes, and whenever one of the checkboxes changes update a div with the values of the checked boxes.
The loop you provide is happening server side, as it is php code. When you wan't to validate the form before submission you must do it on the client, ie using javascript.
So, you will not use the same loop, but rather create a new one that is run when any checkbox is changed.
I suggest you to add a class name to the checkboxes (like class='cb_answer') in the php loop. This will help you to safely select the specific checkboxes when doing the validation.
Here is a script snippet that will add the value of selected checkboxes to a div each time any checkbox is changed. Add this just before </body>. May need to modify it to fit your needs.
<script>
// make sure jQuery is loaded...
$(documet).ready( {
// when checkboxes are changed...
$('.cb_answer').on('change', function() {
// clear preview div...
$('#answers_preview').html('');
// loop - all checked checkboxes...
$('.cb_answer:checked').each(function() {
// add checkbox value to preview div...
$('#answers_preview').append(this.val());
});
});
});
</script>
assuming id='answers_preview' for the div to preview the answers and class='cb_answer' for the checkboxes.

store the option of a selectlist added by jquery into database using PHP

I found a jquery snippet to add and remove options from a select box from box 1 to box 2. This works great. However, when i try to print_r in PHP of the box where the new options are added then it won't show. I cant even see it on the resource after submit. Any solution?
$('#btn-add').click(function(){
$('#select-from option:selected').each( function() {
$('#select-to').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
$(this).remove();
});
});
$('#btn-remove').click(function(){
$('#select-to option:selected').each( function() {
$('#select-from').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
$(this).remove();
});
});
});
and html of the two select lists
<select class="gen" name="selectfrom" id="select-from" multiple size="6" style="width: 150px;">
</select>
<input name="" id="btn-add" type="button" class="add_list" style="vertical-align: top;">
<input name="" id="btn-remove" type="button" class="remove_list" style="vertical-align: top;">
<select class="gen" name="selectto" id="select-to" multiple size="6" style="width: 150px;">
</select>
upon submit i check the $_POST['selectto'] from the selectto box. Any idea's?
EDIT: the foreach in php;
$articles_ary = array();
foreach ($_POST['selectto[]'] as $options)
{
if (!empty($options))
{
$articles_ary[] = $options;
}
}
print_r($articles_ary);
when you POST a select the form submits only the selected option and bare in mind that it must be selected.
with your code you are just adding the options to the selectto, but you're not:
a) chosing one of them (if you want a single value posted)
b) chosing all of them to be posted on the PHP page. (if you want multiple values posted)
in the second case (i thought it's the one you need) you can use this simple jQuery function:
$("#buttonusedtosendform").click(function(e){
e.preventDefault();
$('#select-to option').each( function() {
$(this).attr('selected', true); //with this you select all the option
});
$('formname').submit();
});
bare in mind that if you want to retrieve all the options of a select with PHP you will have to use a little trick by naming the select with square bracket at the end (it's a feature that PHP offer, where it will overwrite the former variable with the latest parsing each one separately):
eg. selectto => selectto[]
this way php will handle it as an array and let you retrieve all the value as if it is one:
foreach($_POST['selectto[]'] as $options){}
When you enter data from one select box to second selectbox, you need to have items selected in second select box to show when you do print_r in php.
For this, after items are added to second select box say with id selectbox2, then you could select all items of second selectbox and then submit the form
for (var i = 0; i < selectbox2.options.length; i++) {
selectbox2.options[i].selected = true;
}
//then Submit form like this, assuming your form name is form1
document.form1.submit();
Hope this helps

Categories