jQuery detecting if php $_POST isset - javascript

I'm new to jQuery, and just wondering if there's a way to detect if a form has been submitted on page load, and if so parsing some code.
I have:
<form action="/login/register" method="post">
<input type="text" value="Username" name="regName"/>
<input type="password" value="Password" name="regPass"/>
<input type="submit" value="Register"/>
</form>
and:
<?php
if (isset($_POST['regName']))
{
//check inputs and add account
}
?>
But i was wondering if i could check if the form had been submitted via jQuery?
Thanks.

Just have PHP set a javascript variable to true if a POST submission was made. Then jQuery just needs to check its value.
<script type="text/Javascript">
var was_posted = <?php echo ('POST' === $_SERVER['REQUEST_METHOD']) ? 'true' : 'false'; ?>
</script>

Related

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.

prevent result, show through AJAX, after reload browser

I have a insert query through ajax. It is working correctly. But when I reload browser then result disappears from div section and if I insert form through ajax again then result is showing.
I have a file first.php (in which, form is present), a AJAX code and a firstcall.php where query will be execute.
My first.php (html form) is:
<form class="reservation-form mb-0" action="" method="post" autocomplete="off">
<input name="name1" id="name1" class="form-control" type="text" placeholder="Enter Name" required aria-required="true">
<input name="age" id="age" class="form-control" required type="number" placeholder="Enter Age" aria-required="true">
<input type="checkbox" id="checkbox" class="checkbox1" name="namec[]" value="<?php echo $value['id']; ?>" >
<input type="button" class="pull-right btn btn-warning" value="Submit" id="submit">
</form>
Here data should be display:
<div class="col-md-5">
<div class="panel panel-primary" id="showdata">
<!-- Here is the results, but when reload browser then result disapper-->
</div>
</div>
AJAX is:
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var name1 = $("#name1").val();
var age = $("#age").val();
var chkArray=[];
$('.checkbox1:checked').each( function() {
chkArray.push($(this).val());
} );
var selected;
selected = chkArray.join(',') ;
if(selected.length > 1){
$.ajax( {
url:'firstcall.php',
type:'POST',
data:{name1: name1,age: age,namec: chkArray},
}).done(function(data){
$("#showdata").html(data);
});
}
else{
alert("Please at least one of the checkbox");
}
});
});
</script>
firstcall.php is:
<div class="panel panel-primary" id="showdata">
<?php
foreach($_POST['namec'] as $selected){
echo $selected;
$_SESSION['name1']=$_POST["name1"];
$_SESSION['age']=$_POST["age"];
echo $name1=$_SESSION['name1'];
echo $age=$_SESSION['age'];
$query=mysql_query("insert into patient_details (p_name,p_age,g_number) values ('$name1','$age','$selected')") or die(mysql_error());
}
?>
First of all fix your query to use MySQLi, instead of MySQL, check this or the PHP manual
Also don't ever add direct $_POST or $_GET variables into your mysql query, filter them first using mysqli_real_escape.
$name1 = mysqli_real_escape($link, $_POST["name1"]);
$age = mysqli_real_escape($link, $_POST["age"]);
After that, to show the data when the page reloads, you need to load the data with the page, easiest way to do that is just add in your HTML PHP tags with an echo command inside, adding your variables.
If I understand your question correctly, you want the Ajax result to also show on page load?
Right now you only execute the JS after a click (so on page load/relaod you will just see the html), you might want to execute it after page load aswell (so execute the script without the .click)
You could create a function once, and call it when the page is ready and on click.

Get value from input text in php without pressing Enter

Hay I'm new to php and I have made php code like this :
<?php
session_start();
echo 'Hellow Hisoka';
?>
<form name="form" method="post">
<div class="col-sm-3">
<label class:>Nama :</label>
</div>
<div class="col-sm-9">
<input type="text" name="nama_tamu" id='nama_tamu' class="form-control" placeholder="Nama Lengkap">
<?php
$myValue = $_POST['nama_tamu'];
?>
</div>
<br/><br/>
<?php
echo $myValue;
?>
</form>
When I want to show the echo message, I need to hit enter on my keyboard first in order to get the value of $_POST['nama_tamu'];. My question is can I get the value of nama_tamu input without pressing enter, or maybe without using POST or GET and then assign it to $myvalue?
You will need to use Javascript. You can use the Jquery events :
<script>
$( "#nama_tamu" ).keyup(function() {
alert( $this.val() );// alerting the value of the input field
});
</script>
Web development is all about communication. In this case, communication between two (2) parties, over the HTTP protocol:
The Server - This party is responsible for serving pages.
The Client - This party requests pages from the Server, and displays them to the user. In most cases, the client is a web browser.
Each side's programming, refers to code which runs at the specific machine, the server's or the client's.
You cannot get values without submitting for the user has not entered any yet. PHP is a server side language. To get values before submit and do certain actions with them you will need javascript (a client side programming language).
The simplest method to get a value is using the getElementById().
var something = document.getElementById('someid');
<input type="text" name="something" id="someid">
You can also use jQuery:
var something = $('#someid').val();
Conclusion
The simple answer to your question is: This is not possible.
Why not? I hear you asking. Because PHP doesn't know the values of your form before you send the form to your webserver.
Use keyup().
function check(id)
{
document.getElementById("result").innerHTML = id;
}
<input type="text" name="test" id="test" onkeyup="check(this.value);">
Your value: <span id="result"> </span>
$(document).ready(function() {
$("#check").keyup(function(){
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="check" >
For this purpose you should use .keyup function/event. Following are the snippet :
$(document).ready(function () {
$("#nama_tamu").keyup(function(){
$("#enterdata").html($("#nama_tamu").val());
$.ajax({
type: 'POST',
url: "getdata.php",
data: "nama_tamu="+$("#nama_tamu").val(),
success: function(res)
{
$("#outputdata").html(res);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
session_start();
echo 'Hellow Hisoka';
?>
<form name="form" method="post">
<div class="col-sm-3">
<label class:>Nama :</label>
</div>
<div class="col-sm-9">
<input type="text" name="nama_tamu" id='nama_tamu' class="form-control" placeholder="Nama Lengkap">
<?php
$myValue = $_POST['nama_tamu'];
?>
<br> You press following character:<div id="enterdata"> </div>
</div>
<br/><br/>
<div id="outputdata"></div>
<?php
echo $myValue;
?>
</form>
Also create one file for the required output.
Now in getdata.php file
echo $nama_tamu=$_POST['nama_tamu'];

php variables get values from jquery variables without post to the database

<script>
$(document).ready(function(){
$("#date").click(function(){
start = $("#date_start").val();
end = $("#date_end").val();
});
});
</script>
<input name='date_A' type='text' id='date_start' />
<input name='date_B' type='text' id='date_end' />
<input type="button" id="date" class="button" value="check" />
The question is how to get value of "start" and "end" from the jquery to put that in PHP variable without post it first to database?
<?php
$start_date = "";
$end_date = "";
?>
The both variables above need the value of the variable "start" and "end" from jquery above
$(document).ready(function(){
$("#date").click(function(){
start = $("#date_start").val();
end = $("#date_end").val();
$.ajax({
type: 'post',
url: '/your_page_link/',
data: {start : start, end : end},
success: function (res) {
}
});
});
});
In PHP:
<?php
if(!empty($_POST)){ // If you are using same page, then it'll help you to detect ajax request.
$start_date = $_POST['start'];
$end_date = $_POST['end'];
}
?>
I fear you want to read values from jQuery and inject them in PHP in the same page, which is impossible.
You have to understand what PHP is first. It generates the page, that is then sent to the browser, that then executes jQuery code. PHP code completely disappeared from the generated page. jQuery has no idea of PHP's presence, they just can't interact this way. You must use a GET or POST query in order to send values to a PHP page, back to the server.
You want to read things like this : Difference between Javascript and PHP
This is what you have to do.
<form id="form" name="form" action="" method="post">
<div id="block">
<input type="text" name="startDate" id="startDate" placeholder="Start date" required/>
<input type="text" name="endDate" id="endDate" placeholder="End date" required />
<input type="submit" id="Download" name="Download" value="Download"/>
</div>
</form>
and put this code in the same page
<?php
$startDate = $_POST['startDate'];
$endDate = $_POST['endDate'];
?>

confusion passing variable to php through multiple scripts

I am having difficulty passing a variable from a first form to a second form. There are four scripts involved: debug.php, getVar.php, printme.php and scripta.php. Running debug.php and typing "blah" for a "password to continue", select scripta.php from the pulldown and hit "Submit", I expect to see $dbpass="blah" for all of the scripts. I see it for the first page, but after the second pages' "Submit" button is pressed, the value is forgotten once inside of "printme.php". I suspect this has to do with variable scope. Any help is appreciated.
debug.php:
<html>
<body>
<form name="gateway" action= "" method="POST">
<fieldset>
<label>password to continue:</label>
<input type="text" id="dbpass" name="dbpass">
<label>Select Script:</label>
<select name="scriptSelect" id="scriptSelect">
<option value="">Please make a selection</option>
<option value="scripta.php">scripta</option>
</select>
<input name="updateGateway" type="submit" value="Submit">
<input name="resetForm" id="resetForm" type="reset" value="Reset Form">
</fieldset>
</form>
</body>
</html>
<script type="text/javascript">
document.getElementById('scriptSelect').addEventListener('change', function(e){
var selected_value = e.target.value;
document.forms['gateway'].action = selected_value;
alert(selected_value);
});
</script>
scripta.php:
<html>
<body>
<?php require 'getVar.php'; ?>
<form name="secondform" action= "printme.php" method="POST">
<fieldset>
<label>Hit submit to continue:</label>
<input name="updateScripta" type="submit" value="Submit">
</fieldset>
</form>
</body>
</html>
getVar.php:
<?php
if (isset($_POST['dbpass'])) {
$dbpass = #$_POST["dbpass"];
}
echo "you entered $dbpass";
?>
printme.php:
<?php
echo "Inside of printme, you entered $dbpass";
?>
Thanks
In scripta.php, add the line: <input type="hidden" name="dbpass" value="<? echo $dbpass ?>" /> somewhere inside the form tag.
In printme.php, add this line at the top of the page <? $dbpass = $_POST['dbpass'] ?>
There may be other errors in the scripts you have provided. Check back once you have made the above changes.
Mate... that's not how it works... Each request is independent...
In order to pass a value from one script to the other you either use sessions ($_SESSION) or you need to repost the variable.
Also, I don't know what you're trying to accomplish but passing passwords around, in plain text...
Repost variables
In scripta.php add this
<input name="dbpass" value="<?php $dbpass; ?>" type="hidden"/>
to your form. This will send the value contained in $dbpass in a hidden value.
Then, in printme.php you need to retrieve the value so just require that getVar.php script
require 'getVar.php';
echo "Inside of printme, you entered $dbpass";
Using Sessions:
change your getVar.php
session_start();
if (isset($_POST['dbpass'])) {
$_SESSION['dbpass'] = $_POST["dbpass"]; // you don't need that #
} else {
$_SESSION['dbpass'] = null;
}
then in your subsequent scripts, everytime you want to access dbpass just use
session_start();
$_SESSION['dbpass']
example:
<?php
session_start();
$_SESSION['dbpass']
echo "Inside of printme, you entered $dbpass";

Categories

Resources