I am doing ajax cross domain request to my php page on server.
I am posting form from html via ajax to my php page on server.
Have problem with validation in client side.
I don't know how to do validation in client side before send form.
html form is standard form, posting input fields: name, last name, message....
My html form, client side:
<script type="text/javascript">
var output = $('.nesa');
$(document).ready(function(){
$("#form1").submit(function (e) {
e.preventDefault();
$.ajax({
url: 'http://www.example.com/form.php',
crossDomain: true, //set as a cross domain requests
type: 'post',
data: $("#form1").serialize(),
beforeSend: function (){
// add spinner
$('.spinner').append('<img id="animacija" src="spinnersmall.gif" alt="Loading" />');
},
success: function (data) {
$(".nesa").html(data);
alert("sent " + data);
},
error: function(){
output.text('Message is not sent!');
}
});
});
});
How to to validation? I try to put code in beforeSend but without success.
Or maybe to use submitHandler?
Idea is when user click submit, that validation start, and if fails to tell "insert your email address". Now when i click submit it send data to server. I want that first check input fields.
This form is actual working it sending data to server, but just need to figure out how to do validation. Where to put validation in ajax call?
Thanks
Create a function to validate form which return true/false. Call the function just before the $.ajax. check if return is false then return.. see the example below...
if(!validateForm())
return false;
First, are you actually using an AJAX form?
You explained that you load the form itself via AJAX, but do you send it that way, too? It looks to me that you're trying to send it the HTML way. You can hook into the click event of the send button before you send the form. However, since the button is added to the page at runtime, you need to register the event to document.
$(document).on('click', 'input[type=submit]', function() {
// Validate form
// Add error message on fail, and return
// Else submit form via AJAX
});
In either case, you can use jQuery's blur event as an alternative to validate each field when the user jumps to the next. You could even validate every time the user presses a key with keypress.
I always validate them right before I enter them into an AJAX call. Here is my exampel
$('#form_nieuwsbrief').bind('submit',function(){
var name = $('input[name=naamNieuwsbrief]').val();
var email = $('input[name=emailNieuwsbrief]').val();
var proceed = true;
if (name==""){
$('input[name=naamNieuwsbrief]').css({'border':'2px solid red'});
proceed = false;
}
if (email==""){
$('input[name=emailNieuwsbrief]').css({'border':'2px solid red'});
proceed = false;
}
if(proceed == false){
$("#msg").append("<div class='alert alert-danger' role='alert'>U bent informatie vergeten in te vullen.</div>");
setTimeout(function(){
$('.alert').fadeOut(400, function(){
$(this).remove();
})
;},10000
);
}
if(proceed == true){ // make the ajax call
This is just a quick one for a newsletter that just requests name and email. But the principle is the same. Just before you make an ajax call, create the if else statement with a variable you set if something is false. else you stick it tot he original validation, thus you can proceed.
Please validate the form before sending ajax request. If there is no error then ajax request should be send otherwise return false.
You can do like:
$("#form1").submit(function (e) {
e.preventDefault();
// Get the Login Name value and trim it
var name = $.trim($('#name').val());
// Check if empty of not
if (name === '') {
alert('Text-field is empty.');
return false;
}
});
You can see the demo Here's (http://jsfiddle.net/LHZXw/1/)
You can also make a function onKeyup.
You're already validating via server side correct? Why don't you use that same validation rules to appear like your client side - via Ajax. I have a tutorial on how to do that:
http://michaelsoriano.com/how-to-ajax-validate-forms/
Related
basically i have a form and in that form i have a username textbox with a submit button.
now what i want is that before we submit the form i want to send the text value to server so the server could check if the username has not been taken by any other user and then submit the form, based on research i had, i found this tutorial useful https://scotch.io/tutorials/submitting-ajax-forms-with-jquery, altough this tutorial is using php for server coding and i am using java servlet but my ajax script never gets to execute.
here is my code:
<html>
<head>
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"> </script>
<script>
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'username' : $('input[name=UserName]').val(),
};
alert('hello');
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : '../postr', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
</script>
<form class="Registration_Form" id="Registration_Form" action="../postr" method="POST">
<div id="Registeration_Username_DIV" class="Registeration_Username_DIV">
<input type="text" id="Registeration_Username_box" class="Registeration_Username_box"
name="UserName" onblur="Usernameerrorfunc(this, 'Usernameerror_spn', 'Usernamenowallow_spn');" maxlength="30" onclick="textboxfocus(this)"/>
</div>
<div class="Registration_Submit_Div">
<input type="submit" value="submit" id="SumbitForm_btn" class="SumbitForm_btn" name="Submit_btn"/>
</div>
</form>
<script>function Usernameerrorfunc(field, errordiv, Notallowcharserror_SPN){
if (field.value == '') {
field.style.borderColor = "red";
document.getElementById(Notallowcharserror_SPN).style.visibility = "hidden";
document.getElementById(errordiv).style.visibility = "visible";
} else if(!field.value.match(/^[a-zA-Z0-9~`!##\(\.)]+$/)){
field.style.borderColor = "red";
document.getElementById(Notallowcharserror_SPN).style.visibility = "visible";
document.getElementById(errordiv).style.visibility = "hidden";
} else {
field.style.borderColor = "rgb(150,150,150)";
document.getElementById(errordiv).style.visibility = "hidden";
document.getElementById(Notallowcharserror_SPN).style.visibility = "hidden";
}
}</script>
as you can see in my ajax script i have an alert() which it should pop up hello but it never does
Good Morning!
I think there are several things to say about your code. First of all your submit function:
$('form').submit(function(event) { ... }
Here you want to catch the submit-event when the user hits the button. Everything good, but since your button is of type=submit the browser will also react on the click and handle the submit-process by itself. Your function won't get called properly. To prevent this you have to escape the default behaviour of your form on submitting:
$('form').submit(function(event) {
event.preventDefault();
$.ajax({ ... });
}
This will do the trick to let the browser do what you want instead of handling the submit by itself.
So now your browser can run your ajax call.
Next thing: The ajax-call.
You did many things right, but some important things wrong. Look at the following structure:
$.ajax({
url: 'your_url_to_send_data_to',
type: 'post', //the method to use. GET or POST
dataType: 'json',
data: data, //your data: {key1:value1, key2:value2}
success: function(data) { //handle a successfull response (200 OK)
alert(data);
//here you can do with your data whatever you want
},
error: function(jqXHR, textStauts, errorThrown){ //handle every error. e.g. 500
alert(textStatus + ': '+errorThrown);
}
}});
This will handle the sending and the recieving of your request. The success function will get called if the server returns an 200 OK. Otherwise the error function gets called.
Now you just have to handle the request on server side properly.
Third thing: What's about the real submit after the name-check?
Since you preventDefault() the default browsers action, sou have to do it manually. You could think of triggering the submit again, but you would ran another time in your own function you've written so far.
Therefore you have to do it by your own. But wait! You can combine the two things in one call!
Think about this:
let the user fill your form
let him hit the submit button
preventDefault behaviour of your browser and build a FormData and put all your values in it
prepare your ajax call
send the FormData with your ajax call to your server
Handle name-check and all other things on server-side
answer the request
evalutate the answer in your success function
Note: On server side you have to print the application/json header to let the browser and finally your ajax call handle your answer properly.
Since you want a dynamic check of the user name availability, I suggest you react to the keyup event (note: I also added support for other possible change-incurring events in my demo below) and schedule a check run after a fixed delay. Once the delay transpires, if the user hasn't typed anything in the interim, you can run the AJAX check and update the page; if the user did type something in the interim, you can simply not run the check (yet). This means a check will automatically be run after every flurry of typing, as long as the user ceased typing for at least the hard-coded delay.
With regard to submitting, I would just allow the user to submit the form in the normal way without any last-second AJAX check of user name availability. You're still going to have to perform a server-side check for availability, in case the user disabled JavaScript or somehow constructed their own submit HTTP query, so you may as well depend on that server-side check upon form submission. The dynamic AJAX check is really only beneficial as a quick notification to the user, and so should only be provided if the user edits the user name, and then does not submit the form immediately. Most of the time the user will not submit the form immediately after editing a field, and most users can be relied upon to not submit the form if it is clearly indicated on the page that there is a validation failure.
var USERNAME_CHECK_DELAY = 800;
var userInputValCount = 0;
var userInputVal = '';
window.handlePossibleUserInputChange = function() {
let $userInput = $('#userInput');
let $checkDiv = $('#userCheckLine');
// if this event doesn't reflect a value change, ignore it
if ($userInput.val() === userInputVal) return;
userInputVal = $userInput.val();
// update the value count
let userInputValCountCapture = ++userInputValCount; // closure var
// schedule a potential check run
setTimeout(function() {
// only check the current name if the user hasn't typed since the provoking event
if (userInputValCountCapture !== userInputValCount) return;
checkUsername();
},USERNAME_CHECK_DELAY);
// update the status message
if ($userInput.val().trim() === '') {
$checkDiv.text('');
} else {
$checkDiv.attr({'class':'checking'});
$checkDiv.text('checking...');
} // end if
};
$('#userInput')
// listen to all events that could cause a change in the input value
.on('keyup change',handlePossibleUserInputChange)
// drop is special; the drop event unfortunately fires before the text is changed
// so we must defer the call until after the text is changed
// same with mouseup; occurs when clicking the input box X button in IE
// same with paste via context menu, rather than shortcut (which would trigger keyup)
.on('drop mouseup paste',function() { setTimeout(handlePossibleUserInputChange); })
;
var lastTaken = true;
window.checkUsername = function() {
let $checkDiv = $('#userCheckLine');
let $userInput = $('#userInput');
// just reset the check line if the input value is empty
if ($userInput.val().trim() === '') {
$checkDiv.text('');
return;
} // end if
// ... send ajax call, get result ...
// (for demo purposes, just invert the previous result)
let taken = lastTaken = !lastTaken;
if (taken) {
$checkDiv.attr({'class':'taken'});
$checkDiv.text('user name is taken.');
} else {
$checkDiv.attr({'class':'notTaken'});
$checkDiv.text('user name is available.');
} // end if
};
.taken { color:red; }
.notTaken { color:green; }
.checking { color:grey; font-style:italic; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1">
<div>
<input id="userInput" type="text" placeholder="username"/>
<span id="userCheckLine"></span>
</div>
<input type="submit" value="Submit"/>
</form>
I think you should use the "remote" of jquery validation (https://jqueryvalidation.org/remote-method/) this check the validation of the field in the server. You need jquery.
$("#Registration_Form").validate({
rules: {
Registeration_Username_box: {
required: true,
remote: {
url: "check-email.php",
type: "post"
}
}
}
});
I need to detect if the user has leaved the page or if he submit the form, i tried something like this:
window.onbeforeunload = function(e) {
if ($('form').submit() == true) {
console.log('form submitted!');
} else{
console.log('good bye!');
};
};
I need this because if he leave the current page i will run a php code to delete some information but if he submit the form the php will store the information in another place.
Thanks!
I dont't think you can do it like this. You may want to use a classname or some other attribute in the form to mark the submission, either by js if you're submitting with ajax or in php, checking the post / get data.
For example:
$('#submit').on('click', function(e){
//post ajax
,success: function(data){
//do other stuff
$('$myform').addClass('submited');
}
});
Then,
window.onbeforeunload = function(e) {
if ($('#myform').hasClass('submited') {
//do submitted stuff
} else{
// dont
};
};
In case of normal submission, the conditional would have to do with $_POST or $_GET data and the way you build the html in your php file, with the same logic.
I use a jQuery.get() request to send a form data. But often the page reloads/redirects too fast, before my JavaScript/jQuery code catches and sends the form data to where i need. I use alert() to get the ajax request done while the user clicks ok on alert. Now i need the form working as usual (with PHP post and redirect) and to send the form data using jQuery or JavaScript BEFORE the page reloads and NO alerts. Is there any elegant way to make the page wait until jQuery is done with the request (without using alert)?
jQuery('#form').live('submit', function() {
var inputValue = jQuery(this).find('#theInput').val();
jQuery.get('http://someurl.com/order?var=' + inputValue);
//alert('an unwanted alert');
});
UPD: I embed jQuery code through Google Tag Manager's iframe. So I can't change the way the form works. And I shouldn't prevent the form from submitting.
jQuery('#form').live('submit', function(e){
e.preventDefault(); // prevent default behaviour
var inputValue = jQuery(this).find( '#theInput' ).val();
jQuery.get('http://someurl.com/order?var=' + inputValue, function(){
// redirect
});
//alert('an unwanted alert');
});
I would take a look at [done][http://api.jquery.com/deferred.done/] which could probably do what you want it to do. .done() will wait for the entire ajax to finish, and then run whatever function you call within done.
You can bind callback to do redirect and return false; to prevent default redirect shown as below:
jQuery('#form').on('submit', function() {
var inputValue = jQuery(this).find( '#theInput' ).val();
jQuery.get('http://someurl.com/order?var=' + inputValue,
function(data){
//write redirect code here. In case if you want to check response, you can get it in data variable.
});
return false; //prevent default redirect action
});
I've created a form on a clients site and I'm trying to use AJAX for the subscribe form.
The submit seems to just redirect rather than serializing the form and working with AJAX.
I think the issue here is that it doesn't know whether the response data is "success" or not.. possibly utilises a different variable to determine if it was a success or error? It should display the message accordingly to the user either way, ie:
Success -> You have been signed up.
Error -> Invalid email address.
Should also be a message for a blank name entered as it's a required field but unsure how to handle that error.. :/
Complete Fiddle: http://jsfiddle.net/pUd5P/6/
Form
<form id="newsletter" action="http://app.bronto.com/public/webform/process/" method="post">
....
</form>
JS
//ajax subscribe
$( document ).ready( function() {
$("#newsletter").submit( function() {
//Do the AJAX post
//alert("submitting");
alert(data);
$.post($("#newsletter").attr("action"),
$("#newsletter").serialize(),
function( data ) {
//alert(data);
if ( data == 'success' ) {
$('#newsletter-message').html('You have been signed up.')
.removeClass('error')
.css('visibility','visible');
} else {
$('#field-error').html('Invalid email address.')
.addClass('error')
.css('visibility','visible');
}
});
//Stop the normal POST
return false;
});
});
have a look at event.preventDefault()
$("#newsletter").submit(function(event) {
event.preventDefault();
// rest of your code here.
This will prevent the form from submitting in the standard way and refreshing the page and allow your $.post to return results.
I can see you used return false but try this instead (or aswell as) :D
I just dont understand this behavior but make it work
http://jsfiddle.net/pUd5P/12/
it is creating the problem on name = sid so i just changed it to tsid
<input type="hidden" name="tsid" value="37ea72cebcc05140e157208f6435c81b" />
now its making an ajax request, You need to test it on your server as it is giving
Origin is not allowed by Access-Control-Allow-Origin. error.
Alright so i have form validation function.the function runs through form validation functions that returns false if the field isn't valid.
The problem is when it get to the function that uses ajax to check if the field is valid.
for some reason its seems that it doesn't "wait" for ajax to return and returns false automatically.
is there a way around this?
Here is the code:
function form_validation(){
if (!NewValidationForm('pcode', 'Please fill in all the fields'))
return false;
if (!NewValidationForm('fname', 'Please fill in all the fields'))
return false;
if(!validate_coupon()){
alert("bad!!");
return false;
}
return true;
}
function validate_coupon(){
var url = $j("#site_url").val() + 'ajax_functions.php';
var coupon = $j("#pcode").val();
var result_status = false; // seem its jumps from here to:
$j.ajax({
type: "POST",
url: url,
data: { ajax: 'ajax', coupon: coupon}
}).success(function(insertID){
var obj = $j.parseJSON(insertID);
if(obj.status == 1){
result_status = true;
}
});
// straight over here
if(result_status == true){
return true;
}
}
Usually in this situation I do something like this in $(document).ready():
$('form').submit(function (evt) {
if (!$(this).attr('data-submitted')) {
evt.preventDefault();
$(this).attr('data-submitted', 'true');
// call your form validation code here that fires the ajax request
return false;
}
return true;
});
Then, in your $.ajax callback, when your validation completes, call $('form').submit(). This effectively uses an attribute on the form as a flag for whether the state of the validation request. When the user first submits the form, the flag gets set and the validation process begins. When the validation completes, the form's submit event is triggered, and since the flag is set, this time the form gets submitted like normal.
If this approach works for you, you'll probably want to add a little polish. For example, you'll probably want to disable the submit button before calling $.ajax and enable it again if the validation fails. You'll also probably want to remove the data-submitted attribute from the form if the validation fails, since the user might submit the form a second time and you presumably want to perform another validation in that case.