Script won't stop after failing validation - javascript

I am using javascript validation for my input box from javascript-coder and it works fine on my non-ajax pages but when I use ajax to POST inputs the script runs through without stopping even if validation fails. I tried an example from here but when I tried the suggestion the validation didn't work at all. In my ajax script I can get everything to work with jquery validation by simply putting this in before posting data:
var frm = $(this).closest('form');
if($(frm).valid()){
But I really want to stick with this validation library so I am hoping someone in the community more familiar javascript and maybe even this validation library can help me find an equivalent because I haven't been able to find anything in all the documentation that allows you to test if validation failed or not before moving my ajax script forward.
My form:
<form method="post" name="send_message_frm" id="send_message_frm">
<div style="margin-top:20px;"></div>
<fieldset>
<div class="clear"></div>
<div style="margin-top:20px;"></div>
<label>Product Group Name:</label>
<input name="desc" class="text-input medium3-input required" type="text" id="desc" value="">
<div style="color:red;" id='send_message_frm_desc_errorloc' ></div>
<div style="margin-top:20px;"></div>
</fieldset>
<input name="user" class="text-input medium3-input" type="hidden" id="user" value="<?php echo $myid ; ?>">
<div style="margin-top:20px;"></div>
<input type="submit" id="send-message" name="submit" value="Send" class='button' />
<div style="margin-top:20px;"></div>
</form>
<script type="text/javascript">
var frmvalidator = new Validator("send_message_frm");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("desc","alnum","Only numbers and letters are allowed");
frmvalidator.addValidation("desc","req","Please enter a description");
</script>
My Ajax script:
<script type="text/javascript">
$(document).ready(function(){
//Validate form....what can I put here to test if validation is completed properly????
//onclick handler send message btn
$("#send-message").click(function(){
$(this).closest('form').submit(function(){
return false;
});
var frm = $(this).closest('form');
$("#ajax-loading").show();
var data = $(frm).serialize();
$(frm).find('textarea,select,input').attr('disabled', 'disabled');
$.post(
"productgroup_add.php",
data,
function(data){
$("#ajax-loading").hide();
$(frm).find('textarea,select,input').removeAttr('disabled');
$("#send_message_frm").prepend(data);
}
);
}
);
});
</script>

After reviewing the validation script, I discovered (as suspected) that it attaches the validation method to the form's OnSubmit event handler, which sounds about right...
this.formobj.onsubmit = form_submit_handler;
But... it also attaches itself to the form object:
this.formobj.validatorobj = this;
which has a method that you can call to validate your form:
if (!this.runAddnlValidations())
To run the validations, it looks like you can just do something like:
if(!document.forms[0].validatorobj.runAddnlValidations()) return;

Related

Submit checkbox value on form without page refresh AJAX PHP

I just started learning ajax and its really great and time saving i agree.
But i got stuck at this point sending form data without page reload.
Below is my html code.
<form id="form4" method="post">
<input type="checkbox" name="test" id="agreed" value="check">
<br>
<br>
<input type="submit" id="form-submit" name="submit" value="Send">
<p class="form-message"></p>
</form>
Below is my Ajax script
<script>
$(document).ready(function() {
$("#form4").submit(function(event) {
event.preventDefault();
var action = 'another_test';
var agreed = $("#agreed").val();
var submit = $("#form-submit").val();
$(".form-message").load("test3.php", {
test: agreed,
submit: submit,
action: action
});
});
});
</script>
Below is my php code
<?php
if (isset($_POST['action'])) {
if ($_POST['action'] == 'another_test') {
$test = $_POST["test"];
$errorEmpty = false;
if (!empty($test)) {
echo "<p>Click the checkbox pls</p>";
$errorEmpty = true;
}
else {
echo "<p>Checkbox clicked</p>";
}
} else {
echo "Error.. cant submit";
}
}
?>
<script>
var errorEmpty = "<?php echo $errorEmpty ?>";
</script>
The php file is on another page called test3.php
This particular code works if it was an input text but doesn't work for a checkbox.
Please help me so i can learn well.
Thanks in advance.
.load() (as per the documentation) performs a GET request, not a POST, but your PHP is (as shown by the $_POST references) expecting a POST request - and it usually makes sense to submit form data using POST.
So you'd be better to use $.post() - this will send a POST request. Then you can handle the response and load it into your "form-message" element in the "done" callback triggered by that request.
N.B. You could also make the code shorter by putting the "action" variable as a hidden field in the form, and then simply serialize the form in one command instead of pulling each value out separately.
Example:
HTML:
<form id="form4" method="post">
<input type="checkbox" name="test" id="agreed" value="check">
<br>
<br>
<input type="submit" id="form-submit" name="submit" value="Send">
<input type="hidden" action="another_test"/>
<p class="form-message"></p>
</form>
JavaScript
$(document).ready(function() {
$("#form4").submit(function(event) {
event.preventDefault();
$.post(
"test3.php",
$(this).serialize()
).done(function(data) {
$(".form-message").html(data);
});
});
});
Documentation:
jQuery Load
jQuery Post
jQuery Serialize

Can't get my simple JavaScript Event Handler working

I am trying to get an event handler on an HTML form. I am just trying t get the simplest thing working, but I just cannot see what I am missing.
It is part of a wider project, but since I cannot get this bit working I have reduced it down the most very basic elements 1 text field and a button to try and see what it is I am missing.
All I want to do is get some text entered and flash up message in a different area on the screen.
The user enters text into the input field (id=owner).
The plan is that when the button (id="entry") is pressed the event handler (function "entry") in the entry.js file should cause a message to display.
I don't want the form to take me to a different place it needs to stay where it is
I just want some form of text to go in the: <div id="feedback" section.
When I can get it working: I intend the create the text from the various text fields that get entered.
I Know that this is beginner stuff & I know that I have reduced this down such that it barely worth thought but I would welcome any input please & thank you.
HTML code is:
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>
<script src="entry.js"></script>
Code for entry.js is:
function entry() {
var elOwner = document.getElementById('owner');
var elMsg = document.getElementByID('feedback');
elMsg.textContent = 'hello';
}
var elEntry = document.getElementById('entry');
elEntry.onsubmit=entry;
I have tried:
Adding in a prevent default:
window.event.preventDefault();
doing this through an event Listener:
elEntry.addEventListener('submit',entry,false);
using innerHTML to post the message:
elMsg.innerHTML = "
At present all that happens is that the pushing submit reloads the page - with no indication of any text being posted anywhere.
One issue is that you have a typo, where getElementById capitalized the D at the end.
Another is that preventDefault() should be called on the form element, not the input.
Here's a working example that corrects those two mistakes.
function entry(event) {
var elOwner = document.getElementById('owner');
var elMsg = document.getElementById('feedback');
elMsg.textContent = 'hello';
event.preventDefault();
}
var entryForm = document.getElementById('entry').form;
entryForm.onsubmit = entry;
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>
I also defined a event parameter for the handler. I don't remember is window.event was ever standardized (it probably was), but I'd prefer the parameter.
Be sure to keep your developer console open so that you can get information on errors that may result from typos.
var elEntry = document.getElementById('entry');
elEntry.addEventListener("click", function(e) {
e.preventDefault();
var elMsg = document.getElementById('feedback');
elMsg.textContent = 'hello';
});
<form method="post" action="">
<label for="owner">Input Owner: </label>
<input type="text" id="owner" />
<div id="feedback"></div>
<input type="submit" value="enter" id="entry" />
</form>

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'];

submit my form through ajax using javascript

Just wanted to ask, how will i submit my form through ajax using javascript.
Here's my code:
<script>
function show_edit(bugid,device)
{
document.getElementById('updateform').style.visibility='visible';
document.getElementById('U_bugid').value=bugid;
document.getElementById('U_device').value=device;
}
function hide()
{
document.getElementById('updateform').style.visibility='hidden';
}
</script>
Here's my hidden form
<div id"update_form" >
<form onsubmit="ajax_submit();">
<fieldset>
<label for="maskset">MASKSET</label><input type='text' name='bugid' id='U_bugid' readonly >
<label for="device">DEVICE</label><input type='text' name='device' id='U_device' readonly>
<label for="reason">Comments</label><textarea rows=10 cols=40 name='reason'></textarea>
<input id="S_update" class='S_update' value="Update Data" type="submit" >
</form>
</fieldset>
</div>
Can i put it this way below, when i click submit it will immediately submit through ajax code together with my new comment(from textarea):
function show_edit(bugid,device)
{
var maskset;
document.getElementById('updateform').style.visibility='visible';
document.getElementById('U_bugid').value=bugid;
document.getElementById('U_device').value=device;
function ajax_submit()
{ //code in submitting ajax i already know; }
}
Will this work?
It seems that what you want to do is to stop the submition of your code you need to add onsubmit="return ajax_submit()" to your HTML and make sure the function return false.
function ajax_submit()
{
return false;
}
By the looks of your code you would greatly benefit from getting with jQuery in order to select DOM elements as it will simplify your life greatly.
On that note it would make your life a hell of a lot easier using jQuery Ajax. Specially if you read up on jQuery AJAX functions .
$.post("test.php", { bugid: $('#U_bugid').val(), device: $('#U_device').val() } );

E-mail form interactivity

I'm a web development student and I need some help. I have the code below; How do I make it work only when the form is submitted and not the text field is clicked. I also would like it to get and insert the textField's value in the .thanks Div. Please help me learn.
<script type="text/javascript">
$(document).ready(function(){
$(".quote").click(function(){
$(this).fadeOut(5000);
$(".thanks").fadeIn(6000);
var name = $("#name").val();
$("input").val(text);
});
});
</script>
<style type="text/css">
<!--
.thanks {
display: none;
}
-->
</style>
</head>
<body>
<form action="" method="get" id="quote" class="quote">
<p>
<label>
<input type="text" name="name" id="name" />
</label>
</p>
<p>
<label>
<input type="submit" name="button" id="button" value="Submit" />
</label>
</p>
</form>
<div class="thanks"> $("#name").val(); Thanks for contacting us, we'll get back to you as soon as posible</div><!-- End thanks -->
This is a bit rough and ready but should get you going
$(document).ready(function(){
$("#submitbutton").click(function(){
//fade out the form - provide callback function so fadein occurs once fadeout has finished
$("#theForm").fadeOut(500, function () {
//set the text of the thanks div
$("#thanks").text("Thanks for contacting us " + $("#name").val());
//fade in the new div
$("#thanks").fadeIn(600);
});
});
});
and I changed the html a bit:
<div id="theForm">
<form action="" method="get" id="quote" class="quote">
<p>
<label>
<input type="text" name="name" id="name" />
</label>
</p>
<p>
<label>
<input type="button" name="submitbutton" id="submitbutton" value="Submit" />
</label>
</p>
</form>
</div>
<div id="thanks">Thanks for contacting us, we'll get back to you as soon as posible</div><!-- End thanks -->
There are several things at issue here:
By using $('.quote').click(), you're setting a handler on any click event on any element contained within the <form>. If you want to catch only submit events, you should either set a click handler on the submit button:
// BTW, don't use an id like "button" - it'll cause confusion sooner or later
$('#button').click(function() {
// do stuff
return false; // this will keep the form from actually submitting to the server,
// which would cause a page reload and kill the rest of your JS
});
or, preferably, a submit handler on the form:
// reference by id - it's faster and won't accidentally find multiple elements
$('#quote').submit(function() {
// do stuff
return false; // as above
});
Submit handlers are better because they catch other ways of submitting a form, e.g. hitting Enter in a text input.
Also, in your hidden <div>, you're putting in Javascript in plain text, not in a <script> tag, so that's just going to be visible on the screen. You probably want a placeholder element you can reference:
<div class="thanks">Thanks for contacting us <span id="nameholder"></span>, we'll get back to you as soon as possible</div>
Then you can stick the name into the placeholder:
var name = $("#name").val();
$('#nameholder').html(name);
I don't know what you're trying to do with the line $("input").val(text); - text isn't defined here, so this doesn't really make any sense.

Categories

Resources