I am trying to call my ajax code after my js validate() methods returns true on submit of the searchId button. But the ajax code is not executing. if I place an alert there it works fine.
Where I am doing wrong? Please help!!
here is my javascript code
<script language="JavaScript">
function validate()
{
var msg = "";
//all my field validations are here
msg += "o Name is not a valid name.\n";
if (msg > "") {
alert(msg);
return false;
}
else {
return true;
}
}
$(document).ready(function(){
$("#simple-post").click(function()
{
$("#ajaxform").submit(function(e)
{
// getting the values of both firstname and lastname
var beginDate = $('input[name="txtBeginDate"]').val();
var endDate = $('input[name="txtEndDate"]').val();
var mdnVal = $('input[name="txtMsid"]').val();
// posting the values
var dataString = 'beginDate=' + beginDate + '&endDate=' + endDate+ '&mdnVal=' + mdnVal;
alert(dataString);
var formURL = $(this).attr("action");
//alert(formURL);
$.ajax(
{
url : formURL,
dataType:'json',
async: false,
data: dataString,
beforeSubmit: validate,
success:function(data){
queryObject = eval('(' + JSON.stringify(data) + ')');
queryObjectLen = queryObject.empdetails.length;
drawChart();
},
error : function(xhr, type) {
alert('server error occoured')
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#ajaxform").submit(); //Submit the FORM
});
});
Here is my HTML code
<form name="ajaxform" id="ajaxform" action="getData.jsp" onSubmit="return validate();" method="POST">
<Table>
<input type="submit" name="action" value="Search" id="searchId">
<input type="text" name="name" id="id" size="10" maxlength="10">
//other input fields
</table>
</form>
<button class="btn btn-info" id="simple-post">Run Code</button>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
UPDATE
I have updated my code, i can submit my form, but the validation not working. I am using beforeSubmit: validate, still i dont see my validation messages. Please help.
I fxed the problem. Added a Submit button markup and removed Run Code. Changed onsubmit to onclick on the submit button. Again removed $("#simple-post").click(function() form my jquery code.This seems to be working fine now.
Thanks to this post
Validate a form with javascript before submitting with ajax?
Related
I'm developing my Django application and I would like to use JavaScript in order to improve my website.
I have a form and I would like to display 2 things :
Confirm the form before submit
If form is well submitted, display a message : 'Form is saved'
It's the first time I'm using JS and I need help to make this process.
This is my code :
<form class = "form" method='POST' action=''> {% csrf_token %}
<br></br>
{{ form.as_p}}
<br></br>
<button type="submit">Valider</button>
</form>
<script>
$('#form').submit(function() {
var c = confirm("Click OK to continue?");
return c; //you can just return c because it will be true or false
});
</script>
And if my form is valid and saved :
<script type="text/javascript" >
$(document).on('Valider', 'form.form', function(form) {
var $form = $(form);
$.ajax({
url:"/path_to_my_html_file/BC_form2.html",
type: "POST",
success: function(form) {
alert("Form is saved");
}
});
});
</script>
Could you help me ?
Thank you
You can try to adopt by your purpose this code:
$('#form').submit(function(e) {
// Prevents form to be submitted by default post request with page reloading
e.preventDefault();
if (confirm("Click OK to continue?")) {
// Here you can call your AJAX request
callAjax($('input[type=text]').val())
}
});
function callAjax(value) {
// Making AJAX request to your endpoint
// GET ipify just for example
$.ajax({
url:"https://api.ipify.org?format=json",
type: "GET",
success: function(form) {
alert("Form is saved");
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<input type="hidden" value="MOCK FOR CSRF TOKEN" />
<br></br>
<input type="text" required />
<br></br>
<button type="submit">Valider</button>
</form>
Use .valid() in submit function
$('#form').submit(function() {
var isValid=$("#form").valid();
if (isValid) { //If there is no validation error
var c = confirm("Click OK to continue?");
if(c){
$.ajax({
url:"/path_to_my_html_file/BC_form2.html",
type: "POST",
success: function(form) {
alert("Form is saved");
}
});
}
}
else {
alert('form is not valid');
}
});
</script>
I have a new problem. My whole website is written in PHP as well as all validations. Is there a way to do validations in php and then execute javascript like the example bellow?
if (#$_POST['submit']) {
if ($txt == "") {
$err = "No comment";
}
else {
echo "<script type='text/javascript'>
function myFunction() {
var txt' = '$txt';
var dataString = 'txt=' + txt;
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: dataString,
cache: false,
success: function(php) {
alert(php);
}
});
}
</script>";
}
}
<div id="text">
<form action="" method='POST'>
<textarea maxlength="2000"></textarea>
<input type='button' onclick="myFunction()" name='submit' value='post' />
</form>
</div>
This doesn't work. So I'm wondering how should I do it?
I guess forms don't work with javascript, but how do I do it without a form?
You don't need to use php at all. You can post your textarea data like in the below example.
HTML
<div id="text">
<textarea id="txtArea" maxlength="2000"></textarea>
<button id="btnSubmit" name='submit'>post</button>
</div>
Javascript/jQuery
$("#btnSubmit").on('click',function(e) {
e.preventDefault();
var txtValue = $("#txtArea").val();
if(txtValue.length==0) {
alert("You have not entered any comments");
} else {
$.ajax({
type: 'POST',
url: 'ajaxjs.php',
data: {txt:txtValue},
cache: false
})
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
});
}
});
The solutions is:
1. add function for submit event.
2. call ajax with form fields values as data.
3. do vildation inside php called with ajax request and return status code (valid/not valid)
4. analyse code in js and output error/success message.
First of all: Your code has a couple of errors.
You are asking if $txt == "" whilst $txt was not visibly set.
Your text area has no name
Your if doesn't ask if empty($_POST["submit"])
Second of all: You mentioned that you want the code to be executed on submit of the form. Therefore you can simple do this:
<form onsubmit="formSubmit();">
...
</form>
<script>
function formSubmit()
{
if(...)
{
return true; // Valid inputs, submit.
}
return false; // Invalid inputs, don't submit.
}
</script>
The return false is important because if it would miss, the form would be submitted as usual.
Good morning, I want to send to an external site to my two variables by post are username and password and the page I create a cache in the browser when I go to another url already be logged in code what I do is check for through PHP if the data is correct or not, if they are correct returned if, but returns no, if they are correct what I want to do is force the form to send the submit the url, the problem is that everything works fine to the point the submit the form no longer do anything, can you help me?
Thank You
My code:
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#submit").click(function () {
var user = $("#user").val();
var pass = $("#pass").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'user=' + user + '&pass=' + pass;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
cache: false,
success: function (result) {
if (result == 'si') {
$("form").attr('action', 'http://xzc.tv/login');
$("form").submit();
//window.open('http://xzc.tv');
alert('entro if');
return true;
} else {
alert('entro else');
}
}
});
return false;
});
});
</script>
</head>
<body>
<form action="" method="post" id="formoid">
<div><label>Usuario:</label><input name="user" placeholder="Usuario" type="text" id="user"></div>
<div><label>Contraseña:</label><input name="pass" placeholder="Contraseña" type="text" id="pass"></div>
<div><input name="enviar" type="submit" value="Enviar" id="submit"></div>
<div><input name="btnPass" type="submit" value="¿Olvidaste tu contraseña?"></div>
</form>
</body>
Just declare the event parameter in the click handler, and then do event.preventDefault(). Doing so, the default submit action is ignored and your code will be executed instead:
$(document).ready(function () {
$("#submit").click(function (e) {
e.preventDefault();
var user = $("#user").val();
var pass = $("#pass").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'user=' + user + '&pass=' + pass;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
cache: false,
success: function (result) {
if (result == 'si') {
$("form").attr('action', 'http://xzc.tv/login');
$("form").submit();
//window.open('http://xzc.tv');
alert('entro if');
return true;
} else {
alert('entro else');
}
}
});
return false;
});
});
checkout the result whether its returning "si" if its correct
try
changing code
from
$("form").attr('action', 'http://xzc.tv/login');
$("form").submit();
to
$("#formoid").attr('action', 'http://xzc.tv/login');
$("#form").submit();
try using id of form
To submit try the following
$("form#formoid").submit();
$("form#formoid")[0].submit();
$("form#formoid").submit(function(e) {});
My contact form works well in Chrome & Safari but it doesn't work in Firefox or IE. It keeps submitting as a GET. Can anyone find the problem?
<form action="#" id="contactForm">
<input type="submit" id="contactClick" class="button white" style="margin-top:-2px;" name="submit" value="Send it!">
</form>
var $contactClick = $("#contactClick"),$contactForm = $("#contactForm"),$emailText = $("#emailText"),$emailSubmit = $("#emailSubmit"),$form = $("#contactForm"), $emailSubmit = $("#emailSubmit");
$("#contactForm").submit(function(){
event.preventDefault();
$contactClick.attr('disabled', 'disabled');
$contactClick.attr('value', 'Sending . . .');
var url = "/backend/page-content/emailPOST.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $contactForm.serialize(), // serializes the form's elemWorkents.
success: function(data)
{
$emailText.text(data);
$emailSubmit.fadeIn(400);
$contactClick.removeAttr('disabled');
$contactClick.attr('value', 'SEND IT!');
var noticeLength = $emailText.text();
if(noticeLength.length > 27){ $contactForm[0].reset(); }
}
});
return false;
});
You do not have event argument in the callback function.
$("#contactForm").submit(function(event)
I have a form that submits via Ajax. After the user sends the form, the text changes displaying the form was sent successfully and then shows the form filled out. I want to display the form but I don't want them to re-submit the form so I want to disable the inputs as well as the submit button. I tried adding: $('#submit_btn').className +=" disabled" to the ajax script but it just made the page refresh without submitting anything.
The ajax script is as follows:
$(function() {
$('.error').hide();
$('input.text-input').css({backgroundColor:"#FFFFFF"});
$('input.text-input').focus(function(){
$(this).css({backgroundColor:"#FFDDAA"});
});
$('input.text-input').blur(function(){
$(this).css({backgroundColor:"#FFFFFF"});
});
$(".button").click(function() {
// validate and process form
// first hide any error messages
$('.error').hide();
var name = $("input#name").val();
var email = $("inputemail").val();
var phone = $("inputphone").val();
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "http://www.green-panda.com/website/panda/webParts/contact-form.php",
data: dataString,
success: function() {
$('#myModalLabel').html("<h3 class='text-success' id='myModalLabel'>Contact Form Submitted!</h3>")
$('#myModalSmall').html("<p class='muted'>Your submiessions are below. We will be contacting you soon, you may now close this window.</p>")
$('#submit_btn').className +=" disabled"
.hide()
.fadeIn(1500, function() {
$('#message').append("<i class='icon-ok icon-white'></i>");
});
}
});
return false;
});
});
runOnLoad(function(){
$("input#name").select().focus();
});
How could I possibly disable the inputs and button after a successful form submission?
http://jsfiddle.net/gY9xS/
Actually it's a lot simpler than what you're trying to do, you don't need to disable the inputs, simply cancel the submit after the ajax request:
$('form').submit(function(){
return false;
});
Put it inside the success handler of your ajax request.
If you want to disable the submit button, replace this wrong thing:
$('#submit_btn').className +=" disabled"
With:
$('#submit_btn').prop("disabled", true);
In my application, i just disabled the submit button and shows some progress message
function submitForm(formObj) {
// Validate form
// if (formObj.email.value === '') {
// alert('Please enter a email');
// return false;
// }
formObj.submit.disabled = true;
formObj.submit.value = 'Log In...';
return true;
}
<form class="form-login" accept-charset="UTF-8"
method="POST" action="/login" onsubmit="return submitForm(this);">
......
<input type="submit" id="login-submit" name="submit" value="Log In">
</form>