Saving multiple forms to a session without knowing input names - php

<form id="questions_1">
<div data-role="collapsible-set" data-theme="" data-content-theme="" id='q1'>
<!-- GETS QUESTIONS FROM THE DATABASE -->
</div>
</form>
So I have a form that goes on for 5 pages like shown above, and I want to save all the data from each step, I am thinking something along the lines of this to pass all the data for each form into a .php page:
function formSubmit1() {
$("#questions_1").submit(function() {
$.post('addToSession.php',$("#questions_1").serialize().function(data) {
});
return false;
});
}
By adding the following code to each "submit"/next page button I think I can call the function.
<a data-role="button" href="#questions_2" onClick=formSubmit1()>Next</a>
This might need some customization but the part I am really unsure about is how do I get all the data without knowing their id's. The idea is to make the questions in this poll vary in order, size and questions so I need a general code that can handle any input.

Use $_REQUEST to get data from forms on submit. After getting data $_SESSION['name'] = $_REQUEST.

Related

Onblur or onchange check, using a php function in a registration form

I would like to be able to check the text in a text-box after it has changed, and report what is wrong.
It is for a registration form.
This is a part of register.php where
<form action"" method="post">
<ul class="ul-reg">
<li>
<p>Username: </p><input name="username-field" type="text" onblur="someFunction()" /><span id="UsernamehelpText"> </span>
</li>
</ul>
</form>
Then I would have a registerfunctions.php where i would store all the functions for checking lenght,char,maybe regex etc.. Its not really that important what functions i call. I just don't know how to call them.
Form what i have seen the span is where u post the errors, but if there is any other option im open for it, all i want is to be able to post the erorr text in the same line as the text-box
I have checked JavaScript and AJAX, but I am pretty new in this and don't really understand how it works.
After discussion in comments I understand what you want.
First, an explanation. There are two places where validation occurs: In your frontend (your web page) and in your backend (in the PHP script that saves the posted values). Anything that you really don't want to save - for example unescaped SQL strings, too-long fields, and so on - has to be validated in PHP, because it is trivial to get around Javascript validation. For example, nothing is stopping someone from sending a POST to your server containing illegal values without even bothering to visit your webpage.
Even though you need to perform validation in the back-end, it's still user friendly to do the same validation in the front end, so the user doesn't have to wait as long to see an error. This also reduces traffic to your server. Something you probably want to do in a big project is to have some kind of system for writing validation rules centrally, and then using those rules to dynamically generate both PHP and Javascript validation. The advantage of doing that is that you don't duplicate your business rules in two places, but in a smaller project it's probably not worth the hassle.
Validation in the frontend looks about like this: You bind an event handler to an appropriate event or events (you can add onkeydown="validateUserName()" for example, so that the validation reacts a bit quicker), and update your warning text appropriately.
<form action="" method="post">
<ul class="ul-reg">
<li>
<p>Username: </p>
<input id="username" name="username-field" type="text" onblur="validateUserName()" />
<span id="UsernamehelpText"></span>
</li>
</ul>
</form>
<script type="text/javascript">
function validateUserName() {
var userNameElement = document.getElementById('username');
//Do your work: Get the value of the user name field, check
// the values against your validation rules...
var helpText = document.getElementById('UsernamehelpText');
if(isValid)
helpText.innerHTML = "";
else
helpText.innerHTML = "Invalid!";
}
</script>
In the backend, when you process the form, you then have to check the same rules in PHP to prevent illegal values from being posted either maliciously or due to an error in your Javascript. If an error is found, you don't save, instead you can just re-render the form with the submitted values in the input fields and a message indicating what was invalid - this allows the user to change their inputs without losing the values they submitted.
With jQuery it would look something like this:
function someFunction() {
$.ajax({
url: "checkStuff.php",
data: $("input[name='username-field']").serialize,
success: function(data) {
if (data == "correct") {
$("#UsernamehelpText").html("Valid");
} else {
$("#UsernamehelpText").html("Invalid");
}
}
});
}
Your PHP could be something very simple that just checks the validity of the input and then echos "correct" if it is.

How do I create if statements in php to perform a specific action depending on what form has string in it

Im trying to create a grid on my page in each cell there will be a simple one line form. If a person enters data into lets say FieldA I would like the php to perform actionA but if the data was entered in FieldF I would like actionF performed. Is this possible without having to create a php for each cell and upload all those php files?
Or is there a way to perform the GET method in each form to append the data to the end of the action url without the field name showing (ie sample.com/somestuff/fieldA instead of sample.com/somestuff/fieldname=fieldA) thus not needing php at all?
Did you try anything. Please try to write some code. If you get struck paste the code here, somebody will help you out..
In my opinion, why you need different forms. Just have a form which has n text boxes and perform the task that you need.
Your problem is a little ambiguous to me. I'll give it a shot though.
On the form I would set:
`method="post" action="<?php echo $PHP_SELF ?>"`
This will cause the form to submit back to itself. Then at the top of the page you could do something like the following:
<?php
if (isset($_POST["fieldA"]){
performActionA();
} else if (isset($_POST["fieldB"]){
performActionB();
}
etc...
?>
Is that what you are trying to do? Keep in mind php is executed server side before any interaction with the user.
otherwise you could use javascript to change the action field of the form. (Untested)
<script type="text/javascript">
function setAction(elt){
var page = document.getElementById(elt).value;
document.myform.action="sample.com/somestuff/"+page;
}
</script>
<form id="myform" action="sample.com/somestuff/">
<input type="text" name="text1" onchange="setAction('text1')" />
</form>

Strategies for a multi-page form?

I've been trying to make a multi-page poll with jQuery Mobile that is supposed to interact with my MySQL database through Ajax/PHP and have been having issues with it for a while now. It seems I have some problems submitting the form as a result of having it split into several pages. One requirements I need is that the page can not have a page reload.
In my first attempts I tried to divide the pages up into the following:
<div id="page1" data-role="page">
This however failed so many times no matter how I tried to code it. I can not get the submit button to work and I think it could be caused by the fact that I have split the form into several div "pages". I've also tried to make next/submit buttons rather than "Next, next, next ... submit" so that I can store the temporary data in the session, unsuccessfully.
I reworked my whole strategy into a code that hides the question divs that are not active. By this I mean I have one div with data-role set to page, and within it I have several divs with data-roles of content that are hidden/shown by clicking through the form with the next button. I managed to make a small sample form this way that submits the whole form and gets printed out perfectly with some PHP code. However I have yet to successfully validate this version. I can only get my script to validate the last page, and even then it requires ALL checkboxes to be checked, which is pointless. When I tried to implement this version into my real project I could not get it to submit to the .php script at all, but that might just be some syntax error that I will keep looking for.
So, have anyone done anything similar? I'm looking for potential other strategies to solve this issue, or perhaps someone has a theory as to why my aforementioned attemps have failed. Seems Ajax form submits are hard to get working within jQuery Mobile?
Also in case someone can spot a flaw in this I've attached this code that I use for submission, is there an easy way to make this into a function? Or is that pointless?
$(document).ready(function()
{
$("#submit").click(function()
{
var data_string = $('#form').serialize();
$.ajax(
{
type:'POST',
url:'add.php',
data:data_string,
success:function(response)
{
$("#answers").html(response);
}
});
})
});
I also use this function during window.onload to generate the poll with a lengthy .php script. Basically it generates the questions as , every other question variety has only name="answers[question_id]".
function getQuestions(id)
{
var xmlhttp = getHttpRequestObj();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(id).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","poll2.php",true);
xmlhttp.send();
}
The form looks like this:
<form id="form">
<div data-role="content" id="form'.$page.'" class="section">
<fieldset data-role="controlgroup" data-type="vertical" data-mini="true" id="'.$question_id.'">
<input type="checkbox" name="answers['.$question_id.']['.$alt_id.']" id="'.$question_id.'_'.$alt_id.'" value="'.$alt_id.'"/>
<label for="'.$question_id.'_'.$alt_id.'">'.$alt_desc.'</label>
</fieldset>
<input type="button" name="next" value="Next" id="next" onClick="toggleVisibility(\'form'.($page+1).'\')" class="next-btn"/>
</div>
The last page has this code instead of the next button:
</div><input type="button" id="submit" value="Submit" class="submit-btn"/></form>
In my opinion, hiding the other options and open one by one is a better way (also called multi step form).
For validation, you can do it in client side with javascript or use ajax which triggers on appropriate event (you don't need to submit it for validation) and validates in server side.
You are in right track. The issue i see here is how you'l do the validation but that'l depend upon how your form is structured.

Secure solution to hidden forms

I have this code:
<? if ($cur_post['poster_id'] == $forum_user['id']) { ?>
<div class="txt-box textarea required">
<label for="fld<?php echo ++ $forum_page['fld_count'] ?>"><span><?php echo $lang_post['Write message'] ?> <em><?php echo $lang_common['Required'] ?></em></span></label>
<div class="txt-input"><span class="fld-input"><textarea id="fld<?php echo $forum_page['fld_count'] ?>" name="req_message" rows="14" cols="95"><?php echo forum_htmlencode(isset($_POST['req_message']) ? $message : $cur_post['message']) ?></textarea></span></div>
</div>
</div>
<? }
else { ?>
<? } ?>
I need a more secure solution to hidden forms, because currently with this code when I press submit (as an admin) it says I must enter a value for the written message.
I can bypass this using hidden forms under the ELSE bit - but people with any knowledge can just bypass this using Inspect Element or Firebug and then post that value.
I need a more secure solution to this, so that people cannot edit Hidden forms. Do I post the old variable somehow to the form?
It's for a PunBB page (edit.php): http://punbb.informer.com/svn/punbb/tags/punbb-1.3.3/edit.php (original).
Thanks
This is always an interesting problem.
I suggest storing private data in the users $_SESSION with an index unique to the form + page call. I just came into a similar problem at work where I was starting to pass way too much private data through hidden form fields. Now I simply pass a unique id which I use to index the specific private form data in the session.
It's not a 100% solution. Storing the data in the session rather than in the form means a stale form can timeout (ie if the session is killed/timed out), but it's a worth while trade off I think.
I'm not entirely sure I understand the question. Are you trying to control how the form renders, or trying to figure out how to add 'sensitive' data the a form?
First, if you're worried about what parts of the form are being rendered on the page, anything in the else clause would only render if the conditions in the if clause were not true. The else is not 'hiding' part of the form.
Second, there is no such thing as a 'secure' client-side form. Generally speaking, you cannot control what data is submitted to your application, and anyone can submit any POST or GET data they want. Instead you have to handle it on the server-side by properly filtering to ensure that a user has the proper authorization to do what they're trying to do. It sounds like you need to require the user to identify as an admin when the form is processed (most likely through session data).

What is the best way to get jQuery/Ajax to work with CodeIgniter in this example?

I have a problem trying to get CodeIgniter and jQuery to produce ajax functionality. I have been coding all day, learning jQuery, and generally getting my butt kicked. Let me break down the situation, and hopefully, someone will have the courage to help me.
I have a trouble ticket system that displays many tickets on a page... each ticket is nested inside of a multitude of divs like so:
<div class="eachticketwrapper" id="ticket-362">
<div class="actionlog">
<form action="<?= base_url();?>admin/updateticket/362" method="post" id="362" name="362">
<ul class="displayinline">
<p>Action Log:
<span class="actionlog-362">
<?php echo $actionlog; ?>
</span>
</p>
</div> <!--actionlog-->
<p>
<textarea name="actionlogbox362" cols="100" rows="2" id="actionlogbox362" style="" ></textarea>
</p>
<div class="finalbuttons">
<?php echo form_open('admin/updateticket/'.'362'); ?>
<li><?php
$attrib = "class='updatebutton-362' id='updatebutton-362'";
echo form_submit("RapidTask",'Update',$attrib); //setup the button, and set permissions. ?></li>
<?php echo form_close(); // close the form. ?>
</div> <!--finalbuttons-->
</div> <!--eachticketwrapper-->
When run, the $actionlog should resemble something like the following:
worker - 2009-06-25 18:15:23 - Received and Acknowledges Ticket.
worker - 2009-06-25 18:15:23 - Changed Status to In Progress
worker - 2009-06-25 18:15:46 - Changed Priority to High
worker - 2009-06-25 18:15:46 - Changed Category to Network Connection Problem
worker - 2009-06-25 18:17:16 - did something
And then there is a textarea and an update button following it.
Here is the contents of my supplementary jQuery file:
$(document).ready(function() {
$('.updatebutton-362').click(function()
{
var id = $(this).attr("id").split("-"); // Split the id value at the hyphen, and grab the ticketnum.
$('.actionlog-'+id[1]).load('http://localhost/ci/index.php/ajaxtestc/'); // do something...
return false; // return false so default click behavior is not followed.
});
});
the ajaxtestc controller looks like this:
function index()
{
$data['actionlog'] = $this->m_tickets->actionLogPull(362);
$this->load->vars($data);
$this->load->view('content/ajaxtestform');
}
And the m_tickets model looks like this:
function actionLogPull($requestedNum=NULL)
{
$this->db->where('ticketnum', $requestedNum); // Grab only the status for the ticket requested $requestednum=NULL
$requestedTicket = $this->db->get('tickets'); // set the initial ticket info to a variable
$returnvalue = $requestedTicket->row('actionlog');
return $returnvalue;
}
Now... here is what I WANT. I want to click the update button, have it take whatever the worker has typed into the text area, add it to the end of the existing log in the database, and refresh the action log on the screen.
I can't come up with a clear way to do this. Can anyone shed some light on how I could start this process?
Any help is greatly appreciated, and thanks in advance.
Inside $('.updatebutton-362').click, change the .load() line to (replace name, id with whatever parameters you want to send):
$.post('http://localhost/ci/index.php/ajaxtestc/',
{name: "John Doe", id: "anything"},
function(data) {
$('.actionlog-'+id[1]).html(data);
}
});
Then above everything in index() in the ajaxtestc controller, parse the _POST variables and call whatever function you have in your model to update the action log.
Whatever is displayed by the index() action will be loaded into the actionlog span.
First, your code look mess. The first tag seems unclosed, and the form_open is nested inside it.
My rule of thumb to developing a web is, make it work without any javascript first. Then add javascript as better experience.
In your case above, try build the form with old way, after submit, redirect to page you want. After that working well, add jquery one at a time. Use jquery form plugins to submit form. Add a simple checking in the controller to handle ajax request.
I usually use json for form submit, so in controller, I will return a json_encode array to a ajax submitted form request.
Hope this help you.

Categories