I cannot get client side and server side validation to work - javascript

I have the following forms
<form name="courses">
<div="requiredfield">
<input type="text" name="coursename" id="coursename">
</div>
<input type="submit" name="submitform1">
</form>
<form name="students">
<div="requiredfield">
<input type="text" name="studentfirstname" id="studentfirstname">
</div>
<div="requiredfield">
<input type="text" name="studentlastname" id="studentlastname">
</div>
<div="requiredfield">
<input type="text" name="studentage" id="studentage">
</div>
<input type="submit" name="submitform2">
</form>
I use this code for client side validation
// this works fine
$('#courses').submit(e) {
e.preventDefault();
if ($('#coursename').val() == 0) {
// error message is appended to the div containing the field
// the same for the other form and its field
}
}
What does not work is the server side validation
<?php
if (isset($_POST['submitform1'])) {
if (empty($_POST['coursename'])) {
$course_mistake = "please fill this field"
}
}
?>
I have no idea why the server side validation does not work. Please help me.

<form name = "courses" method="post" action="validation.php">
// Your form fields.
</form>
You should specify the method and the name of php file in <form> , in which your controls will go on submit .
See this http://www.w3schools.com/php/php_forms.asp

1 You prevent form submitting:
$('#courses').submit(e) {
e.preventDefault(); // This prevents form submitting to PHP side
If you don't use Ajax (I don't see any code related), than you are note sending data to PHP
2 <form name="courses"> means you are using $_GET method, but in PHP you expect $_POST.
Either add method="post" or in PHP use $_GET/$_REQUEST.
3 You are not outputting errors nowhere - missing $course_mistake processing

Related

Pre-populate HTML form text from URL

I am using this form on my php file to create the form
<input type="text" name="OrderLNumber" id="OrderLNumber" >
<br>
<input type="submit" name="submit" value="Status">
</form>
after that I am trying to pre-fill the form OrderLNumber field from this URL:
status/2727?OrderLNumber=24206927
Page loads normally but field is not filled as I intend to. How can I make this work ?
You need to get the order number from the url by using the $_GET['OrderLNumber'] variable.
The code below will test to see if the form has been submitted. If the from has loaded fresh with no POST data it will grab the order number from the url. If the form has been submitted and there is POST data it will use whatever is in the form for the order id.
Like so:
<?php
if(isset($_POST['OrderLNumber']) && $_POST['OrderLNumber']){
$orderLNumber = $_POST['OrderLNumber'];
}else{
if(isset($_GET['OrderLNumber']) && $_GET['OrderLNumber']){
$orderLNumber = $_GET['OrderLNumber'];
}
}
?>
<form action="" method="POST">
<input type="text" name="OrderLNumber" id="OrderLNumber" value=" <?php echo $orderLNumber; ?> " ><br>
<input type="submit" name="submit" value="Status">
</form>
Hope this helps.

jquery AjaxSubmit function how to get result from the form page to display

I'm trying to understand how to use ajaxSubmit() properly and I'm having some difficulties. I want to submit my form with ajax and after change the container value to the result echo by the form. I have an HTML form
<form action="contact.php" method="post" id="contact_form" >
<div id="form-box">
<input type="text" name="name" maxlength="40" >
<input type="submit" name="contact" value="SUBMIT" />
</div>
</form>
And then in JS I use the following code to submit the form to contact.php
$(document).ready(function() {
var options = {
success: showResponse
};
$('#contact_form').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
});
function showResponse(responseText) {
$("#form-box").html("Thank you message");
}
Now, the #form-box changes with my "Thank you message" ... but how do I grab what is echo from contact.php after the script is executed?
I'm not sure how to do this and make it work.
It would be included in the responseText, assuming your PHP file is actually outputting something.
Try updating your function to
function showResponse(responseText) {
$("#form-box").html("Thank you message"+responseText);
}
The 'responseText' parameter contains the response from php file.
function showResponse(responseText) {
console.log(responseText);
$("#form-box").html("Thank you message");
}

Submit Form With Both Action and Onsubmit Function

My JS is not that great so I have been fiddling with this for a while now.
I have a form which is being POST to another file when the submit button is clicked. When it is clicked I also want to show an alert then redirect the user back to a URL.
The redirecting code works just fine on a button where I call the function "onclick" like so:
<button onclick="test()">Return</button>
But I don't want to have an extra button for this...I want the form to POST then show an alert box then go to URL specified but I get not a function error from console, thanks.
<iframe name="noreloadhack" style="display:none;"></iframe>
<form action="http://www.example.com/test.php" onsubmit="return test();" method="post" target="noreloadhack">
JS:
<script>
function test() {
alert('Hello World');
var return_url = document.getElementById('return_url').value;
window.location.href= return_url;
}
</script>
If it makes a difference I have the form target set to a hidden iframe as a hack to not reload page on submit (I know, not the best method). I'm pretty much using 4 form attributes here.
I have some old code that I used to solve a similar situation. Where I wanted to submit a form but not reload the page, here it is. Since there were only 4 input fields I just grabbed the values using jquery.
Javascript:
function processForm() {
var teamMembers=new Array();
console.log($("#"));
var schoolName=$("#schoolname").val();
var teamMembers=new Array();
teamMembers.push($("#contestant1").val());
teamMembers.push($("#contestant2").val());
teamMembers.push($("#contestant3").val());
$.ajax({
method: "POST",
url: "php/register.php",
data: { schoolname: schoolName, teammembers:teamMembers.toString()}
})
.done(function( msg ) {
alert( "Your team is now registered " + msg );
$('#register').hide();
location.reload();
});
// You must return false to prevent the default form behavior
// default being reloading the page
return false;
}
HTML:
<form id="registration_form" onsubmit="return processForm()" method="POST">
<p style="margin:0px;">School Name:</p>
<input type="text" id="schoolname" name="schoolname" autocomplete="off" class="input" required>
<hr>
<p style="margin:0px;">Contestants</p>
<div id="teammembers">
<input type="text" id="contestant1" name="contestant1" autocomplete="off" class="input" required>
<p></p>
<input type="text" id="contestant2" name="contestant2" autocomplete="off" class="input" required>
<p></p>
<input type="text" id="contestant3" name="contestant3" autocomplete="off" class="input" required>
</div>
<input type="submit" id="registered">

Onsubmit event after javascript form submit

I have an upload file form, and i try to upload the file when it's selected,so i tried something like this:
<form enctype="multipart/form-data" method="POST" onsubmit="return
UploadFile(this);">
<input id="upfile" type="file" onchange="this.form.submit();"/>
</form>
The form.submit() works , but of course i need to do some validation on submit,so i tried to run a function:
function UploadFile(file){
alert('Bleah');
return false;
}
On normal circumstances it should return false, and the form shouldn't reload the page,but this doesn't happens.
If i add a submit input into the form, it works as expected:
<form enctype="multipart/form-data" method="POST" onsubmit="return
UploadFile(this);">
<input type="submit" name="upload" value="Upload">
<input id="upfile" type="file"/>
</form>
Can anyone explain me what is wrong please?
Try this:
function UploadFile(file) {
if (file.value === '') {
alert("Invalid File");
} else {
alert('Form will be submitted now!');
document.getElementById('myForm').submit();
}
}
<form enctype="multipart/form-data" method="POST" id="myForm">
<input id="upfile" name="upfile" type="file" onchange="UploadFile(this);" />
</form>
To upload the file when it's selected, you must call UploadFile() function on the input change, not on the form change tag. If you submit on input change, the page gets reloaded.
So, you'd better use something like this:
$('#upfile').onchange(function(){
if(UploadFile(this.parent('form'))){
this.parent('form').submit();
}
})
And you won't need onchange and onsubmit inside the tags any more.
Solution:
<form id="formname" enctype="multipart/form-data" method="POST" action="test.html">
<input id="upfile" type="file" onchange="sendForm()"/>
</form>
<script>
function sendForm() {
var field = document.getElementById("upfile");
if (field) {
console.log("the is a file and the form will be sent");
document.forms["formname"].submit();
}
}
</script>
OLD--
I dont understand, how would you like to submit the form without a submit button? or at least, handle the submission in javascript "object.addEventListener("keydown", myScript);"
--
ok, I read it once again and I understand the question
You need to handle this on javascript and detect the selection of the file. Look at this thread:
how to check if a file is selected using javascript?

Javascript form validation - PHP variable as VALUE - Invalid Input

I have an issue where I am validating form submission with javascript. The form is prefilled with results from the database as PHP values like this:
<form name="profiledit" action="profile_edited.php" method="POST" >
<h3>Name:</h3>
<input type="text" id="teamname" name="teamname"
value="<?php echo $result['teamname'];?>">
</form>
This is the javascript:
<script type="text/javascript">
function empty() {
tn = document.getElementById("teamname").value;
if (! /^[a-zA-Z0-9]+$/.test(tn)) {
alert("Please enter a valid Team Name");
return false;
}
}
</script>
The submit button is :
onClick="return empty();"
The problem is that is always tells me top "Please enter a valid Team Name" unless I retype the text in the box (that was supplied by the PHP value).
I cannot see any weird spaces or things in "view source".
What could the problem be?
Thanks.
EDIT1 : Sorry I forgot to paste closing brace. It was there in the code and this does work for BLANK forms OK. Just not when it has a prefilled value from PHP.
Try this
Check this link
Html
<form name="profiledit" action="" method="POST" id="profiledit">
<h3>Name:</h3>
<input type="text" id="teamname" name="teamname" value=""/>
<input type="button" id="submit" value="submit" name="submit" />
<input type="submit" id="submitform" value="submitform" name="submit" style="display:none;" />
</form>
Jquery
$('#submit').click(function(){
var pattern=/^[a-zA-Z0-9]*$/;
var tn = $("#teamname").val();
if(tn == "" && pattern.test(tn)){
alert('1');
}else {
//alert('2');
$('#submitform').trigger('click');
}
});
Hope its helps
Well, there was nothing wrong with the responses after all. My code was good and you guys code was good as well.
The problem?
Well I just happened to be testing with a teamname that had a SPACE in it!!!!!!!!!!
So having finally worked out that was the problem all along I would like to thank you all for your inputs.
I have used the regex instead : /^\w+( \w+)*$/
Allows words, numbers and a space.

Categories