Hide / Show form either with php or Jquery/Javascript - javascript

I have a problem here which I have solved with two different solutions. I would like to know:
Which solution is the most secure?
Which solution is more efficient, basically which one requires the least bandwith for user?
Which solution in the long run is easiest to maintain?
Is there a possibility that any of the solutions might get outdated in the near future? Example if they change how jQuery .hide() works or anything else, whatever.
Here are my solutions:
Solution 1 with jQuery and some php.
jQuery Code:
$(document).ready(function(){
$.get( "hide_forms_until_logged_in.php", function( data ) {
console.log(data.response);
if(data.response == "false") {
$("form").hide();
} else {
$("form").show();
}
}, "json");
});
HTML markup:
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="file" /> <br/>
<input type="submit" name="submit" value="Upload"/>
</form>
hide_forms_until_logged_in.php:
include 'session.php';
if (isset($_SESSION['login_user'])) {
echo json_encode(array("response"=>"true"));
} else {
echo json_encode(array("response"=>"false"));
}
Solution 2 with mostly php:
hide_forms_until_logged_in.php:
include 'session.php';
if (isset($_SESSION['login_user'])) {
echo "<form action='' method='POST'
enctype='multipart/form-data'>
<input type='file' name='file' /> <br/>
<input type='submit' name='submit' value='Ladda upp'/>
</form>";
} else {
echo "Logga in for att ladda upp filer";
}
And inside the page:
<?php include "hide_forms_until_logged_in.php" ?>
I know I could have made a function and call it inside the include there, for the sake just put the include there.
The form itself before posting anything to database has a check if the user is logged in or not.

Related

Submit checkbox value on form without page refresh AJAX PHP

I just started learning ajax and its really great and time saving i agree.
But i got stuck at this point sending form data without page reload.
Below is my html code.
<form id="form4" method="post">
<input type="checkbox" name="test" id="agreed" value="check">
<br>
<br>
<input type="submit" id="form-submit" name="submit" value="Send">
<p class="form-message"></p>
</form>
Below is my Ajax script
<script>
$(document).ready(function() {
$("#form4").submit(function(event) {
event.preventDefault();
var action = 'another_test';
var agreed = $("#agreed").val();
var submit = $("#form-submit").val();
$(".form-message").load("test3.php", {
test: agreed,
submit: submit,
action: action
});
});
});
</script>
Below is my php code
<?php
if (isset($_POST['action'])) {
if ($_POST['action'] == 'another_test') {
$test = $_POST["test"];
$errorEmpty = false;
if (!empty($test)) {
echo "<p>Click the checkbox pls</p>";
$errorEmpty = true;
}
else {
echo "<p>Checkbox clicked</p>";
}
} else {
echo "Error.. cant submit";
}
}
?>
<script>
var errorEmpty = "<?php echo $errorEmpty ?>";
</script>
The php file is on another page called test3.php
This particular code works if it was an input text but doesn't work for a checkbox.
Please help me so i can learn well.
Thanks in advance.
.load() (as per the documentation) performs a GET request, not a POST, but your PHP is (as shown by the $_POST references) expecting a POST request - and it usually makes sense to submit form data using POST.
So you'd be better to use $.post() - this will send a POST request. Then you can handle the response and load it into your "form-message" element in the "done" callback triggered by that request.
N.B. You could also make the code shorter by putting the "action" variable as a hidden field in the form, and then simply serialize the form in one command instead of pulling each value out separately.
Example:
HTML:
<form id="form4" method="post">
<input type="checkbox" name="test" id="agreed" value="check">
<br>
<br>
<input type="submit" id="form-submit" name="submit" value="Send">
<input type="hidden" action="another_test"/>
<p class="form-message"></p>
</form>
JavaScript
$(document).ready(function() {
$("#form4").submit(function(event) {
event.preventDefault();
$.post(
"test3.php",
$(this).serialize()
).done(function(data) {
$(".form-message").html(data);
});
});
});
Documentation:
jQuery Load
jQuery Post
jQuery Serialize

Validate form with ISSET when using js delay function

I am trying to validate if the correct form is being sent with isset(), but this validation is not TRUE when a javascript delay is being applied. How come? What is the best way to check if the correct form was submitted via the POST method? See my code below. Maybe a hidden field would do the trick, but I actually really would like to know why the below code is not going through.
<script type="text/javascript">
window.addEventListener('load', function onload(){
var ccform = document.getElementById('cc_form');
if(ccform){
ccform.addEventListener('submit', function before_submit(e){
setTimeout(function wait(){
// After waiting, submit the form.
ccform.submit();
}, 2000);
// Block the form from submitting.
e.preventDefault();
});
}
});
</script>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['cc_form_submit'])) {
//Send the form
//Not working
echo 'ready to send!';
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//Send the form
//Working
echo 'ready to send without ISSET!';
}
?>
<form action="" method="post" class="cc_form" id="cc_form">
<button class="cc_form_submit" type="submit" name="cc_form_submit">Send!</button>
</form>
In your example, there are so many possible solutions:
Solution 1:
You can use a hidden value inside your form and then check this value in isset() method like:
<form method="post">
<input type="hidden" name="form1" />
<button>Submit</button>
</form>
<form method="post">
<input type="hidden" name="form2" />
<button>Submit</button>
</form>
<?php
if(isset($_POST['form1'])){
// do somthing
}
if(isset($_POST['form2'])){
// do somthing
}
?>
Solution 2:
You can use input type submit instead of <button> like:
<form method="post">
<input type="submit" name="form1">
</form>
<form method="post">
<input type="submit" name="form2">
</form>
<?php
if(isset($_POST['form1'])){
// do somthing
}
if(isset($_POST['form2'])){
// do somthing
}
?>
Solution 3:
You can use different action for multiple <form> like:
<form method="post" action="form1.php">
</form>
<form method="post" action="form2.php">
</form>
Edit:
As per your comment
don't know why if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['cc_form_submit'])) { is not working.
Its not working because, you are using name= attribute with <button>, in this case solution 2 will work for you.

calling for javascript function in php form

I am using a contact form on my website and I want it to use a javascript function to use a popup box to tell the user that they have not filled all fields. I have this code:
<?php
$action=$_REQUEST['action'];
if ($action=="") /* display the contact form */
{
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
*Name:<br>
<input name="name" type="text" value="" size="30"/><br><br>
*Email:<br>
<input name="email" type="text" value="" size="30"/><br><br>
*Message:<br>
<textarea name="message" rows="7" cols="30"></textarea><br>
<input type="submit" value="Send email"/>
</form>
<script type="text/javascript">
function requiredFields() {
alert("Please fill in all fields!");
}
<?php
}
else /* send the submitted data */
{
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$message=$_REQUEST['message'];
if (($name=="")||($email=="")||($message==""))
{
echo "requiredFields();";
}
else{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("email#email.com", $subject, $message, $from);
echo "Email sent!";
}
}
?>
</script>
However, the website displays this error:
Fatal error: Call to undefined function requiredfields() in /home/a8502709/public_html/test/contact.php on line 46
The line above is the line that it echoes the calling for the function. How can I properly call the function in echo?
You didn't quote your echo output:
echo requiredFields();;
It should be:
echo "requiredFields();";
Otherwise you're telling PHP to execute the requiredFields() function, which doesn't exist in PHP. Hence the error. Your intent here is to tell the JavaScript on the rendered page to execute the function. So as far as PHP is concerned you're just outputting a string to the page.
Note also that this is a syntax error:
echo "Email sent!";
What this will do is emit the following to the JavaScript in your <script> block:
Email sent!
Which, of course, isn't valid JavaScript. You probably meant to output that somewhere else in the page.
Edit: You also seem to have a significant logical error in your code. If you remove the unrelated lines, your structure is essentially this:
if ($action=="") /* display the contact form */
{
?>
<script type="text/javascript">
<?php
} else {
echo "requiredFields();";
}
?>
</script>
So... You only open the <script> tag in the if block, but you use that tag in the else block. By definition both can't execute. Only one or the other. So you're going to have to restructure this a bit.
Maybe close the <script> tag in the if block too, and then open another one in the else block? Or have multiple if/else blocks for the HTML and for the JavaScript? There are a couple of different ways to structure this. But you should see what I'm talking about when you view the page source in your browser. You'll see that, in the event of the else block, you're never creating a <script type="text/javascript"> line and therefore aren't actually executing any JavaScript.
Though, thinking about this some more, it doesn't make sense at all to have the JavaScript start in the if block. Since only the else block uses it. You can't define the function in the if and then try to use it in the else because, again, by definition only one or the other would execute. Maybe just move all of the JavaScript to the else:
<?php
$action=$_REQUEST['action'];
if ($action=="") /* display the contact form */
{
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit">
*Name:<br>
<input name="name" type="text" value="" size="30"/><br><br>
*Email:<br>
<input name="email" type="text" value="" size="30"/><br><br>
*Message:<br>
<textarea name="message" rows="7" cols="30"></textarea><br>
<input type="submit" value="Send email"/>
</form>
<?php
}
else /* send the submitted data */
{
?>
<script type="text/javascript">
function requiredFields() {
alert("Please fill in all fields!");
}
<?php
$name=$_REQUEST['name'];
$email=$_REQUEST['email'];
$message=$_REQUEST['message'];
if (($name=="")||($email=="")||($message==""))
{
echo "requiredFields();";
}
else
{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("email#email.com", $subject, $message, $from);
echo "alert('Email sent!')";
}
?>
</script>
<?php
}
?>
Honestly, this mix of PHP/HTML/JavaScript you have here is a little confusing. Which isn't making this any easier for you. You'll probably want to re-structure this a bit once you get it at least working.

Refreshing div with AJAX

Index.php
...
<form id="calculator_form" name="form" action="" method="get" >
<input name="one" type="text">
<input name="two" type="text">
<input type="submit">
</form>
...
<!-- refresh area -->
<?php if(isset($_GET["one"])) { ?>
<div>
<?php echo $_GET["one"] . " " . $_GET["two"]; ?>
</div>
<?php } ?>
<------------------->
I would like to submit the form and reload the refresh area indicated above. I know this can be achieved by using AJAX but I'm not quite sure how.
I have tried putting the refresh area in a separate ajax.php file and using JQuery but it didn't work;
$(document).ready(function() {
$("#calculator_form").submit(function(event) {
event.preventDefault();
$("#divtoappend").load("ajax.php", data);
})
})
I've also tried using $.get() but to no avail.
I'm able to send the data back and forth to a seperate php page but I'm stuck trying to achieve what I am looking for.
EDIT:
The code that I posted was quickly written and the syntax isn't the issue in question, I'm merely wondering how I can refresh a <div> under the form so that it will once again do the if(isset($_GET["one"])) check and print the updated php variables.
EDIT 2:
My code is now as follows:
Index.php
...
<form id="calculator_form" name="form" action="" method="get" >
<input name="one" type="text">
<input name="two" type="text">
<input type="submit">
</form>
...
<div id="append">
<!-- where I want the ajax response to show -->
</div>
...
ajax.php
<?php if(isset($_GET["one"])) { ?>
<div>
<?php echo $_GET["one"] . " " . 4_GET["two"]; ?>
</div>
<!-- assume there's n number of divs -->
<?php } ?>
Now I want the ajax.php div to append to the #append div in index.php. There has to be a better way than altering the ajax.php and using echo:
ajax.php (with echo)
<?php
if(isset($_GET["one"])) {
echo "<div>". $_GET["one"] . " " . $_GET["two"] . "</div>";
}
?>
So, as ajax.php could be very large, is there a better solution than
just echoing data from ajax.php to index.php?
Now this can be done in many ways.. One of them is Following.. Try this:
Index.php file
<form method="get" id="calculator_form">
<input name="one" type="text" id="one">
<input name="two" type="text" id="two">
<input type="submit" name="submit">
</form>
<div class="result"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#calculator_form").on('submit', function(event){
event.preventDefault();
var one = $('#one').val(); // Taking value of input one
var two = $('#two').val(); // Taking value of input two
$.get( "ajax.php", { one:one, two:two }). done( function( data ) {
$('.result').html(data); // Printing result into result class div
});
});
});
</script>
ajax.php
<?php if(isset($_GET["one"])) { ?>
<div>
<?php echo $_GET["one"] . " " . $_GET["two"]; ?>
</div>
<?php } ?>
Use this,
$(document).ready(function() {
$(document).on('submit',"#calculator_form",function(event) {
event.preventDefault();
$.get(
'ajax.php',
function(ret_data){
$("#divtoappend").html(ret_data);
}
);
});
}) ;
The original syntax for $.get is,
$.get(
URL,
{
VAR_NAME1:VAL1,
VAR_NAME2:VAL2
},
function(response){
// your action after ajax complete
}
);
Typo: You have accidentally used $(document).read( instead of $(document).ready(! That will stop your code running.
Note: jQuery has a handy shortcut for the document ready handler:
$(function(){
// your code here
});
I'm not sure if I understand the question correctly, but here is what you can do: Assign some ID or at least the css Class name to the target div and paint the stuff you are getting from AJAX response something like below.
$(document).ready(function() {
$("#calculator_form").submit(function(event) {
event.preventDefault();
$.ajax({
url: "Ajax_URL",
success: function(result) {
$("#targetDiv").html(result.one + " " + result.two); //assuming you have assigned ID to the target div.
}
});
})
})

Send multiple headers or multiple submitting for the form?

When the user inserts two numbers (from-to), I want to send (((full path))) for each number.
how would I accomplish this? Is there a way in PHP, javascript or any other language. Would I send many headers or multiple submissions for the form?
P.S:
The (go.php) page that receive and process each number individually.. I can't put hands on it to make changes, I only must send individual numbers to it because that's how the other page is coded.
This what i've tried:
<form action="test.php" method="post">
<input type="text" name="first">
<input type="text" name="second">
<input type="submit" name="submit">
</form>
<?php
$f=$_POST['first'];
$s=$_POST['second'];
for($i=$f; $i<=$s; $i++){
header('location:go.php?f='.$i);
}
?>
you can not send header twice you can do this like below
<?php
$f=$_POST['first'];
$s=$_POST['second'];
header('location:go.php?first='.$i.'&second='.$s);
?>
go.php
you can catch these two variables using get method
<?php
$first=$_GET['first'];
$second=$_GET['second'];
//rest of the code
?>
Why not use javascript to submit so many times:
// supposing you have jQuery
for (var i = Number($(':input[name=first]').val()),
end = Number($(':input[name=second]').val());
i <= end; i++) {
$.get('go.php', { f: i }, function (response){
// do something with response
});
}
You can't do it via simple single script. You can do it via multithreading or curl. I am giving you example of curl:
one.php
<form action="test.php" method="post">
<input type="text" name="first">
<input type="text" name="second">
<input type="submit" name="submit">
</form>
<?php
$f=$_POST['first'];
$s=$_POST['second'];
for($i=$f; $i<=$s; $i++){
//write curl code to execute two.php with url : http:// yoursite.com/two.php?f=$i
}
?>
two.php
<?php
header('location:go.php?f='.$_REQEST['f']);
?>
Hope this explanation help you. Best of Luck.

Categories

Resources