I'm using the CodeIgniter PHP framework. I have a simple form that has an $editcode hidden variable that gets sent on form submit. The form submits data to a form processing function which then redisplays the view with the form again, however with the $editcode$ variable changed to a new value.
The problem is that no matter what I do, the value of $editcode remains the same as the original value even after the form is submitted and the view redrawn with a new $editcode variable.
Extract from my view showing how $editcode is included and submitted.
echo form_open('/add', $formattributes);
echo form_hidden('editcode', set_value('editcode', $editcode));
echo form_submit('submit','Submit!','id="submit"');
The add() function code (the $refreshed_editcode is positively different from the original $editcode that got generated).
...
$data['editcode'] = $refreshed_editcode;
$this->load->view('includes/template', $data);
When the view gets redrawn by the add() function, the $editcode value should be $refreshed_editcode, but instead it's still the original value.
I know CodeIgniter does some caching of variables for nested views, however in this case I am explicitly resending new values for the $editcode variable. What gives?
Try getting rid of the call to set_value. Since the form field is hidden, it really shouldn't give you much benefit anyway, and I suspect that is where the "caching" is happening (If I'm not mistaken that function is part of the form_helpers file and it actually is designed to cache to help re-populate data, but it has been a while since I've used it).
Related
I'm stuck with a php/mySQL thing..
I have a dynamically created form and I want to parse the $_POST variables it generates. To be specific,I have a query in SQL which generates the fields in my form. Then, I need to process these variables in the php file, where the action of the form goes.
However, I cannot parse the dynamically created $_POST variables. Below is my code:
$sql="just-a-query";
$result = mysql_query($sql);
while ($data = mysql_fetch_array($result)) {
${''.$data['parameterName']}=$_POST[$data['parameterName']];
}
For example, if I have 3 variables that got through the form the values:
house=1
tree=3
car=2
I would like to save them via php like this:
$house=$_POST['house'];
$tree=$_POST['tree'];
$car=$_POST['car'];
However I can't get through it. It returns Undefined index error. Any thoughts?
If you want to find if a variable is defined before using it, it's as simple as using isset():
if( isset($_POST[$data['parameterName']]) ) {
${''.$data['parameterName']}=$_POST[$data['parameterName']];
}
If on the other hand, it's supposed to be defined (you see the form element), but then it's not getting defined in the postback. First check to make sure that your form submission type is post, then check to make sure you are using the name attribute in the form elements.
thank you for your time. My problem was that I was parsing wrong parameters from the HTML.
Yes, I'm an idiot and yes, var_dump() helped me to figure my error.
Thanks again!
btw, my code was working perfectly. Ha!
NEW INFORMATION:
I used the print_r function on the $_REQUEST and something very strange is happening there too. Some values are being correctly passed by the GET such as a value on another form which passes in "TRUE". This can be seen in the print_r output but isn't written to the file... Still no closer to finding a solution to my problem however.
I'm working on a page with a lot of forms which are loaded in as needed by AJAX. This all works fine as does parsing the name:value pairs and storing them appropriately.
My error happens when the PHP parses the GET request sent by AJAX when the user is finished, it only seems to retrieve the values from certain fields.
The idea is that the user can add data from any number of forms, which are then turned into a GET request and sent to the server.
The JavaScript is building my request perfectly and all forms are sent correctly.
Depending on the forms the user submits, the data is processed by a large switch statement which passes the relevant names to a variadic function which grabs the values, and creates a string for writing to a file.
The strange error is that only some values get written to the file with others only having a blank line. No error reported by Apache or PHP, no error reported in the JavaScript console either.
I'll use the Colour form for example as this is one of the more complex.
So I add a colour action and click the button to submit all forms (this time, it's just the colour form though)
My get request looks like this:
actionIDs=Colour&coOptionSelect=Tinting&coColourEffect=Sepia&coRemoveColour=#000000&coRemoveFuzzNumber=0&coRemoveHueSelect=None&coReplaceColour=#000000&coReplaceFuzzNumber=0&coReplacementColour=#000000&coReplacementAlphaNumber=0&coReplaceHueSelect=None&coReplacementHueSelect=None
Next, the PHP parses the actionIDs part as sometimes, there will be many actions. This works fine.
We now jump to the Colour part of the switch statement.
case "Colour":
$config = processAction("coOptionSelect", "coColourEffect", "coRemoveColour", "coRemoveFuzzNumber", "coRemoveHueSelect", "coReplaceColour", "coReplaceFuzzNumber", "coReplacementColour", "coReplacementAlphaNumber", "coReplaceHueSelect", "coReplacementHueSelect");
file_put_contents($confpath . "colour.conf", $config);
break;
That writes to the correct file, but strangely, only coOptionsSelect and coColourEffect have their values written to the file. It isn't their input type as they are select statements similar to the other selects on the form. On other forms, it may be a number input or a text input that submits properly instead.
It isn't random either, the same ones will always write out properly. It also isn't positional as I moved around the values and it's still the same ones that write correctly, their position doesn't affect anything.
Finally here is processAction function.
function processAction()
{
$config = "";
foreach(func_get_args() as $field)
{
$temp = isset($_REQUEST[$field]) ? $_REQUEST[$field] : null;
$config = $config . $temp . "\n";
}
return $config;
}
The end result should be all values should write to their relevant files correctly, rather than the current issue where only a few values from each form are written, with the rest of the values being written as blank lines.
You probably need to encode your # sign to a encoded method %23
you could also use urlencode to do it before passing it to your variable.
Reference: http://php.net/manual/en/function.urlencode.php
Update:
If you are going to try to encode through javascript I would try and use this method
var newURL =
"http://example.com/index.php?url=" + encodeURIComponent(actionIDs);
or
var newURL =
"http://example.com/index.php?url=" + escape(actionIDs);
Reference: Encode URL in JavaScript?
You have three options:
escape() will not encode: #*/+
encodeURI() will not encode: ~!##$&*()=:/,;?+'
encodeURIComponent() will not encode: ~!*()'
But in your case, if you want to pass a URL into a GET parameter of other page, you should use escape or encodeURIComponent, but not encodeURI.
See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.
This may be a n00b topic but, anyways, I have been having a rather difficult and strange time with this bug. Basically I was working on a controller method for a page that displays a form. Basically, I was debugging the form's submitted data by var dumping the form input using codeigniter's $this->input->post function like so:
var_dump($this->input->post('first_name'));
Every other day this has worked, but today I was finding that when I dumped post variables to the browser it would return false as if they had no values even though they did have values when I submitted the form. Then I tried accessing the variables through PHP's POST superglobal array directly like so:
var_dump($_POST['first_name']);
and that returned empty as well so then I tried dumping the entire post array like so:
var_dump($_POST);
and it was empty as well despite the fact that I filled out the entire form. Nevertheless, the records in my MySQL database were being updated (which means that the form was submitting even though my $_POST variables appeared empty).
Also, I reasoned that normally, if I var dumped variables in the controller function before a redirect function call that it should give me a 'Headers already sent' error but it never did. It just redirected me to the supposed success page instead of dumping my variables.
So for the about 2 hours I thought that my POST data wasn't being sent and re-checked the code for errors and began commenting out statements one by one until I could find the culprit statement in my script.
Finally, I commented out a chunk of code that sets a success message an redirects, like so:
/*
if($record_updated_successfully)
{
$this->session->set_flashdata('success', $this->lang->line('record-updated-successfully'));
}
redirect('admin/success_page');
*/
and only then did the script start dumping out all my previous variable dumps using codeigniter's $this->input->post function as well as the $_POST superglobal array.
So ok, if the script does indeed redirect me despite the variable dumps sending output before headers are sent then I can see why the $_POST variables would appear empty.
So then the real question is why the script would still redirect despite my sending of output before headers are sent? Has anyone ever experienced this?
Any help with this would be appreciated.
EDIT: with respect to loading the view here's a simplified version of my script looks like
with the debugging var dump statements:
function some_controller_method() {
var_dump($this->input->post());
var_dump($_POST);
// some code
if($this->input->post('form_action') == 'update record') {
// code that runs when the form is submitted
/*
* ...
*/
if($record_updated_successfully)
{
$this->session->set_flashdata('success', $this->lang->line('record-updated-successfully'));
}
redirect('admin/success_page');
}
$this->load->view('my-view-file.php');
}
While I can't be sure, I'm going to assume you were outputting things like the var_dump() in your view file. A view is not executed at the time you call it, for example:
$this->load->view('some_view');
echo "hi!";
In a controller will not result in the contents of some view followed by "hi". It will results in "hi" followed by the contents of some view. The view is actually output after everything else in the controller has run.
This is the only thing that comes to mind with the information you've presented. I'd have to see more code to offer a different diagnosis.
I had "the same" problem and I found an unset() function in a loop in my code. Perhaps this will help.
As usual, I thought something in the Drupal forms API would be simple... what was I thinking?
Problem
I have a block that outputs a form via drupal_get_form(). Somehow in the block's display function, I want to check whether the form failed validation (i.e. has any errors that were set by form_set_error() in my form's validation function).
Tried so far...
checking $_SESSION['messages']['error'] in block display function - but they are gone by then
checking $_POST in block display function - nothing useful here
checking form_get_errors() in mymodule_preprocess_page() - empty
checking form_get_errors() in mytheme_preprocess_page() - empty
I am confused by my calls to form_get_errors() being empty. It calls form_set_error() with no args - which leaves $reset = FALSE, thus the static var that holds the form errors does not get cleared. So I don't know where that var is getting reset - somewhere by another forms api function? - so that by the time I call it in my module or theme, it's empty.
help?
So, does anyone know at what point (preprocess functions?) I can call form_get_errors() before the static var is cleared? Or have another idea how to check for form errors in the block that displays the form? (By the way - I am fairly sure I could check this easily once I am inside my function that drupal_get_form() calls... but I need to know about the errors in the enclosing block display function.)
This is ugly as all get out but it should work.
$form['#validate'][] = '_error_preservation_helper';
...
function _error_preservation_helper($form, &$form_state) {
$GLOBALS['_error_preservation_helper'] = form_get_error();
return true;
}
I'm trying to build a registration system using PHP and the AJAX components of jquery.
My jQuery takes the values of the username and password fields and makes a POST request to the PHP script, which grabs the values using $_POST and saves them to the database.
Of course, i'm wanting to make sure that there aren't any duplicate usernames, and beyond using the PHP mysql_error() function, i wasn't sure how to do this.
So i want to set my PHP to first check for entries in the database with the username the person enters in the form, if it exists, i'd like to return a custom error message to the user using the php return() feature.
How can i use jQuery to first POST the values to the script, and then return any data/ custom error messages that i am creating with return();
By the way, security is not an issue here.
Simplest way would be to make a page, for example, post.php. post.php will do all the checking and stuff you want and, I know you want to use return, but just echoing the stuff back would be the absolute easiest. So, echo any error or even a value (for example, you can echo back -1 for a false or a 1 for a true).
The jQuery side is pretty simple:
$('form').submit(function(){
$.post('post.php',{username:$('#username').val(),password:$('#password').val()},function(data){
//username and password == $_POST['username'] && $_POST['password']
//data will now equal anything you echo back. So, lets say you did as my example and used -1 for an error
if(data==-1){alert('ERROR');}
});
return false;
});
If there is an error you will get an alert otherwise nothing will happen at all. Now you could do an else{} and have whatever you want for if there is no error.