What is the best way to ensure that a logic test on a self-referencing PHP form correctly identifies the HTML button used to submit the form, when that form is actually submitted via jquery.submit() -rather than by a click of the button itself?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Total Tutor </title>
<link type="text/css" rel="stylesheet" href="course.css">
<script src="../jquery.js"></script>
</head>
<body>
<script>
$(document).ready(function() {
//event that triggers the javascript/jquery form submission
$('li').dblclick(function()
{
selectedCourse=$(this).text();
sessionStorage.removeItem('selectedCourse');
sessionStorage.setItem('selectedCourse', selectedCourse);
editForm();
});
//the function called by the normal button submission and the alternative jQuery only submission: note the non jQuery one sets the $-POST variable fine
function editForm() {
var s= confirm( 'Would you like to edit ' +selectedCourse+ '');
if(s)
{
alert('form is called');
}
}
$('#edit-button').click(function() { editForm(); });
});
</script>
<?php
if(!isset($_POST['submit']))
{
?>
<ul>
<li>Maths</li>
<li>English</li>
</ul>
<form id="edit_delete" method="POST" action=" <?php echo $_SERVER['PHP_SELF']; ?>">
<button type="submit" id="edit-button" name="submit" value="edit" ><img src="../images/pencil.png"></button>
<button type="submit" id="delete-button" name="submit" value="delete" ><img src="../images/deleteo.png"></button>
</form>
}
<?php
else
{
if($_POST['submit']=='edit')
{
?>
<p>Thank you for selecting edit</p>
<?php
}
if($_POST['submit']=='delete')
{
?>
<p>Thank you for selecting delete</p>
<?php
}
}
?>
</body>
</html>
Use a variable to indicate how the data was posted.
In your html form:
<input type="hidden" name="wasClicked" id="wasClicked" value="1" />
In your jQuery:
$('#wasClicked').val("0");
Then in your PHP, test $_POST['wasClicked'] to see if it is 0 or 1
Related
I have code with single page PHP method
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
<?php
if(isset($_POST['submit'])){
$date=$_POST['date'];
}else{
$date=date('Y-m-d');
}
?>
<form action="" method="post" id="formId">
<input type="text" name="date" id="datepicker">
<input type="submit" name="submit">
</form>
<?php echo $date; ?>
<script>
$(function() {
$('#datepicker').datepicker({
autoclose: true
})
});
</script>
how, if i want to use ajax to keep the page not to reload? please help me
ok so here is quick tutorial. ajax helps you to submit your form without page loading. You have to use action="somepage.php". when you click it it will pass the values there right away. so here is basic coding
<form id="formId">
<input type="text" name="dte" id="dte">
<button type="button" id="buttonsubmit">submit</button>
</form>
and ajax should be look like. In my coding id="buttonsubmit" is button id so when user will click it it run the function and takes the values
var dte;
$("#buttonsubmit").click(function(){
dte = $("#dte").val();
$.ajax({
url:"somepage.php",
method:"POST",
data:{dte: dte},
success: function (data){
if(data == "done"){
window.location='http://somedomain.com/';
}
}
});
});
in somepage.php you will have
<?php
if(isset($_POST['dte'])){
$date=$_POST['dte'];
echo "done";
}else{
$date=date('Y-m-d');
}
?>
note: i am writing echo "done"; in success method it will come and
according to code when success will see it will redirect the page
I'm a newbie in php. I want to validate a form and set the form data to the session variables so as to use them onto next page.
here is the code,
<?php
session_start();
?>
<html>
<head>
<script type="text/javascript">
function val(){
var n=document.f.cname.value;
if(n==""||n==null){
alert("Please enter name field.");
return false;
}
}
</script>
</head>
<body>
<form method="post" action="<?php $_Php_SELF?>" onsubmit="return val()">
name : <input type="text" name="cname" />
<input type="Submit" name="submit" value="Sub"/>
</form>
<?php
if(isset($_POST['submit'])){
$_SESSION['caname']=$_POST['cname'];
header("location:sessiontest2.php");
}
?>
</body>
</html>
The second page just echos the session variable.
Without validation it works fine.
Handle your redirection before the html part. Also fixed your code.
<?php
session_start();
if(isset($_POST['submit'])){
$_SESSION['caname'] = $_POST['cname'];
header("location:sessiontest2.php");
}
?>
<html>
<body>
<form name="myForm" method="post" action="<?= $_SERVER['PHP_SELF']?>" onsubmit="return validate()">
Name : <input type="text" name="cname"/>
<input type="Submit" name="submit" value="Sub"/>
</form>
<script type="text/javascript">
function validate() {
var name = document.forms["myForm"]["cname"].value;
if(name.length === 0){
alert("Please enter the name");
return false;
}
}
</script>
</body>
</html>
The
if(isset($_POST['submit'])){
$_SESSION['caname']=$_POST['cname'];
header("location:sessiontest2.php");
}
has to be at the top of the page after the session_start(), because the header function must be called before html is printed out.
Other than that it looks fine.
How should I check in php if checkbox is checked after button was clicked?
I tried to do like this, but nothing happens. It returns the answer of my first condition. I tried to put "checked" property on one of checkboxes, but code still doesn't work...
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
$('#refreshList').on('click', function() {
var url = 'admin/thisPage.php';
$('#div1-wrapper').load(url + ' #div1');
});
});
</script>
</head>
<body>
<div>
<input type="checkbox" name="active_registration" id="active_registration" value="" > active registration
<input type="checkbox" name="coming_events" id="coming_events" value="" /> Comming events
<button type="button" class="btn btn-primary" id=refreshList>refresh</button>
</div>
<div id="div1-wrapper">
<div id="div1">
<?php
if ( !isset($_POST["active_registration"]) && !isset($_POST["coming_events"])) {
echo "false/false";
}
if ( isset($_POST["active_registration"]) && !isset($_POST["coming_events"])) {
echo "true/false";
}
if ( !isset($_POST["active_registration"]) && isset($_POST["coming_events"])) {
echo "false/true";
}
if ( isset($_POST['active_registration']) && isset($_POST['coming_events'])) {
echo "true/true"
}
?>
</div>
</div>
</body>
</html>
I am using Pure JS to first prevent the form from submitting then I have some validation code and finally automatic submission but the data is not passing from client side to server script.
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Chat Room</title>
<link type="text/css" href="main.css" rel="stylesheet" />
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<div id="container" class="add-nick">
<h3>Enter Your Name</h3>
<form action="chat.php" method="post" id="add-nicki">
<input type="text" placeholder="At least 6 alphabets e.g. Jackson" class="text" name="name" />
<input type="submit" value="Submit" class="submit" name="btnsubmit" />
</form>
</div>
</body>
</html>
The JS:
window.onload = function() {
document.forms[0].onsubmit = function(e) {
e.preventDefault();
var regexp = new RegExp("^[A-Za-z]+$"),
elem = this.elements[0],
value = elem.value;
if(regexp.test(value) && typeof value != "null" && value.length > 5) {
elem.className = "text correct";
var formElem = this;
setTimeout(function() { formElem.submit(); }, 0);
}
else elem.className = "text wrong";
};
};
The PHP file:
<?php
session_start();
if(isset($_POST['btnsubmit'])) {
$_SESSION['name'] = $_POST['name'];
echo $_SESSION['name'];
}
else {
if(!isset($_SESSION['name']))
echo "Header";
else
echo $_SESSION['name'];
}
?>
Is there something wrong or JS submit function is not functioning properly ?
The request parameter corresponding to a submit button is only passed if the form is submitted as a result of clicking that button. That's not the case here since you suppress the original form submit (the one triggered by the button), then later call formElem.submit() from JavaScript; no button click means no request parameter, and therefore isset($_POST['btnsubmit']) in your PHP script won't ever return true.
One solution might be to add the btnsubmit parameter to the form's action before submitting it:
formElem.action += (formElem.action.indexOf('?') == -1 ? '?btnsubmit=Submit' : '&btnsubmit=Submit');
I'm trying to display data from mysql on the same page that i've got my form with checkboxes. The question is how to write js script that gonna display it.
The code is:
<form id="myForm" action="pdoakcja.php" method="post">
<!--Instruktor: <input type="text" name="name" /> -->
Permissions:<input type="checkbox" name="M1" value="M1" />M1
<input type="checkbox" name="M2" value="M2" />M2
<input type="submit" value="Szukaj" />
</form>
<div id='name-data'>Instruktorzy o podanych uprawnieniach:</div>
<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script>
............??????
</script>
You could solve your problem by using jquery form plugin, which will help you to submit the form without having to reload the page and show you the return from your target page in the same page. Just follow the instructions:
Download this jquery form plugin first and save it.
Then
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<!-- This jquery.form.js is for Submitting form data using jquery and Ajax -->
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
success: showResponse
};
// bind form using 'ajaxForm'
$('#myForm').ajaxForm(options);
});
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
if(responseText==1){
$("#error").html('No Result Found');
} else{
$("#result").html(responseText);
}
}
</script>
<form id="myForm" enctype="multipart/form-data" action="pdoakcja.php"
method="post" name="myForm">
<!--Instruktor: <input type="text" name="name" /> -->
Permissions:<input type="checkbox" name="M1" value="M1" />M1
<input type="checkbox" name="M2" value="M2" />M2
<input type="submit" value="Szukaj" />
</form>
<span id="error"></span>
<span id="result"></span>
YOUR pdoakcja.php file: (I have got the following code from your another post here, haven't checked it though)
<?php
$query = mysql_query("SELECT * FROM permissions WHERE m LIKE '".$_POST['M1']."' OR m LIKE '".$_POST['M2']."' OR mn LIKE '".$_POST['MN1']."' ");
if($query) {
while($permissions = mysql_fetch_assoc($query)){
$query2 = mysql_query("SELECT name_surname FROM instruktorzy WHERE instruktor_id='".$permissions['instruktor_id']."'");
while($Mdwa = mysql_fetch_assoc($query2)){
echo "<p style=\"font-size: 14px; font-family: Helvetica; background-color: #FFFFFF\"> ".$Mdwa['name_surname']."<br />" ; "</p>" ;
}
}
} else {echo "1";}
?>
I hope this will work for you. For detail information you could study the jquery form plugin's website.
Heres a pseudo example showing how you can do it with jQuery, this will also update as you click the check box so you could remove the submit altogether;
You say you already have a database doing the job so I wont include that. Just copy and paste.
<?php
//Some pseudo data kinda as your receive it from a query
$datafromSql = array(
array('id'=>1,'permission'=>'M1','theData'=>'User has M1 permission'),
array('id'=>2,'permission'=>'M2','theData'=>'User has M2 permission'),
array('id'=>3,'permission'=>'M1','theData'=>'User has M1 permission'),
array('id'=>4,'permission'=>'M1','theData'=>'User has M1 permission'),
);
//Access the data
if($_SERVER['REQUEST_METHOD']=='POST'){
$is_ajax = false;
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){
$is_ajax = true;
}
//pseudo code, really you would put your query here
// SELECT theData FROM your_table WHERE permission=POST_VALUE ... ...
//And then format your output
$result=array();
foreach($datafromSql as $row){
if($is_ajax == true){
foreach($_POST as $key=>$value){
if($_POST[$key] == 'true' && $row['permission']==$key){
$result[]=$row['theData'].'<br />';
}
}
}else{
foreach($_POST as $key=>$value){
if($_POST[$key] == $row['permission']){
$result[]=$row['theData'].'<br />';
}
}
}
}
$result = implode('<hr />',$result);
//AJAX Response, echo and then die.
if($is_ajax === true){
header('Content-Type: text/html');
//example output sent back to the jQuery callback
echo $result;
//echo '<pre>'.print_r($_POST,true).'</pre>';
die;
}
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js" charset="utf-8"></script>
<script type="text/javascript">
function update(){
$.post('./<?php echo basename(__FILE__)?>',
{
M1: $("#M1").is(':checked'),
M2: $("#M2").is(':checked')
},
function(data) {
$('#result').replaceWith('<div id="result"><h1>The Result:</h1>'+ data +'</div>');
});
}
</script>
</head>
<body>
<form method="POST" action="<?php echo basename(__FILE__)?>">
Permissions:
<input type="checkbox" id="M1" name="M1" value="M1" onChange="update()"/>M1
<input type="checkbox" id="M2" name="M2" value="M2" onChange="update()"/>M2
<input type="submit" value="Szukaj" />
</form>
<p id='result'><?php echo isset($result)?$result:null;?></p>
</body>
</html>
You should use the PHP MySQL functions to retrieve the data you want from your database and then display them via PHP, not javascript.
Especially have a look at this: mysql_fetch_assoc - there is a fully working example.