Get form checkbox values and pass them through pagination? - php

I need to get values from some selected checkboxes and pass those values through pagination in php/mysql. If on another page user selects other checkboxes, I need to add their values to array selected earlier.
I need this for a product comparison page. In short I need to:
get the checkbox values
store them
include the checkbox values from other pages in pagination
and when user selects "compare" send that array to compare page.
Anybody know how to do this? Related examples would be appreciated?

There are different ways to maintain state across pages, including cookies, session variables, hidden inputs, passing them in the querystring, persisting to database, etc. In this case I would probably use a session variable.
For more info on PHP session see PHP Sessions.

One solution would be to load all of the pages at once in their own divs inside of a form. When you click on a new page link, hide all divs except the one you need to show. That way all checkboxes are submitted in the same form, making it easier to handle server-side. That of course depends on how heavy each individual page is and how many pages there are.
Another solution would be to keep a session variable, tracking what was clicked. Each time someone clicks to go to another page. POST to the server a list of the checkboxes.

You could do it by using javascript to store the checkbox selection in a cookie. Here's some sample code to get you going in the right direction.
var aa_checkbox;
function init_checkbox(){
//setup blank cb cookie
if(!Cookie.read('cb')){
Cookie.write('cb', JSON.encode({}));
}
//setup "associative array" to match what is currently in the cookie
aa_checkbox = JSON.decode(Cookie.read('cb'));
//set up each checkbox with class="remember_cb"
$$('input.remember_cb').each(function(el){
//mark checked if it is in the cookie
if(aa_checkbox[el.name]){
el.checked = 'checked'
}
//setup onclick event to put checkbox status in the
el.addEvent('click', function(){
if(el.checked){
aa_checkbox[el.name] = 1;
}else{
delete(aa_checkbox[el.name]);
}
})
})
//save aa_checkbox back into cookie upon leaving a page
window.onbeforeunload = function(){Cookie.write('cb', JSON.encode(aa_checkbox));};
setup_form();
return true;
}
function setup_form(){
//set up form so that it adds the inputs upon submit.
$$('form.remember_cb_form').each(function(form){
form.addEvent('submit', function(ev){
//clean up previously inserted inputs
var aa_hidden_insert = $$('input.hidden_insert');
$each(aa_hidden_insert, function(el){
el.parentNode.removeChild(el);
})
var el_form = this;
//insert hidden elements representing the values stored in aa_checkbox
$each(aa_checkbox, function(i_value, s_name){
if(i_value){
var el_input = document.createElement('input');
el_input.type = 'hidden';
el_input.value = i_value;
el_input.name = s_name;
el_input.setAttribute('class', 'hidden_insert');
el_form.appendChild(el_input);
}
});
});
});
}
window.addEvent('domready', init_checkbox);
There is a working demo here and a more thorough explanation here

Your pagination links could actually perform a form POST, then read the checkbox[] in ur php script, and update a hidden form element or add the value to a session, anything stateful. so your anchor could look something like
<a href="#" onclick="document.myform.submit()">next&lt/a>

Related

jQuery: Store dynamic form with values and reload on back button

I've Googled and searched on SO quite a bit for this unique problem, but not really finding my exact solution.
I have a basic form with X number of inputs. At some point in the form, the user as the freedom to add inputs via button click if needed. When they submit the form, it goes to another page to collect the posted form data, but I want the ability for the user to click "Back" (or send them back programmatically) if the submit fails.
I have error checking setup prior to submit via javascript, but there are other things (such as a PHP mailer) that could fail and I want them to be able to resubmit their data.
The issue of course is when the browser clicks back, it - at best - refreshes the initial form that was in the DOM with input data, but I lose all of the dynamically added inputs.
I want to capture the form/data in a session and have it repopulate the DOM with the submitted version created by the user on click back.
The closest I've come is doing something like this on SUBMIT:
var theForm = $('#myForm');
sessionStorage.setItem('formData', JSON.stringify(theForm.clone(true).html().toString());
And this on postback/click back:
$('#myForm').replaceWith(JSON.parse(sessionStorage.getItem("formData")));
The problem here is I get my form, but not the data! Do I need to iterate over each input to get my data put back in the recreated form?? Why doesn't it grab the data when .clone(true)ed?
Here's the answer I ultimately got to work.
Upon form validation, I set the session to hold the form data like so:
var theForm = $('#MyForm');
sessionStorage.setItem('formHTML', JSON.stringify(theForm.clone(true).html()));
theForm.find('input,select,textarea').each(function(){
sessionStorage.setItem(this.name,this.value);
});
Then, when the DOM loads again, I have this that checks for the session and populates the form with data if it exists:
$(document).ready(function(){
if (sessionStorage.getItem("formHTML")) {
$('#MyForm').html($.parseJSON(sessionStorage.getItem("formHTML")));
}
$('#MyForm').find('input,select,textarea').each(function(i,elem){
var sessItem = elem.name, sessValue = '';
if (sessValue = sessionStorage.getItem(sessItem)) {
if(elem.type=='radio' && elem.value==sessValue){
alert(elem[i].type+' has value of "'+elem[i].value+'"');
$('[name='+sessItem+']')[i].prop('checked',true);
}
else if(elem.type=='textarea'){
alert(elem.type);
$('[name='+sessItem+']').val(sessValue);
}
else
{
$('[name='+sessItem+']').val(sessValue);
}
}
});
});

get selected checkbox values into jQuery and process to the other page

I need help with the jquery. Im just starting on how to code with jQuery so im kinda newbie. please help me with some solutions,
so far i have this in the markups
<input type='checkbox' data-headmark=".$row['HEAD_MARK']." data-id=".$row['ID']." class='cuttingCheckbox' name='cuttingCheckbox'/>
and the jquery i have so far is just disabling the checkbox once selected,
$('.cuttingCheckbox').change(function() {
if (this.checked) {
this.setAttribute("disabled", true);
}
});
and the page who is going to use the values is the database process,
oci_parse($conn,"UPDATE FABRICATION_QC SET CUTTING = 'Y'
WHERE HEAD_MARK = ".$_POST["headmark"]." AND ID = ".$_POST["headmark_id"].";");
so the idea is sending those two values from checkbox to another page dynamically
Thanks guys for helping me
The answer to this question depends on if you want to send that update to the database life (I.E., right when the checkbox is checked) or on the form submit.
If live, you will use Ajax to immediately post the data. If not live, you will likey (in the jQuery) have to add something like so:
if (this.checked){
this.setAttribute("disabled", true);
var hidden=document.createElement("input");
input.type="hidden";
input.name=this.getAttribute("data-headmark");
input.value=this.getAttribute("data-id");
document.body.appendChild(input);
}
That way, an input of type "hidden" is added so when the form is posted, you can retrieve the variables stored in $_POST. If you need to keep track of what those variables are, you could use a similar method to append to a hidden input with a fixed name.

How to remember form inputs without submit event when page is reloaded or refreshed?

i am having form with many text inputs in a page
along with them i am providing zend pagination to select results.
but when i use zend paginate the user form inputs are lost as it is not submit
as the page reloads evertime i move to a new page is there any way i can maintain the user input .
Please can any one help me find a solution to this problem ..
Pseudo Code:
With javascript get the values on change and store it in a cooke (use jquery cookie plugin)
jQuery('form').on('change', 'input', function() {
jQuery.cookie(...)
})
And the solution is...
AJAX + Session
Send a ajax request on change event of every input.
Save data to Session.
Every time you load form data check for Session to fill form fields.
You can use sessions:
$form = array();
if (!empty($_POST))
{
$form = $_POST;
}
elseif (!empty($_SESSION['form']))
{
$form = $_SESSION['form'];
}
And then use $form to populate the input fields.
You could use ajax onfocusout of elements and store the value in the session.While loading the page fetch the data from the session and show it.

JQuery Mobile, Multiple forms on a page, submit unique form by form id through JQuery Post.

I tried giving all the forms on the page the same form id or individual form id's with a unique.submit function. Neither seemed to work, always only the first form would work all the rest, would just kick me back to the homepage. see my code. code works great on pages with just one form, but when I have multiples it causes problems.
$("#sQuote").submit(function() {
//Send the serialized data to mailer.php.
$.post("mailerS.php", $("#sQuote").serialize(),
//Take our repsonse, and replace whatever is in the "formResponse"
//div with it.
function(data) {
$("#sQuote").html( $("#formResponse").html() );
}
);
return false;
});
});
I tried this with all the form id's = sQuote and the named them individually sQuote1 ect... and added another .submit for that unique ID
For what it's worth, on every single page all used id attributes have to be unique. Having more than one id attribute with the same value will lead to all kind of failure.
Validate your document with the W3 validator and fix the errors as a start. Duplicate ids will be reported as errors there.

beginner Javascript ajax form help

Hello all I'm new to this whole thing still.
I would like some help figuring out how to do this please. I can pull info out of a database and put stuff in using ajax/javascript but I cant figure out how to complete the problem below. I want to be able to make my php form submit and update with out page refresh.
Example.
Page1. Main page
-Drop down
javascript/Ajax on change of dropdown get info from page 2.
Form from page two now displays without page refresh on change of drop down.
When submit button from page two is pressed inserts form data into Mysql database.
Once new data is submitted into sql data base the form updates and shows data in mysql database for the specific ID in the drop down.
Page2.
form drop down info.
Form is filled with info if there is data in the database for it.
Javascript/Ajax on button submit sends input fields to page 3
Page 3.
insert data into mysql using javascript/ajax so no page refresh is required
Thanks
You need to loop through all the input fields in your form, package them into a query string, and send that to your form processing page.
Something like
var queryString = '';
for(var i = 0; i < document.formName.elements.length; ++i) {
queryString += document.formName.elements[i].name + '=';
queryString += document.formName.elements[i].value + '&';
}
//trim off the last '&' here
If you're using select boxes, you'll have to identify them in the loop above and extract their value a little differently. The query string format I used here is for a POST query; in a GET query, you need to append this to the url of the form processing page with a '?'
Consider the following example using jQuery (though you could adapt this to raw js or a different js library):
function doSubmit(event) {
event.preventDefault();
var $this = $(this);
$.ajax({
url: $this.attr('action'),
type: 'post',
data: $this.serilaize(),
success(responseHtml) {
// assume responseHtml is the next form
var newForm = ajaxifiyForm($('form', responseHtml));
$this.unbind('submit').replaceWith(newForm);
}
});
return false;
}
function ajaxifyForm(form) {
return $(form).submit(doSubmit);
}
$(document).ready(function(){
ajaxifyForm($('#your-form'));
});
Here we rely on the first page load to have the form already included on the server side. When the DOM is ready we attach an event handler to the submit event of the form. This handler overrides the normal submission process and instead uses ajax. It submits to the URL we specified in the action attribute.
When a post is successful it takes the HTML response from that post and replaces the original form with it after applying the same handler we used on the original form. This relies on the assumption that the php script(s) we are posting to always return the next form with all its values filled out.
Keep in mind you can submit file data in this way. Youd need to use an iframe as an intermediary to do that (there are other ways to do this as well that doesnt use an iframe). you can google ajax file upload for solutions to that problem.

Categories