Here is code
<script type='text/javascript'>
$("#focusform").submit(function(event)
{
event.preventDefault();
var $form = $( this ),
usname = $form.find( 'input[name="name"]' ).val(),
uspass = $form.find( 'input[name="pass"]' ).val();
if($('#chk').is(':checked')) var checked='yes';
else var checked='no';
$.post("/login/submit/", { name: usname, pass: uspass, checkbox: checked, template_framed:"yes",submit: "yes" }, function(data)
{
if(data=='error'){
alert("You have made an error");
return false;
}
else{
if(checked=='yes')window.location='/usercookie/';
else window.location='/login/success/';
return true;
}
});
});
</script>
But browser doesn't want to promt whether save password or not. Cant't you help me?
I would do a pre check and use Ajax to check the is correct, this would then return the error or success message, if success continue to post the form otherwise display the error using Ajax
The browser won't offer to save passwords if your <form> doesn't have an action URL and doesn't have a submit button. Your password field must also be an <input type="password" />.
It doesn't work when you try to assign the submit function with jQuery in that way:
$("#focusform").submit( ...
However it does work if you add an onsubmit attribute to the form:
<form id="focusForm" action="page.php" method="post" onsubmit="return mySubmit()">
^^ here
And then return false in your submit function:
function mySubmit()
{
// do the jquery ajax or whatever you want to do here
return false;
}
<iframe id="temp" name="temp" src='/engine/blank.html' style="display:none"></iframe>
<form id='focusform' target='temp' method='post' onsubmit="return mySubmit()">
...
</form>
<script type='text/javascript'>
function mySubmit()
{
var $form = $("#focusform"),
usname = $form.find( 'input[name="name"]' ).val(),
uspass = $form.find( 'input[name="pass"]' ).val();
var checked = ($('#chk').is(':checked')?'yes':'no');
$.post("/login/submit/", { name: usname, pass: uspass, checkbox: checked, template_framed:"yes",submit: "yes" }, function(data)
{
if(data=='error'){
alert("<?=$lang['made_error']?>");
}
else{
alert("Loged in");
}
});
}
</script>
And it works :)
Related
I have a form with the action attribute set to "/tasks/". All I want is that on submitting the form, the data go to "/tasks/", but the user is not redirected to "/tasks/", they just stay on "/" instead. Is it possible to achieve?
I tried to add "return false" and "preventDefault" to the "onclick" handler, but that's not what I need as they cancel the form submission.
<form id="add-task-form" method="POST" name="add-task-form" action="/tasks/" enctype="multipart/form-data">
<label for="name" class="field-description">*Name</label>
<input id="name" type="text"required name="name" autofocus="true"><br>
<label for="description-text" class="field-description">*Description</label>
<textarea id="description-text" name="description"></textarea><br>
<button type="submit" id="save-button" class="saveButton"><span>Add task</span></button>
</form>
$('#save-button').on( 'click', function(){
if($('input').data().length() != 0){
var data = $('#add-task-form form').serialize();
$.ajax({
method: "POST",
url: '/tasks/',
data: data,
success: function(response){
$('#add-task-form').css('display', 'none');
var task = {};
task.id = response;
var dataArray = $('#add-task-form form').serializeArray();
for(i in dataArray) {
task[dataArray[i]['name']] = dataArray[i]['value'];
}
appendTask(task);
getTasksCount();
}
});
return false;
$('#home-page').show();
$('#add-task-page').remove();
};
})
I'm new to js and jQuery and they are definitely not my strongest points, so please, advice.
It's shall work like this :
$('#save-button').click(function(event) {
event.preventDefault();
...
});
to know more about it : https://api.jquery.com/event.preventdefault/
You can do something like this.
$(document).ready(function(){
var $form = $('form');
$form.submit(function(){
$.post($(this).attr('action','/tasks/'), $(this).serialize(), function(response){
// Do something
},'json');
return false;
});
});
quotation
if you want to prevent it all, you can use event.preventDefault(). But since you are using ajax and you don't want to reload the page, you can try to apply this code:
$("#save-button").click(function(){
$.post('{post_url}',
$("#add-task-form form").serializeArray(),
function(data){
if (data.success){
redirect = '{last}';
} else {
reload(true);
}
},"json"
);
});
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.
I have a form that validates a value at a time. When all the values are validated and correct my ajax post function does not want to post. I would like to post when all the values are correct. One text field has a name, the last text field is an email.
Please check my jsFiddle and the code below.
HTML:
<form enctype="multipart/form-data" method="post" id="myform" name="myform_1">
<input type="text" value="" id="name" name="myname" />
<input type="text" value="" id="email" name="myemail"/>
<input type="submit" value="Valid" id="validate" name="validate"/>
</form>
Javascript:
$(document).ready(function(){
function checkLength( o, n, min, max ) {
if ( o.val().length > max || o.val().length < min )
{
o.css("background-color","#F30");
return false;
}
else
{
o.css("background-color","#FFF");
return true;
}
}
function checkRegexp( o, regexp, n ) {
if ( !( regexp.test( o.val() ) ) )
{
o.css("background-color","#F30");
return false;
}
else
{
o.css("background-color","#FFF");
return true;
}
}
//Click action
$("#validate").click(function()
{
var name = $( "#name" );
var email = $("#email");
var valid = true;
emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
valid = valid && checkLength( name,"Please enter a name",3,6);
valid = valid && checkRegexp( name, /^[a-z]([A-Z_\s])+$/i, "Name may consist of a-z, and 3 or more characters." );
valid = valid && checkLength( email, "email", 6, 80 );
valid = valid && checkkRegexp( email, emailRegex, "eg. ui#jquery.com" );
//Email
//alert ($("#myform").serialize());
//End of Email
if(valid)
{
var request = $.ajax({
url: "inc/newsletter.php", // Ofcourse this would be your addLike.php in your real script
type: "POST",
data: $("#myform").serialize()
});
request.done(function(msg) {
alert("Your details have been saved");
location.reload();
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
return valid;
}
else
{
alert("No;")
}
});
});
Your submit event handler is not returning false, hence it is posting the form completely. First, make sure the event bubbling is stopped in the click handler
in the following manner:
$("#validate").click(function(event)
{
//YOUR AJAX CALL
//RETURN SHOULD ALWAYS BE FALSE FOR AJAX SUBMISSION WHEN CALLED FROM TYPE BUTTON
event.preventDefault();
event.stopPropagation();
return false;
})
You can then trace if the ajax call happens in the browser console...
Hope it helps!
Friend, youre calling this function "checkkRegexp" that doesnt exist!!
And you should return false at the end of youre function to prevent the form submission if some validation goes wrong!
You should also have a look at "parsley". This will help you with form validations.
Change the start of your function like this
$("#validate").click(function(e){
e.preventDefault();
//Rest of your function
}
e.preventDefault() is not cross browser compatible and might break in older browsers. Use the following if you support older browsers
if(e.preventDefault()!=undefined){
e.preventDefault();
}else{
e.returnValue = false;
}
If you are interested in knowing why your approach is not working. The button you are clicking is a submit button and you are not preventing it default behavior. This is the reason that form is submitted even though your form fields are incomplete.
Point to note is still ajax cal won't be called in example provide but it will be natural form refresh.
Solution provided will stop default action and will give full control to your ajax request and validations
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?
I have this form:
<form method='post' id='registration'>
...
<input type='submit' value='Submit' />
</form>
And a script which send the form via POST:
<script>
$(document).ready(function(){
$( "#registration" ).submit(function(event) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var form = $(this);
var username = form.find( "input[name='username']" ).val();
var password = form.find( "input[name='password']" ).val();
var url = "action.php";
// Send the data using post
$.post( url, {
username: username,
password: password
});
});
});
</script>
I have written Validate() function also. Where is the right place to add it and how?
I'd personally do it right before the post.
if (validate()) {
$.post();
{
This requires your function validate() to return either false or true if the form is valid.
#Rebirth is quite right.
#Nikolay Tsonev, Why don't you put
var form = $(this);
var username = form.find( "input[name='username']" ).val();
var password = form.find( "input[name='password']" ).val();
var url = "action.php";
into your Validate() function.
and it would just go like directly like;
event.preventDefault();
if (validate()) {
$.post();
{