I'm trying to validate a form using Ajax and onchange function. Basically I want automatic validation once the focus is gone from the input box. Then it will state an error if it's blank / invalid entry.
For some reason the validation works for invalid entries but won't work for empty inputs on first try (meaning if i refresh page and go to second field box by tab, there's no error). The funny thing is the empty error works fine after i erase an entry. I've tried using $var = "" or empty($var) but I still get the same results.
Here's the php part:
if(isset($_GET["isbn"]) )
{
$isbn = $_GET["isbn"];
$error="";
if(empty($isbn) || !preg_match("/^\d{12}$/", $isbn) )
{
$error .= "Please enter a valid ISBN";
echo $error;
}
else
echo $error;
}
Here's the rest:
<script type="text/javascript">
function validateIsbn(keyword)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.status == 200 && xhr.readyState == 4)
{
var res = xhr.responseText;
document.getElementById("err1").innerHTML = res;
}
}
xhr.open("get","validate_isbn.php?isbn=" + keyword,true);
xhr.send();
}
</script>
<form method="get" action="">
<label class="top-label">ISBN:</label>
<input name="isbn" id="isbn" type="text" onchange="validateIsbn(this.value)"/>
<div id="err1"> </div>
<p></p><p></p>
You say you want automatic validation once the focus is gone from the input box. The event triggered in that case is onblur, not onchange.
Related
I have an html form and when the user chooses a file and submits it the $_FILES in the php document doesn't receive the it. The main focus is the form, when I hit submit no file gets submitted but the onclick event fires. and there are no error messages
<form id="artist_post" enctype="multipart/form-data" method="post" onsubmit="return " action="php_parsers/newsfeed_system.php">
<textarea id="statustext" onkeyup="statusMax(this,250)"></textarea>
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input id="audioUpload" type="file" name="audioUpload" accept="audio/*" />
<input type="submit" value="Post" id="statusBtn" onclick="postToStatus('status_post','a','statustext')"/>
</form>
Here is the php doc, I'm just trying to see if the file is getting uploaded
if (isset($_FILES["audioUpload"]["name"])) {
echo "flag1";
}
if ($_FILES["audioUpload"]["tmp_name"] != "") {
echo "flag2";
}
The javascript takes the information from the form and sends it to php through ajax.
function postToStatus(action,type,ta){
var data = _(ta).value;
if(data == ""){
alert("Type something first");
return false;
}
// Checks to see if user uploaded a file to send with post
if(_("audioUpload").value != "") {
type = "c";
}
_("statusBtn").disabled = true;
var ajax = ajaxObj("POST", "php_parsers/newsfeed_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
//Pull some info from whatever the php doc returns
}
}
ajax.send("action="+action+"&type="+type+"&data="+data);
}
function ajaxObj(meth, url) {
var x = new XMLHttpRequest(); // create new http request
x.open( meth, url, true ); // open request and pass it a method and a url to post it to
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
// Modular function that externalizes readyState and status check
function ajaxReturn(x) {
if(x.readyState == 4 && x.status == 200) {
return true;
}
}
Your <form action="..."> needs to be removed. You are using AJAX and are therefore bypassing the form action sequence all together. I have created a replica of this on my server and it works without that there.
I would recommend throwing it into a JSFiddle now and again and hitting the "Tidy" button up top. Otherwise, well done on the code so far.
In case you wanted to see my duplicate copy in action: click here
When a form is submitted, I can get its field values with $_POST. However, I am trying to use a basic jQuery (without any plugin) to check if any field was blank, I want to post the form content only if theres no any blank field.
I am trying following code, and I got the success with jQuery, but the only problem is that I am unable to post the form after checking with jQuery. It does not get to the $_POST after the jQuery.
Also, how can I get the server response back in the jQuery (to check if there was any server error or not).
Here's what I'm trying:
HTML:
<form action="" id="basicform" method="post">
<p><label>Name</label><input type="text" name="name" /></p>
<p><label>Email</label><input type="text" name="email" /></p>
<input type="submit" name="submit" value="Submit"/>
</form>
jQuery:
jQuery('form#basicform').submit(function() {
//code
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
return false;
});
PHP:
if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];
//no any error
return true;
}
To be very specific to the question:
How can I get the server response back in the jQuery (to check if
there was any server error or not). Here's what I'm trying:
Sound like you're talking about Server-Side validation via jQuery-Ajax.
Well, then you need:
Send JavaScript values of the variables to PHP
Check if there any error occurred
Send result back to JavaScript
So you're saying,
However, I am trying to use a basic jQuery (without any plugin) to
check if any field was blank, I want to post the form content only if
there's no any blank field.
JavaScript/jQuery code:
Take a look at this example:
<script>
$(function()) {
$("#submit").click(function() {
$.post('your_php_script.php', {
//JS Var //These are is going to be pushed into $_POST
"name" : $("#your_name_field").val(),
"email" : $("#your_email_f").val()
}, function(respond) {
try {
//If this falls, then respond isn't JSON
var result = JSON.parse(respond);
if ( result.success ) { alert('No errors. OK') }
} catch(e) {
//So we got simple plain text (or even HTML) from server
//This will be your error "message"
$("#some_div").html(respond);
}
});
});
}
</script>
Well, not it's time to look at php one:
<?php
/**
* Since you're talking about error handling
* we would keep error messages in some array
*/
$errors = array();
function add_error($msg){
//#another readers
//s, please don't tell me that "global" keyword makes code hard to maintain
global $errors;
array_push($errors, $msg);
}
/**
* Show errors if we have any
*
*/
function show_errs(){
global $errors;
if ( !empty($errors) ){
foreach($errors as $error){
print "<p><li>{$error}</li></p>";
}
//indicate that we do have some errors:
return false;
}
//indicate somehow that we don't have errors
return true;
}
function validate_name($name){
if ( empty($name) ){
add_error('Name is empty');
}
//And so on... you can also check the length, regex and so on
return true;
}
//Now we are going to send back to JavaScript via JSON
if ( show_errs() ){
//means no error occured
$respond = array();
$respond['success'] = true;
//Now it's going to evaluate as valid JSON object in javaScript
die( json_encode($respond) );
} //otherwise some errors will be displayed (as html)
You could return something like {"error": "1"} or {"error": "0"} from the server instead (meaning, put something more readable into a JSON response). This makes the check easier since you have something in data.
PHP:
if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];
//no any error
return json_encode(array("error" => 0));
} else {
return json_encode(array("error" => 1));
}
JavaScript:
jQuery('input#frmSubmit').submit(function(e) {
//code
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
var myData = data;
if(myDate.error == 1) {//or "1"
//do something here
} else {
//do something else here when error = 0
}
});
}
$("form#basicform").submit();
return false;
});
There are two ways of doing that
Way 1:
As per your implementation, you are using input[type="submit"] Its default behavior is to submit the form. So if you want to do your validation prior to form submission, you must preventDefault() its behaviour
jQuery('form#basicform').submit(function(e) {
//code
e.preventDefault();
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
$(this).submit();
return false;
});
Way 2:
Or simply replace your submit button with simple button, and submit your form manually.
With $("yourFormSelector").submit();
Change your submit button to simple button
i.e
Change
<input type="submit" name="submit" value="Submit"/>
To
<input id="frmSubmit" type="button" name="submit" value="Submit"/>
And your jQuery code will be
jQuery('input#frmSubmit').on('click',function(e) {
//code
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
$("form#basicform").submit();
return false;
});
To get the response from the server, you have to echo your response.
Suppose, if all the variables are set, then echo 1; else echo 0.
if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];
echo 1;
} else {
echo 0;
}
And in your success callback function of $.post() handle it like
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast",{err:data}, function(e) {
if(e.data.err==1){
alert("no error");
} else {
alert("error are there");
});
});
I have a multi page form (pages separated with hidden divs)
All of it is wrapped in form tags, with a submit button. However when the user clicks the submit button at the end, it will check certain criteria on the form. If all good, it will allow the form to submit, else it will preventDefault().
However in IE8+ (maybe lower too), it simply never submits the form. I have console.log'd the JS, and it fires where it should, just IE doesn't submit the form.
I then added a $('#form').submit() call to manually submit it, which it did, but no data got sent...
Any ideas? Sorry if this is a bit vague.
Html
<form method="POST" action="/members/transfer_manager.php" name="f1" id="TM_MainForm">
** Loads of form fields & table structure **
<input type="submit" class="TM_Button" id="TM_submitTransfer" name="save" value="Transfer my account{if $isclientaresellerVAL}s{/if} »" />
</form>
JavaScript
$('#TM_submitTransfer').click(function(e)
{
console.log($.TM_submitTransferERR);
// Submit the form? Let's check first matey.
$.TM_submitTransferERR = false;
if(($('#TM_Movedate').val() == '') && (!$('#TM_MoveNow').is(':checked')))
{
$('#TM_MoveDate_ERR').html($.ObjectER + "Please choose");
$.TM_submitTransferERR = true;
}
console.log($.TM_submitTransferERR);
// Check we have some…
// Set the # of xfers
var rsxfers = $("#TM_UsernamesSubACCTSTAGC").tagit("assignedTags");
var fsxferssplitLGNTH = rsxfers.length;
var OnlySubAccts = $('#TM_only_sub_accounts').prop("checked");
console.log($.TM_submitTransferERR);
if((OnlySubAccts == true) && (fsxferssplitLGNTH < 1))
{
alert("You have not chosen any accounts to transfer");
$.TM_submitTransferERR = true;
}
console.log($.TM_submitTransferERR);
// Check TOS
if(!$('#TM_Tos').is(':checked'))
{
// Show error?
$('#TM_Tos').focus();
$.TM_submitTransferERR = true;
}
console.log($.TM_submitTransferERR);
// Error, return false.
if($.TM_submitTransferERR === true)
{
console.log("Don't do it!");
console.log($.TM_submitTransferERR);
e.preventDefault();
return false;
}
console.log($.TM_submitTransferERR);
console.log("do it!");
$('#TM_MainForm').submit();
return true;
});
How to prevent a form from submit if text box is empty?
This I have done in JSP successfully using alert message.
Javascript:
function validate()
{
var x=document.forms["Form1"]["comp"].value;
if (x==null || x=="")
{
alert("comp cannot be blank");
return false;
}
<form name="Form" action="welcome.php" onsubmit="return validate()" method="post">
<input type="text" name="comp">
How can I do the same using PHP? So that whenever a user submits without entering text it should give message to user through an javascript alert() message.
I can display alert message:
echo '<script language="javascript">alert("comp cant blank");</script>';
But how can i give condition?what are the changes has to be made in the above please put it in a code form.i have to do it only in PHP.
You cannot stop a form from submitting using PHP.
PHP is server side, you would need to have Javascript to handle the form submit if there is an issue with your validation. You should handle validation on both client side (JS) and server side (PHP).
So no, not possible with just PHP as you outlined, the form WILL submit, then you validate it. Can't stop it with PHP (as its just HTML to the user).
you can used from this jquery code:
$("#btnSubmitID").click(function(event){
if($("#txtID").val()==''){
event.PreventDefault();
alert("your message");
}
});
this is a sample, you can validate your form with this way before post to the server.
You could submit the form using XHR (known as AJAX) and have php verify the data.
You would still need to submit the XHR using javascript.
Your javascript code looks fine and it should not submit the form when its empty. However, if you want to do from PHP code, you can do the same, but the form needs to submit and return back to same page when its not valid (or empty).
Here is sample code
<?php
if ($_POST['comp'] == '')
{
header("location:yourpagename");
}
else
{
// process
}
?>
And now for the non-pseudo code answer. This is working, tested code that elaborates on the concepts I already posted.
<?php
function formWasPosted()
{
return array_key_exists( 'comp', $_POST );
}
// -------
function validate( &$errors )
{
if ( $_POST['comp'] == '' )
{
$errors['comp'] = 'cannot be blank';
}
return count( $errors ) == 0;
}
// -------
function getError( $fieldName, $errors )
{
$out = '';
if ( array_key_exists( $fieldName, $errors ) )
{
$out = '<span class="errorMsg">' . $errors[$fieldName] . '</span>';
}
return $out;
}
//------------------------------------------------------------------------
// $errors will be passed to our validate function so we can set error messages per field if desired.
$errors = array();
$formMsg = '';
if ( formWasPosted() )
{
if ( validate( $errors ) )
{
// do processing here
header( 'Location: http://www.example.com/success' );
exit();
}
$formMsg = '<div class="errorNotice">There were problems with your submission</div>';
}
?>
<html><head>
<script type="text/javascript">
function validate()
{
var x=document.forms["Form1"]["comp"].value;
if (x==null || x=="")
{
alert("comp cannot be blank");
return false;
}
}
</script>
<style>
.errorMsg, .errorNotice { color: red; }
.errorNotice { font-size: 150%;}
</style>
</head>
<body>
<?php echo $formMsg; ?>
<form name="Form" action="welcome.php" onsubmit="return validate()" method="post">
<label for="comp">Comp <?php echo getError( 'comp', $errors ); ?></label>
<input id="comp" type="text" name="comp">
</form>
</body>
</html>
Here is the general approach I use for processing forms.
Pseudo code:
Has Form Been Submitted?
Is form valid?
process form (db insert/update/delete, other operation here
Else
Print form with error messages and optionally a javascript alert
End is form valid
Else
Print form without error messages
End has form been submitted
I have a simple input form on my site for people to enter in information for submission. The code looks like this in the case they do not enter anything:
this is form.php
if ($_POST['q']) == NULL ){
echo "Please enter your information"
The code works great, but it sends the user to form.php with the echo, where I want this to be echoed on my main page index.html right below the input box - basically so it doesn't navigate away from the page. Is this doable in php or will I need some javascript. I would have searched for ways to do this but I don't know what this method is called.
Thanks!
dont set a action in the url and it will submit to its self, if that still wont work you will need rewrite rules.
If you don't want to navigate away from the page you will need to use Javascript. Add a onSubmit to the form, and then let the function you call there return false, if the input is not complete and the form should not be submitted.
you can make it postback to itsself and then redirect the page to post.php?q=value if there is a value else echo below the input field.
<?php
$qisempty = false;
if(!empty($_POST['q']))
{
header("Location:http://../post.php?q=".$_POST['q']);
}
else
$qisempty = true;
?>
<input name="q" type="text">
<?php if($qisempty) echo "Please enter your information";?>
You can use AJAX for this thing. AJAX is great for this type of problems when you don't want to reload pages to do task in specific place or Div of HTMLpages.
For your problem, You need to create a HTML file with your form in it, and submit it via AJAX. and get your response via same AJAX.
<script type="text/javascript">
function submit_ajax(val1,val2,param1,param2,subfile){
var http = new XMLHttpRequest();
var url = subfile;
var params = val1+"="+param1+"&"+val2+"="+param2;
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
//Remove the alert and use whatever you want to do with http.responsetext like
// document.getElementById("YourDiv").innerHTML=document.getElementById("YourDiv").innerHTML +http.responsetext
}
}
http.send(params);
}
</script>
</head>
<body>
<form>
<input type="text" id="user" value="user" name="user" />
<input type="password" id="password" value="pass" name="pass" />
<button onclick="submit_ajax(user.name,password.name,user.value,password.value, "submit_file.php");">Submit</button>
</form>
<div id="YourDiv">
<!--Something appears here after callback-->
</div>
This was the first page. Now Use your script in your PHP file(probably, submit_file.php) as you want and then echo the text you want in your div by validation or something.. a sample would be
<?php
$username=$_POST['user'];
$password=$_POST['pass'];
if(validateuser($username,$password)){
if(checkuserpass($username,$password){
echo "You were successfully logged in!";
}
echo "Sorry Username/Password Mismatch";
}
else {
echo "There was an error in your input!Please Correct";
}
?>
Hope you got what you wanted...
The simplest way would be assigning the error message to a variable called (e.g $errorMsg)
the printing it on page using a echo or print function.
<?php
if ($_POST['q']) == NULL ){
$errorMsg =' Please enter your information';
}
?>
Place this code where you want the error to appear
<? print $errorMsg; ?>