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');
Related
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
I have been trying to use Messi.js to return a pop up box if the user has an input error in a form. I have a php file called add email:
<?php
/ini_set('display_errors',1);
//ini_set('display_startup_errors',1);
//error_reporting(-1);
include('connectionFile.php');
//test for duplicate emails
$query="SELECT * FROM ClientEmail WHERE ClientEmailAddress = '" . $_POST['emailAdd'] . "'";
$email=$_POST['emailAdd'];
$result=mysql_query($query);
$num=mysql_num_rows($result);
if($num==0)
{
if(isset($_POST['emailAdd']) && $_POST['emailAdd'] != "<<please enter email>>" && $_POST['emailAdd'] !="")
{
// the form was submitted
//remove hacker HTML
$email=strip_tags($_POST['emailAdd']);
//Insert data into database
$sql2="INSERT INTO ClientEmail SET ClientEmailAddress='$email'";
$result=mysql_query($sql2);
}
else
{
print '<script type="text/javascript">';
print 'new Messi("Please enter a valid email.", {title: "Input error", modal:true});';
print '</script>';
}
}
else
{
print '<script type="text/javascript">';
print 'new Messi("Sorry, you have entered an existing email.", {title: "Duplicate Email", modal:true});';
print '</script>';
}
?>
I am not sure where to call the jQuery files and css. I have done so in my index.php page(where the addEmail function is called) but it is still not working.
html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Club Blaque - Sign up for the Revolution</title>
<link href="css/reset.css" rel="stylesheet" type="text/css">
<link href="css/main.css" rel="stylesheet" type="text/css">
<link href="css/messi.min.css" rel="stylesheet" type="text/css"/>
<link href="js/jquery-1.8.2.js" type="text/javascript"/>
<script src="js/messi.js" type="text/javascript"></script>
Thanks in advance
EDIT
My form section currently looks as follows
<form name="emailAddr" method="post" action="">
<p>BE INVITED TO THE REVOLUTION <input id="emailAddress" name="emailAdd" type="text" value="<<please enter email>>" onFocus="clearText(this)" onblur="addText(this)"/>
<button type="submit" name="submit" value="Submit"><img id="submitImage"src='image/submit.ico'/></button> </p>
</form>
You can do the field validation testing in jQuery/javascript before even POSTing the form. That way you can trap errors without refreshing the page.
Note how the Submit button is type="button", not type="submit". The submit function is done via jQuery.
See below stand-alone, fully working example.
jsFiddle here
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#mybutt').click(function() {
//Do your field validation testing here, then submit if okay
var em = $('#emailAdd').val();
var pw = $('#pwordAdd').val();
if (em !='' && pw !='' ) {
$('#myform').submit();
}else{
alert('Please complete all fields');
}
});
}); //END $(document).ready()
</script>
</head>
<body>
<form id="myform" action="yourphpprocessor.php" method="POST">
Email Address:<br />
<input id="emailAdd" name="emailAdd" type="text" /><br />
Password:<br />
<input id="pwordAdd" name="pwordAdd" type="password" /><br />
<input type="button" id="mybutt" value="Submit It" />
</form>
</body>
</html>
Note that if you wish to store the javascript/jQuery in an external file the code would look something like this:
<script type="text/javascript" src='myjavascript.js'></script>
And the file myjavascript.js would look like this:
$(document).ready(function() {
$('#mybutt').click(function() {
//Do your field validation testing here, then submit if okay
var em = $('#emailAdd').val();
var pw = $('#pwordAdd').val();
if (em !='' && pw !='' ) {
$('#myform').submit();
}else{
alert('Please complete all fields');
}
});
}); //END $(document).ready()
For querying the database during field validation, use AJAX. It allows you to send the email address off to a PHP file (let's call it your PHP processor file), do the database lookup, and return a response. The response is anything that you want to build: from a simple 1 or 0 response, to a fully formatted HTML response that you will post into a DIV. In your case, a simple 1 or 0 will be fine.
First thing you must decide is how you want to trigger the AJAX lookup. You could use Submit button, but in our example let's use the jQuery blur() selector as it is triggered the moment a user leaves a field.
$('#emailAdd').blur(function() {
//Test if this email already exists
var em = $('#emailAdd').val();
$.ajax({
type: "POST",
url: "myphpprocessor.php",
data: 'eml='+em+'&anothervar='+summatelse,
success: function(whatigot) {
alert(whatigot);
if (whatigot == 'itexists') {
alert('This email address already exists. Please choose another.');
$('#emailAdd').css({'background-color':'yellow','border-color':'red'});
$('#emailAdd').focus();
}
} //END success callback
}); //END ajax block
}); //END emailAdd.blur
An Important Note About AJAX: All processing of received info must happen in the success: function. So, for example, the error message must happen in there. Once you start working with AJAX (95% of which is in this example - it's not very difficult), this note must be your Bible. Remember it.
Your PHP processor file would look like this:
myphpprocessor.php
<?php
$email = $_POST['eml']; //Note that it is same as the var NAME posted in AJAX
$summat = $_POST['anothervar'];
if ($email != '' && $email != '<<please enter email>>') {
include('connectionFile.php');
//test for duplicate emails
$query="SELECT * FROM `ClientEmail` WHERE `ClientEmailAddress` = '$email'";
$result=mysql_query($query);
$num=mysql_num_rows($result);
if($num > 0) {
echo 'itexists';
}else{
//do nothing
}
}
I have a simple html page below calling a global.js file the global.js file calls a php file that gets a location for a name if it is in a database. (could have put it all on the one page but was following a tutorial).
<!doctype html>
<html
<head>
<title>AJAX Database</title>
</head>
<body>
Name: <input type = "text" id="name">
<br />
<input type="submit" id="submit" value="Get Loc">
<div id="output"></div>
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="js/global.js"></script>
</body>
</html>
global.js is :
$('#submit').on('click',function() {
var name = $('#name').val();
if($.trim(name) != ''){
$.post('ajax/name.php', {name: name}, function(data) {
$('div#output').text(data);
});
}
});
it works fine as is, but if I put in tags as shown below, it won't work. I also want to use a fieldset, but I can't even get it to work with form tags.
I have used other selectors but it won't work.
The problem seems to be the submit button, as it works if that is out of the form..
any ideas? I think using the submit within the form is getting the $.post function to send more than I want it too.
<!doctype html>
<html
<head>
<title>AJAX Database</title>
</head>
<body>
<form>
Name: <input type = "text" id="name">
<br />
<input type="submit" id="submit" value="Get Loc">
</form>
<div id="output"></div>
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="js/global.js"></script>
</body>
</html>
the php file is:
if(isset($_POST['name']) === true && empty($_POST['name']) === false) {
require '../db/connect.php';
$query = mysql_query("
SELECT `names`.`location`
FROM `names`
WHERE `names`.`name` = '" . mysql_real_escape_string(trim($_POST['name'])) . "'
");
echo (mysql_num_rows($query) !== 0) ? mysql_result($query,0,'location') : 'Name not found';
}
Is my problem not using the right selectors, or is there some rule about using selectors for submit buttons within forms ?
You need to prevent the default action of the form. Either by using event.preventDefault() or adding return false at the end of the function.
$('form').on('submit', function(e) {
e.preventDefault();
var name = $('#name').val();
if ($.trim(name) != '') {
$.post('ajax/name.php', {
name: name
}, function(data) {
$('div#output').text(data);
});
}
});
I strongly advise not to use the click of the button but instead I suggest this
<!doctype html>
<html
<head>
<title>AJAX Database</title>
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="js/global.js"></script>
</head>
<body>
<form id="form1">
Name: <input type="text" id="name"><br />
<input type="submit" id="submit" value="Get Loc">
</form>
<div id="output"></div>
</body>
</html>
Where the script is
$('#form1').on('submit', function(e) {
e.preventDefault();
var name = $('#name').val();
if ($.trim(name) != '') {
$.post('ajax/name.php', {
name: name
}, function(data) {
$('div#output').text(data);
});
}
else {
alert('Please enter name');
$('#name').focus();
}
});
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.
I have a problem with my very simple chat. The page is constanly refreshing with AJAX with an timeout of 750ms. If I press or use enter to submit my 'reaction', the page refreshes: is there an way to remove that, so that you can instantly see what you've posted?
You can see the chat at my website: chat
The code:
Index.php
<!DOCTYPE HTML>
<?php include 'config.php'; ?>
<html>
<head>
<script type="text/javascript" src="jquery-1.7.1.js">
function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13)
{
myfield.form.submit();
return false;
}
else
return true;
}
</script>
<title>JavaScript Chat</title>
<link href="style.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="container">
<div id="chatwindow">
</div>
<div class="inputMessage">
<form method="post">
enter code here
<hr></hr>
<textarea name="message" rows="1" cols="55"></textarea><br/>Fill username here<br/>
<input type="text" value="" name="username" />
<input type="submit" value="verstuur" name="submit" onKeyPress="return submitenter(this,event)" />
</form>
<?php include 'send.php'; ?>
</div>
<script type="text/javascript">
$(document).ready(function(){
setInterval ( "get()", 750 );
});
function get(){
$.ajax({
type: 'GET',
url: 'chat.php',
success: function(data){
$("#chatwindow").html(data);
}
});
}
</script>
</div>
</body>
</html>
chat.php
<?php
include 'config.php';
$result = mysql_query("select * from Message");
while($row = mysql_fetch_array($result))
{
echo '<p>' . $row['username'] . " : " . $row['message'] . '</p>';
}
?>
send.php
<?php
if(isset($_POST['submit']))
{
if (!empty($_POST['username']))
{
if(!empty($_POST['message']))
{
$message = mysql_real_escape_string(htmlentities($_POST['message']));
$username = mysql_real_escape_string(htmlentities($_POST['username']));
$query = "INSERT INTO Message (`username`,`message`) VALUES ('".$username."','".$message."')";
mysql_query($query);
}
else
{
echo '<script type="text/javascript">alert(\'Je kan niet niks sturen\')</script>';
}
}
else
{
echo '<script type="text/javascript">alert(\'Vul een gebruikresnaam in!\')</script>';
}
}
?>
if my question is not clear say it please.
And is there a topic/question/post about good spacing? google translated it as "indent".
Thanks
Replace
<form method="post">
With
<form onsubmit="event.preventDefault()" method="post">
You may also use your callback function here like:
<form onsubmit="event.preventDefault();return submitenter(this,event);" method="post">
Working demo: http://jsfiddle.net/usmanhalalit/5RCwF/2/
Add e.preventDefault(); in JS.
Your desired action is to prevent the onSubmit action as the other answers have mentioned. Currently your script isn't quite ready to block submit as you don't have an ajax post method.
You need ajax functionality for the submission side of the application still. For this you can use jQuery post().
You want to create something like
function send() {
$.post(); // Fill in appropriate post() code.
return false;
}
And then call it from your event handlers like onsubmit="return send()" and in place of myfield.form.submit() in your keypress handler.