Im currently trying to develop a form that can work fully without JavaScript.
Basicly i want the user to be able to do the following:
Complete form
Submit form
Success(Update DB or what ever)
Fail (Go back to step 1 but with data from step 1 before already there)
I was thinking of doing the following for example:
<input type="text" value="<?php checkPost(name);?>"/>
Then in check post doing something like:
function checkPost($name){
try{
return $_POST[name];
}
catch{
return "";
}
}
Would this stop the error:
Notice: Undefined index
Which means if the data wasnt posted then just set the value to "" but if it was posted then set the old value to it.
Is this the best way to do it can anyone tell me a smarter way to do this with my forms.
My form markup can be seen here: JS Fiddle
It will not stop error.
Because error is not an Exception in this case.
This sounds much better:
function checkPost(name){
return isset($_POST['name']) ? $_POST['name'] : '';
}
My opinion - it is very bad idea to write validation functions for each for field.
Read about Zend_Form.
You can include it in your project even if you are not using ZF.
Related
Before anyone tells me to look at other similar posts, I already have and I cannot find any solution to my problem.
I am building a questionnaire for a project, and I am using php 5.6, xampp, phpmyadmin, Phpstorm 2017.1.2 and of course the usual languages html css javacript.
In order to write less code, I used the masterpage method to build my website for the questionnaire.
I therefore have a do-test.php where I put my questionnaire alone and an index.php where I have the main skeleton of the page.
I have my questionnaire form with various fieldsets and their inputs. Lastly I have a input type=submit button that I click and the form is supposed to be submitted. However my $_POST method is not working at all.
The following code does all the work. Unfortunately for reasons yet unknown to me, when the if statement runs, it doesn't even look at the isset or !empty method.
Using an IDE debugger
Debugging the do-test.php without the master-page.: My xdebug (installed in phpstorm), jumps directly from the breakpoint in if statement to the bottom of the page. I tried using an else with a message that "submit is not set" and it shows it before and after submitting the form.
if(isset($_POST['Submit']) && !empty($_POST['Submit'])) {
$results = new Results();
$results->ProcessRequest();
if ($results->isSuccessful()) {
echo "<script type='text/javascript'>
alert('Your data is sent to the server');
</script>";
} else {
echo "<script type='text/javascript'>
alert('Something went wrong.');
</script>";
}
}
My http raw post data is visible but the post array is empty.
Debuggin the do-test.php with the master-page: Gets me 502 bad gateway error
Debug using localhost
Using this code snippet here I tried to see what is going on.
Submitting the form from the master-page or the simple do-test page, gives me the following result:
which means that my post array has all the right variables. All that remains is for the method to be executed and for the data to pass into the db.
My post_max_size and variables_order (advise taken from here) are correct.
magic_quotes_gpc (from this post) are off in php.ini.
Could it be the http modules that interfere with POST as told by GeorgeMillo
here??? If so how do I tamper with those?
Could there be something wrong with my version of phpstorm or the php version?
Any suggestion is welcome. Thank you in advance.
I may have written one thing wrong so I gave the wrong impression. I wrote "when the if statement runs", when in fact, the debugger runs and tries to execute the if statement but it doesnt. Sorry for my bad explanation.
The member "Alive or Die" gave me the simple solution of using
if(count($_POST)>0)
and it works!! So I will stick with that.
Thanks to everyone for your fast comments and for pointing out the obvious when one cannot see it!!
this is my first time using PHP in a real project environment. The project is pretty simple, take an existing, working PHP site and update the HTML to be consistent with HTML5. After designing the HTML, I am inserting the PHP from the previous site. This works most of the time, but I get a few errors. For instance:
<?
$sec = $_GET['sec'];
if ($sec == "1") {
echo ('Success!');
}
?>
Is causing the error:
Notice: Undefined index: sec in /file_that_holds_site_build.
Of course that is only if the url doesn't include the append tag (=1) that alerts the message.
So the question is this, what am I missing that causes the $GET when there is no $sec? How do I eliminate this error on first page load?
You're getting that notice because you're trying to access an array index that doesn't exist in some scenarios. Here's how you should be getting the data out of the request.
$sec = array_key_exists('sec', $_GET) ? $_GET['sec'] : null;
Thanks to everyone who provided possible answers to this question. It was Daniel that came up with the easiest fix. Again, I am just adjusting someone else's code to work, so a universal solve would involve too much of my own writing. To the point, the final code looks like this:
<?
if (isset($_GET["sec"])){
$sec = $_GET['sec'];
if ($sec == "1") {
echo ('Success! Your username and password have been sent via email.');
}}
?>
Notice the added if statement. As I said in a comment to Daniel, SO SIMPLE!
Thanks again for everyone's help. I hope to be likewise of service to you all soon.
Simple just use isset($_GET['sec']) to check for the parameter 'sec' before using it in the php code. That should eliminate the error. This is quite trivial I suppose.
I often simply extract() the wohle $_GET super global and then either get the desired variable or not. As a kind of "declaration" I initialize each expected variable first with false. This way I find it much easier to handle than individually doing a check like if(isset($_GET['element'])) ...
$var1=$var2=$var3=false; // my desired variables
extract($_GET); // everything I get from the form
// or: extract($_REQUEST);
if ($var1) { /* do something with it */ }
Possible security risk:
Of course you should be aware that everybody could simply include their own variable as an argument to he page ...
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!
I know that I was already posted similar question but I just can't find the answer and figure it out how to solve this problem.
I'm trying to customize Jquery Star Rating plugin (link text) but I do not know what to do to show the message based on response of PHP script.
Jquery script successfully send rating data to PHP scripts that query the database and based on that echo message of proper or improper rating.
What should I add to an existing JS code so I can get echo from PHP and base on that write a message on some DIV beside rating star?
Jquery:
$('#gal').rating('gl.php?gal_no=<?=$gal_no;?>&id=<?=$id;?>', {maxvalue:10,increment:.5, curvalue: <?=$cur;?>});
Simplified PHP code:
$br=mysql_query("SELECT count(gal) as total FROM ...")
if ... {
echo '0';
}
else echo '1';
}
Jquery code successfully transmitted data to PHP script and when the PHP done with checking data echo the result ('1' or '0'). How can I get this PHP result back to Jquery and based on them write a message? Something like:
if(data=="1")
{
$("#error").show("fast").html('not correct').css({'background-color':'#F5F5F5','border-color' : '#F69'});
}else{
$("#error").show("fast").html('correct').css({'background-color' : '#FFF','border-color' : '#3b5998'});
}
If someone has an idea...I would appreciate it.
You would have to modify the source of the rating plug-in, as it does not provide any way for you to handle return values of your script. Read the documentation of jquery.post method in jquery, and then try to understand rating's code. Notice that when calling post method rating plugin doesn't provide a callback method (in other words it just doesn't care what your php script returns). You could try to modify the code in such way, that it allows you to register your own callback method.
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.