Load array from inputs to PHP with jQuery .load()? - php

Ok, I've been looking and looking for about 2 weeks now and I've yet to find exactly what I need to figure out, so now is the time to ask the experts!
I'm working on an advertising management system and one of the parts of the request form is to select start and end dates for an ad. The user is given an option of adding more dates.
So, there are two inputs that are there initally...
<input type="text" name="startDate[]" id="startDateInput">
<input type="text" name="enddate[]" id="endDateInput">
Then, under that is an option to dynamically add more inputs.
When the user adds more inputs, it just copies those initial inputs, so we end up with more instances. For example:
<input type="text" name="startDate[]" id="startDateInput">
<input type="text" name="enddate[]" id="endDateInput">
<input type="text" name="startDate[]" id="startDateInput">
<input type="text" name="enddate[]" id="endDateInput">
Is there a way to send the results of these inputs as an array using .load()?
I have it sending and displaying the info for one set of inputs with the code below...
var startDate = $("#startDateInput").val();
var endDate = $("#endDateInput").val();
$("#adBooking").show().load('../scripts/checkSpots.php', { startDate: startDate, endDate: endDate});
I guess I just don't 100% understand how to do this. I've been racking my brain for the past two weeks but I can't find anything totally relevant to what I'm doing.
But, what I need to do is make an array of data out of all the startDate and endDate inputs and then throw it through the .load() and into the checkSpots.php page and have it display the information for each set of start/end dates.
Is there a different way of doing this? Maybe a more efficient way? Or, if anyone can shed a bit of light on this broken jQuery noob, I'd greatly apprecaite it! :D

demo: http://jsbin.com/etihaw/3
$(function() {
$("#add-date").click(function(e) {
var i = $('.end-date').length + 1;
$('<p class="dates">' +
'<input class="start-date" name="startDate[' + i + ']" id="startDate' + i + '" />' +
'<input class="end-date" name="endDate[' + i + ']" id="endDate' + i + '" />' +
'</p>').insertAfter('.dates:last');
e.preventDefault();
});
$('#my-form').submit(function() {
var post_data = $(this).serialize();
//$("#adBooking").show().load('../scripts/checkSpots.php', post_data);
alert(post_data);
return false;
});
PHP
<?php
foreach($_POST['startDate'] as $key => $val ) {
echo $key; // 1
echo $val; // 07/12/2011
}
foreach($_POST['endDate'] as $key => $val ) {
echo $key; // 1
echo $val; // 09/12/2011
}
?>

First things first, ID's need to be unique, so when a new date pair is added, append a qualifier on the end of the id:
<input type="text" name="startDate[]" id="startDateInput1">
<input type="text" name="enddate[]" id="endDateInput1">
<input type="text" name="startDate[]" id="startDateInput2">
<input type="text" name="enddate[]" id="endDateInput2">
Or better yet, use a class:
<input type="text" name="startDate[]" class="startDateInput">
<input type="text" name="enddate[]" class="endDateInput">
<input type="text" name="startDate[]" class="startDateInput">
<input type="text" name="enddate[]" class="endDateInput">
Then you can apply some jQuery voodoo whenever you'd like (button click, submit, etc):
$('#myButton').click(function(){
// Our ajax post data. For example, $_POST['startDates'][2] would
// give you the 3rd start date in your php file.
var data = {
startDates: new Array(),
endDates: new Array()
};
// Loop through each date pair, extract its value, and add it to our post data
$('.startDateInput').each(function(){
data.startDates.push(this.val());
});
$('.endDateInput').each(function(){
data.endDates.push(this.val());
});
// Load it!
$('#result').load('doSomething.php', data);
});
Note: Above code is not tested, just an example of one possible solution.
Hope that helps. Oh, and obligatory Family Guy reference.

There is a major flaw in your logic: Any id attribute must be unique in the document. As you use several id's more than once, it will not work or give unexpected results at best.

First, you shouldn't use the same id on multiple elements within a single html page. That's going to cause all sorts of unpredictable behavior. Use class instead so:
<input type="text" name="startDate[]" class="startDateInput">
<input type="text" name="enddate[]" class="endDateInput">
<input type="text" name="startDate[]" class="startDateInput">
<input type="text" name="enddate[]" class="endDateInput">
Then you need to query for all the input elements using jquery loop through each element and assign its value to the appropriate array.
var myEndDateArray = [], myStartDateArray = [];
$(".endDateInput").each(function() {
myEndDateArray.push($(this).val())
});
$(".startDateInput").each(function() {
myStartDateArray.push($(this).val())
});
Finally, you must post the array data to your page in a compatible post format.
$("#adBooking").show().load('../scripts/checkSpots.php', { 'startdate[]': myStartDateArray, 'enddate[]': myEndDateArray});

I bumped int this problem lately, and I found aSeptik solution is very useful.
But there is a mistake in it. From jQuery documentation:
Request Method
The POST method is used if data is provided as an object; otherwise,
GET is assumed.
Since the result of the .serialze() function is string the .load() methode will use GET.
JS code (same):
$(function() {
$("#add-date").click(function(e) {
var i = $('.end-date').length + 1;
$('<p class="dates">' +
'<input class="start-date" name="startDate[' + i + ']" id="startDate' + i + '" />' +
'<input class="end-date" name="endDate[' + i + ']" id="endDate' + i + '" />' +
'</p>').insertAfter('.dates:last');
e.preventDefault();
});
$('#my-form').submit(function() {
var post_data = $(this).serialize();
//$("#adBooking").show().load('../scripts/checkSpots.php', post_data);
alert(post_data);
return false;
});
PHP script with _GET:
<?php
foreach($_GET['startDate'] as $key => $val ) {
echo $key; // 1
echo $val; // 07/12/2011
}
foreach($_GET['endDate'] as $key => $val ) {
echo $key; // 1
echo $val; // 09/12/2011
}
?>

Related

Using AJAX to pass variable into PHP array

I have looked around various other questions relating to this topic but I am still struggling to find a solution to my query.
In my system I am allowing the admin to append extra form nodes to the file so they may input any extra required data, this data is then submitted to the DB to generate pages in the main portion of the site.
I am new to the concept of passing the data back via AJAX so I may be misunderstanding something but here is my code.
Add Node Control
<div id="nodeControl">
<div id="addNode">
<a id="nodeLink" href="#">+</a>
</div>
</div>
<div id="slideOut">Click to add a new section</div>
Add Node click response function
var nodeCount = 2;
$("#nodeLink").click(function(){
// Local Variables
var newSection = '<br/><div id="sectionInfo"><div id="sectionWrap"><div id="sectionInner"><label class="inst head">Section ' + nodeCount + '</label><input class="textOver" type="text" name="sectionTitle' + nodeCount + '" value="<?php $title; ?>"> <label class="inst ib">Please enter any text you would like associated with the section.</label> <textarea style="margin-top: 3px" name="sectionContent' + nodeCount + '" value="<?php $body; ?>"></textarea> <label class="inst ib">Please upload the image associated with this section, .PNG reccomended.</label> <input type="file" style="visibility:hidden;" name="img' + nodeCount + '" id="upload" /> <input type="button" id="fileStyle" class="fSOver" value="Upload Pump Image!" /> </div> </div> </div>' ;
// Append the new section to the document and increment the node count
$('#sections').append(newSection);
nodeCount += 1;
// Call AJAX to pass to PHP
$.ajax({
type: "POST",
url: "../section.php",
data: { setSection : newSection },
success: function() {
alert("Success, ajax parsed");
}
});
$(".successDiv").slideDown(150);
$(".successDiv").delay(1500).slideUp(150);
return false;
});
Node count is instantiated to "2" here, when a node is added the number is appended to the name attribute of any input elements on my form i.e. header2, header3 etc.
This is so when my form is eventually submitted I can loop through each data field and submit it to the database.
As I currently understand the AJAX data variable uses key pairs { a : b } where a = return key and b = return value, I want PHP to be able to access that returned value and store it into an array which can be looped through at the end.
Currently the success message is triggered on my AJAX call but I am unable to access the values in PHP, instead I am thrown an "Undefined index of sections defined".
$section = array();
$setSection = $_POST['setSection'];
$section[] = $setSection;
PHP won't store every setSection variable you pass it over time; each time your script is called, its variables are reset. You probably want to store the variable in a database or session variable.
Here's one approach, using session variables:
session_start(); // unless you already started one
if (!isset($_SESSION['section'])) {
$_SESSION['section'] = array();
}
array_push($_SESSION['section'], $_POST['setSection']);

Change text input values dynamically

My question might be quite easy for you guys, but it's hard for me...
I have a text field and I want to change its value between once <label id="some_id"> is clicked. Until what I've described now, I can do it myself with jQuery, but here comes the complex part (for me, obviously):
I have two values I want for that text field, and once that <label> is clicked, it switches to the value that isn't shown, but once we click it again, it goes back to the original text the text field contained.
I have to keep my jQuery/JS internal because I get the desired values from the database and I don't want to make my .js files .php.
This is what I got:
<label for="html" onclick="$('#html').val('<?php echo $image->convert('html_b', $image_data['image_link']); ?>')">HTML:</label>
<input type="text" id="html" value="<?php echo $image->convert('html_a', $image_data['image_link']); ?>" readonly />
It does the first part I need, changing the value of the field to the new value, but once that button gets clicked again, I want the original text.
Thank you.
You can compare its current value to the available possibilities.
<label id="toggle" for="stuff">I'm a label</label>
<input type="text" val="" name="stuff" id="stuff">​
var possibilities = ["foo", "bar"];
$('#toggle').click(function(){
var old_val = $("#stuff").val(), new_val;
if (old_val == possibilities[0])
new_val = possibilities[1];
else
new_val = possibilities[0];
$("#stuff").val(new_val);
});​
demo
First, don't use inline JavaScript.
You can use a combination of .toggle() and data-* attributes for this. For example, using a data-toggle attribute for the value you want to toggle with.
<label for="html" data-toggle="This is a placeholder">HTML:</label>
<input type="text" id="html" value="This is my real value" readonly>​
$("label[for][data-toggle]").each(function() {
var $this = $(this);
var $for = $("#" + $this.attr("for"));
var originalValue;
$this.toggle(function() {
originalValue = $for.val();
$for.val($this.data("toggle"));
}, function() {
$for.val(originalValue);
});
});​
See it here.
UPDATE #1
I added usage of for attribute of <label>.
UPDATE #2
If you don't want to use .toggle() due to the deprecation notice.
$("label[for][data-toggle]").each(function() {
/* cache */
var $this = $(this);
var $for = $("#" + $this.attr("for"));
var originalValue = $for.val();
/* state variable */
var which = 0;
$this.click(function() {
$for.val(which ? originalValue : $this.data("toggle"));
which = 1 - which;
});
});​
See the non-.toggle() alternative here.
For doing this, on the first button click you need to store the current value of input in some variable and then on 2nd click you can assign that variable to input value. If you donot want to have js file, you can simply use <script></script> tags to write the jquery.
`<label id="label" onclick="replaceText('newvalue')">Click Mee</label>
<input id="html" type="text" value="some value">
<script>
var currentValue="";
function replaceText(newval){
currentValue= $("#html").val();
if(currentValue!=newval)
$("#html").val(newval);
$("#label").attr("onclick","replaceText('"+currentValue+"')");// Here we assigned the other value to label onclick function so that it will keep on toggling the content.
}
</script>`
DEMO HERE
You can store the values into JavaScript variables and use jQuery click method instead of onclick attribute.
var def = "<?php echo $image->convert('html_a', $image_data['image_link']); ?>",
up = "<?php echo $image->convert('html_b', $image_data['image_link']); ?>";
$('label[for=html]').click(function() {
$('#html').val(function(i, currentValue) {
return currentValue === def ? up : def;
});
});

how to remember input data in the forms even after refresh page?

what to do in order to make the form remember the previous input or the current input of the user even after he/she refreshed the page ?
should I do ,
<div class="row">
<label>Contact Messenger </label>
<input type="text" name="messenger" id="messenger" size="50" maxlength="50" value="<?php echo $_SESSION['messenger']; ?>"/>
</div>
or
<div class="row">
<label>Contact Messenger </label>
<input type="text" name="messenger" id="messenger" size="50" maxlength="50" value="<?php echo $_POST['messenger']; ?>"/>
</div>
or
there's a trick to do it ?..how ?
on the page where your form is submitting do something like this
session_start();
$_SESSION['data'] = $_POST['data'];
$_SESSION['data_another'] = $_POST['data_another'];
and than you can access those session variables any where like this
session_start(); // this should be at the top of the page before any html load
<input type="text" name="name" value="<?php echo $_SESSION['data'];?>"/>
refresh your page on success call like this
$.ajax({
type: "POST",
url: "yourfile.php",
data: 'data='+ data,
success: function(){
location.reload();
}
});
I had similar issue at one of my project so I wrote some js to handle this using cookies.
First I found two simple functions to set and get cookies values:
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) {
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1) {
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1) {
c_value = null;
} else {
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1) {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start, c_end));
}
return c_value;
}
Than I wrote two other functions to set and get input values:
function saveValue(input) {
var name = input.attr('name');
var value = input.val();
setCookie(name,value);
}
function getValue(input) {
var name = input.attr('name');
var value = getCookie(name);
if(value != null && value != "" ) {
return value;
}
}
And using jQuery I save user's input value to session cookie
$('input[type=text]').each(function(){
var value = getValue($(this));
$(this).val(value);
}).on('blur', function(){
if($(this).val() != '' ) {
saveValue($(this));
}
});
I hope it'll help ;)
That quite depends on where the data in the fields is coming from.
If your scenario is that you are presenting a blank form, the user enters some data and then without submitting it, refreshes the page, there is nothing you can do. That's up for the browser to handle.
You might be able to do some very weird JavaScript hacking there, but I would not suggest that.
On the other hand, if your data is coming from a previous page or something like that, that's a different story. But then you need to tell us where the data is coming from, so I can give you a reasonable answer.
If you mean, filling out form fields and clicking refresh, then there is no direct way, as the data isn't submitted. That sort of behavior is up to the browser.
The only thing you could do is post the data via AJAX back to your server as the fields change. Your PHP script receiving the data would set some session variables. When the form loads, you would set their default values to the appropriate session values.
Rarely though is there a need for this kind of behavior. There will be many requests sent back and forth to your server.
Session is a good way to store and remember data but why complicate things? Consider if the form has many fields, developer has to store lots of values in session. Why not simply print or echo.
Example:
Form is submitted with input ssName and hidden field ssAct with value of send
Get the ssName and ssAct on form submit
$ssAct=$_REQUEST["ssAct"];
$ssName=$_REQUEST["ssName"];
and the form
<input type="text" name="ssName" value="<?php if($ssAct=='send' && $ssName!='') { echo "$ssName"; } ?>">
<input type="hidden" name="ssAct" value="send">
On submit name will be echoed if it was submitted and was not empty.
None of your suggestions will help you "remember" data after a refresh (action that not send data to the server). What you need is to grab data via javascript (maybe with onkeyup events type) and grab it using cookies. With jquery is very easy.
There are some main issues to check in order to get the data appear after refresh or any event handler:
1) Be aware of the signature. it must contain the method="post" attribute as follows:
<form method="post"/>
else the using of the $_POST['messenger'] will not work.
The default value of the method attribute in the form is get.
<form> equals to <form method="get">
2) Many programmers mix between the attributes id vs name.
Be aware of using the correct attribute. The $_POST associative array is using the name to get data from it. That is why the next example will not work correctly:
<input type="text" id="data" value="<?php echo isset($_POST['data']) ? $_POST['data'] : "" )?/>"
To get it work right you must add the attribute name="data" as follows:
<input type="text" name="data" id="data" value="<?php echo isset($_POST['data']) ? $_POST['data'] : "" )?/>"
Good luck
You could also do without session like the below code:
<input type="text" name="Fname" value="<?php if(isset($_POST['Fname'])){ echo $_POST['Fname']; } ?>" /><br/>
This will keep the typed data inside the input box!
after posting your details to session, write like this in value
<?php print $_SESSION['messenger'] ?>
if you are writing both php and HTML in same file then you can do like this
<?php print $messenger] ?>
try the attribute autocomplete, maybe it will work on some browsers...
<input type="text" autocomplete="on" />
You can use autocomplete for a form too.

How to pass a javascript variable to PHP

Im creating a dynamic form with a button called "Add more rows" when this is clicked a JavaScript function creates a new row of textboxes with the appropriate id.
The problem is, how do I pass a counter variable from my JavaScript function to my next php page so it nows how many rows of textboxes to receive $_POST.
Ive got my JavaScript function however I'm missing data from the rows it creates itself.
any ideas?
Thanks
This is my js function
window.onload=function()
{
inp=document.getElementsByTagName('input');
for(c=0;c<inp.length;c++)
{
if(inp[c].value=='add')
{
inp[c].onclick=function()
{
n=15;
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='time'+n;
document.getElementById('txtara').appendChild(x)
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='event'+n;
document.getElementById('txtara').appendChild(x)
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='supplies'+n;
document.getElementById('txtara').appendChild(x)
var sel = document.createElement('select');
y = document.createElement('option');
y.value = 'Yes';
y.name = 'success' + n;
y.innerHTML = y.value;
x = document.createElement('option');
x.value = 'No';
x.name = 'success' + n;
x.innerHTML = x.value;
sel.appendChild(y);
sel.appendChild(x);
document.getElementById('txtara').appendChild(sel);
document.getElementById('txtara').appendChild(sel);
document.getElementById('txtara').appendChild(sel);
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='comment'+n;
document.getElementById('txtara').appendChild(x)
document.getElementById ('txtara').innerHTML += '<br>';
n++;
}
}
}
//-->
}
You should add an <input type="hidden" name="num_rows" value="0"> to your form and update its value to be the row count when the form is submitted.
Assuming you want the number for easing the way you fetch the data on the server side.
There is a very simple way of doing this.
Let's say you have many input's of the same logical data type you want to handle, like:
<input type="text" name="names" value=""> And you create more of it dynamically.
Of course, you want them individual names to fetch the data, so you do like:
<input type="text" name="names[]" value=""> OR if you have more input for one entity, to make it consistent: <input type="text" name="names[1]" value=""><input type="text" name="eye_colours[1]" value=""> , so you can add a number in the brackets.
What do you do on the PHP side?
if( isset($_POST['names']))
foreach($_POST['names'] as $key => $val){ ... }
PHP parses it as an array, hurray! :)
You can add a name attribute to your form elements. As your form contains multiples elements (and you don't know how much elements), this name attribute must be in the form "my_name[]". The [] chars indicates a collection of elements. So your HTML code could look like this:
<form method="POST" action="mypage.php">
<input type="text" name="whatever[]" value="first" />
<input type="text" name="whatever[]" value="second" />
<input type="text" name="whatever[]" value="third" />
<input type="submit" />
</form>
Then, when the form will be submitted, you can get the values using the PHP variable $_POST['whatever']. This variable is an array and contains all the values of the "whatever" inputs like this:
$myValues = $_POST['whatever'];
// $myValues = array( 0 => "first", 1 => "second", 2 => "third" );
Then, if you want to do some actions with each rows, do a for each loop. If you want to know how many lines were submitted, you can simply do a count.
Since javascript is a client-side language, this is not possible :(
but, you can use AJAX to send a local javascript var to the server by GET, or POST
You can use PHP to output javascript code. If you have a value you can output it directly in javascript, or if you have a more complex value, you can encode it using json_encode.
You don't need to. POST will carry the number of rows for you without a problem. Simply do count($_POST) to get the number of values posted. Or, if you use my suggested version below, use count($_POST['time']) to get the number of time values.
var types = ['time', 'event', 'supplies'];
function createInput( i, n )
{
var base = isNaN( i )? i: types[ i ];
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name= base + "[" + n + "]"; // this will make $_POST[<base>] an array with n as the index.
document.getElementById('txtara').appendChild(x)
}
window.onload=function()
{
inp=document.getElementsByTagName('input');
for(c=0;c<inp.length;c++)
{
if(inp[c].value=='add')
{
var n = 15; // move n out here. Otherwise n will always = 15.
inp[c].onclick=function()
{
for( var i = 0; i < types.length; i++ )
{
// passing both variables in will avoid any possible collisions.
createInput( i, n );
}
var sel = document.createElement('select');
sel.name = 'success[' + n + ']';
y = document.createElement('option');
// option has no name attribute (http://www.w3schools.com/tags/tag_option.asp)
y.value = 'Yes';
y.innerHTML = y.value;
x = document.createElement('option');
x.value = 'No';
x.innerHTML = x.value;
sel.appendChild(y);
sel.appendChild(x);
// you had this three times... why?
document.getElementById('txtara').appendChild(sel);
createInput( 'comment', n );
document.getElementById ('txtara').innerHTML += '<br>';
n++;
}
}
}
}

PHP jQuery validation

Been struggling with this for a couple days now. Here's the set up - I have a parent page "support.php" there are tabs, and when you click a tab it brings in the appropriate form via ajax.
(the relevant code for each section:)
form input's on the AJAX page
<input type="text" class="numbers" name="captchaImage" id="SupportNumbers" size="6" value="" readonly>
<input type="text" class="numbers" name="SupportMath" id="SupportMath" size="6" maxlength="6" tabindex="9">
The parent page - support.php calls for "validation.js" which is my jQuery.validate script.
...
SupportMath: {
required: true,
equal: "<?php echo $randomNumTotal; ?>"
}
There is a .get command on the parent page for a file "random.php"
$.get('PHP/random.php', function (data){
$("#SupportNumbers").val(data);
});
<?php
$randomNum = rand(0,9);
$randomNum2 = rand(0,9);
echo $randomNum ."+". $randomNum2;
$randomNumTotal = $randomNum + $randomNum2;
?>
which generates two random numbers so you can add them together. The validation checks to make sure
the two numbers that are generated are added correctly. I just can't seem to get all these pieces to use the same numbers, i can get the text box "SupportNumbers" to populate with two random numbers say "2 + 5" but when I enter "7" into "#SupportMath" it displays the error msg. It should be $randomNumTotal but I can't get that to the page, and have the validation script check against that.
HELP.
I realize this is clear as mud so ill try and explain more
I have 5 forms on my support page. To reduce the chaos, I have them in a vertical tab set. I don't want my js validation script on the page and I don't want all 5 forms hidden/displayed on the page due to some issues we've had with some bots. So my solution was to bring in the forms with AJAX (done) and just link to the validation script (done) all is good except for our "random math captcha" I can put it in a file and use the ".get" command to populate the box that holds the two random math questions, but can't get the answer to validate. Hope this helps, code below.
EXPLANATION: ( step by step )
we use your method to generate two random number from 1 to 9 at page load
we have added an extra input <input type="hidden" name="math" id="math"/> this field is needed since you are using a readonly field, now the readonly fields are not submitted...by forms, this way we have the one shown to user and another one hidden, this one will be submitted;
we get the #math value that is a string ex: 5+2 so we need to transform this into two int and sum it.
finally we make the check the SUM against the user input #SupportMath
DEMO: https://so.lucafilosofi.com/php-jquery-validation/
PHP ( that check the match against... )
if ( isset($_POST['post']) ) {
$math = explode('+',trim($_POST['math']));
$sum = ( (int)$math[0] + (int)$math[1] );
$message = 'error';
if ( (int)$sum === (int)$_POST['SupportMath'] ) {
$message = 'success';
}
echo $message;
}
jQuery ( pseudo code...)
$(function() {
$.get('random.php',function(data) {
$("#SupportNumbers,#math").val(data);
});
$('#form').submit(function(e) {
e.preventDefault();
var query = $(this).serialize();
$.ajax({
type: "POST",
url: "post.php",
data: "post=post&" + query,
success: function(msg) {
if (msg.indexOf('success') == -1) {
alert('error');
} else {
alert('cURL');
}
}
});
});
});
HTML
<input type="text" class="numbers" name="captchaImage" id="SupportNumbers" size="6" readonly>
<input type="hidden" name="math" id="math"/>
<input type="text" class="numbers" name="SupportMath" id="SupportMath" size="6" maxlength="6" tabindex="9">
Here's a self-sufficient version of what I was referring to.
<?php
session_start();
if (isset($_GET['validate']))
{
$passed = (session_is_registered('validate') && (int)$_GET['validate'] == $_SESSION['validate']);
header('Content-Type: application/json');
echo sprintf('{"validation":"%s"}', $passed?'OK':'FAIL');
exit;
}
function generate_check()
{
// generate a result (incompleted)
$result = Array(
'num1' => rand(0,10), // first random number
'num2' => rand(0,10), // second random number
'problem' => null, // actual math problem
'answer' => null // the answer
);
// random method
switch (rand(0,999) % 3)
{
case 0: // addition
$result['problem'] = sprintf('%d + %d',$result['num1'],$result['num2']);
$result['answer'] = $result['num1'] + $result['num2'];
break;
case 1: // subtraction
$result['problem'] = sprintf('%d - %d',$result['num1'],$result['num2']);
$result['answer'] = $result['num1'] - $result['num2'];
break;
case 2: // multiplication
$result['problem'] = sprintf('%d * %d',$result['num1'],$result['num2']);
$result['answer'] = $result['num1'] * $result['num2'];
break;
}
return $result;
}
$check = generate_check();
session_register('validate');
$_SESSION['validate'] = $check['answer'];
?>
<html>
<head>
<title>Sample Validation</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<Script type="text/javascript">
$(function(){
$('#check').click(function(){
$('#result').css('color','').text('Checking...');
$.getJSON('<?php echo $_SERVER['PHP_SELF']; ?>',{'validate':$('#answer').val(),'_':(new Date()).toString()},function(data){
if (data.validation=='OK')
$('#result').css('color','green').text('PASSED!');
else
$('#result').css('color','red').text('FAILED!');
});
});
});
</script>
</head>
<body>
<p>What is <b><?php echo $check['problem']; ?></b>?</p>
<input type="text" name="answer" id="answer" /><input id="check" type="button" value="Check" />
<p id="result"></p>
<br /><br />
<form action="<?php echo $_SERVER['PHP_SELF']; ?>"><input type="submit" value="New problem" /></form>
</body>
</html>
I used to do pages like this until I found this wonderful inline Jquery validator You simply add a class with relevant information to your form objects and it does the rest. There's no need to fool around with redirecting or sessions for that matter. I've had it in production on about 25 sites for nearly a year without any issues whatsoever.
Edit: looks like you're trying to do a Captcha of sorts, maybe? Perhaps look at ReCaptcha which not only verifies a user is correct, but also helps improve OCR. Alternatively, you could do a slidelock
As we say in my shop, "No reason to go off and write a minivan...."

Categories