I have a form with AJAX submit.
This form is working, but I have the impression that the functions are not correct.
jQuery(document).ready(function(){
var myForm = $("#ajax_form"), email = $("#email"), emailInfo = $("#emailInfo"), ck1 = $("#ck1"), ck2 = $("#ck2"), ck3 = $("#ck3");
jQuery('#ajax_form').submit(function(){
var dados = jQuery( this ).serialize();
jQuery.ajax({
type: "POST",
url: "check.php", // Checking data
data: dados,
beforeSend: function(){
emailInfo.html("<font color='blue'>Checking..</font>");
if(dados == "email=") // >>> This field, how to check if the field is blank?
{
email.focus();
emailInfo.html("<font color='red'>Required.</font>");
return false;
}
},
success: function(data){
if(data == "invalid")
{
emailInfo.html("<font color='red'>Invalid.</font>");
}
else if(data != "0")
{
email.val(data); // This field, how to display the data sent in the email field? not the return of PHP,
ck1.css("display", "none");
ck2.css("display", "inline");
}
else
{
ck1.css("display", "none");
ck2.css("display", "none");
ck3.css("display", "inline");
}
}
});
return false;
});
});
I think that has a lot of wrong code, for example:
if(dados == "email=") // >>> This field, how to check if the field is blank?
and >>
email.val(data); // This field, how to display the data sent in the email field? not the return of PHP,
I tried to update but not return any results
Test Code
//if (email.val() == "")
//{
//email.focus();
alert(email.val()); // op1
alert(dados); // op2
alert($.trim($('email').val())); // op3
emailInfo.html("<font color='red'>Required.</font>");
return false;
//}
if insert an email, the only option that returns is op2 email=teste#teste.com
I think your code is trying to validate email by ajax before submitting form. If so this code seems ok to me out of a few points.
return false at the end of submit call may not work on firefox. Use e.preventDefault();. Look at this post. If you try this code on chrome it may fail beacuse you have no return true anywhere.
Your second code block is ok. email.val(data); is equal to $("#email").val(data);. I think you are trying to set the email input value to the result.
if(dados == "email=") can be changed to if (email.val() != ''). So you wont need to dados also.
You don't use myForm variable nowhere. It should be deleted.
If validating the email on server side is not a must think about validating on client side.
The returned data value is echoed from your PHP file. There are two approaches to take to validate your data:
Do it in the frontend with JS prior to sending your form.
Do it with your PHP code in the separate file.
email.val(data); // This field, how to display the data
sent in the email field? not the return of PHP
I am guessing that you want to ensure that the value doesn't get deleted if the user sends an invalid request (thus having to type the value in again).
What you can do is store the values of what the user has entered on form submit but prior to sending the AJAX request: var emailVal = email.val();
jQuery(document).ready(function(){
var myForm = $("#ajax_form"), email = $("#email"), emailInfo = $("#emailInfo"), ck1 = $("#ck1"), ck2 = $("#ck2"), ck3 = $("#ck3");
jQuery('#ajax_form').submit(function(){
var dados = jQuery( this ).serialize();
var emailVal = email.val(); // Assign the entered input to an emailVal variable
jQuery.ajax({
type: "POST",
url: "check.php", // Checking data
data: dados,
beforeSend: function(){
emailInfo.html("<font color='blue'>Checking..</font>");
if(dados == "email=") // >>> This field, how to check if the field is blank?
{
email.focus();
emailInfo.html("<font color='red'>Required.</font>");
return false;
}
},
success: function(data){
if(data == "invalid")
{
emailInfo.html("<font color='red'>Invalid.</font>");
}
else if(data != "0")
{
email.val(emailVal); // Store the entered value back into the email input
ck1.css("display", "none");
ck2.css("display", "inline");
}
else
{
ck1.css("display", "none");
ck2.css("display", "none");
ck3.css("display", "inline");
}
}
});
return false;
});
});
Another Note
I would also like to point out this: if(data == "invalid")
I have found that PHP can send back error messages within the data along with whatever you ask it to return. If you have any error in your PHP code, this will never hit because invalid will never be the only string of characters in the returned data value. To protect yourself, I would do either two things:
Return an HTTP error and do error handling within the error callback of the AJAX function: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Return a unique word and search for that word within the returned data string:
PHP
if(!validEmailCheck($email)){
echo('invalidRAWR');
}
JS
if(data.indexOf('invalidRAWR') != -1) // Built in PHP errors will never return 'invalidRAWR'
Related
Prevent a submission of a form via POST and submit once conditions are met.
Form is being submitted, I am not sure how to check if the function (which passes an HTML input into Python that checks a database if the user exists (Returns in JSON format true if it doesn't and false if it exists).
I have tried checking if the function is true, which for most cases work, I wonder if it is the $.get is an odd case?
document.getElementById("register").addEventListener("click", function(event) {
event.preventDefault();
let input = document.getElementsByName("username");
function(check) {
$.get('/check?username=' + input.value, function(data) {
document.querySelector('ul').innerHTML = data;
})
if (check()) {
this.submit();
}
else {
alert ("username is taken!");
return false;
}
#app.route("/check", methods=["GET"])
def check():
# Check the http parameter for username.
username = request.args.get("username")
check = db.execute("SELECT username FROM users WHERE username = :username", username=username)
if not check:
return jsonify(True)
else:
return jsonify(False)
I want the alert to flash and prevent form submission of the function runs and returns json(False) - which would indicate the username is taken
But right now it is submitting the form.
$.get() is asynchronous so you can't return a value from check()
Instead do the submit inside $.get() callback if response is true
document.getElementById("register").addEventListener("click", function(event) {
event.preventDefault();
let input = document.getElementsByName("username")[0];
$.getJSON('/check?username=' + input.value, function(data) {
if (data) {
document.querySelector('**formSelector**').submit()
} else {
// notify user
}
});
})
I have been trying to solve a simple but, for me, really hard problem.
I have a form and I need to add data from the form to a database, but with form validation. For validation I use the parsley plugin and for some input fields I use select2 plugin.
I try to add form in this way (Comments is in code):
//try to see is zemljiste or vrsta_rada = null to do not add data to database
var zemljiste = $("#parcele").select2("data");
var vrsta_rada = $("#vrsta_rada").select2("data");
//Now when I click on #dodaj I need to chech is zemljiste or vrsta_rada == null to do not start function for adding data but DONT work
$("#dodaj").click(function () {
if (zemljiste == null || vrsta_rada == null) {
alert('PLEASE fill the fields');
} else {
//HERE if zemljiste and vrsta_rada != null start validation and this also dont work
$('#myForm').parsley().subscribe('parsley:form:validate', function (formInstance) {
formInstance.submitEvent.preventDefault(); //stops normal form submit
if (formInstance.isValid() == true) { // check if form valid or not
zemljiste = $("#parcele").select2("data").naziv;
id_parcele = $("#parcele").select2("data").id;
vrsta_rada = $("#vrsta_rada").select2("data").text;
//code for ajax event here
//Here is ajax and when I fill all fields I add data to database but here success and error into ajax dont work???
$.ajax({
url: "insertAkt.php",
type: "POST",
async: true,
data: {
naziv: $("#naziv").val(),
parcele: zemljiste,
vrsta_rada: vrsta_rada,
opis: $("#opis").val(),
pocetak: $("#pocetak").val(),
zavrsetak: $("#zavrsetak").val(),
status: $("#status").val(),
id_parcele: id_parcele,
}, //your form data to post goes here as a json object
dataType: "json",
success: function (data) {
//SO if success I add data but this code below dont work also in error dont work
$('#myModal').modal('hide');
drawVisualization();
console.log('YESSSSSSS');
console.log(data);
},
error: function (data) {
console.log(data);
}
});
}
});
}
});
With this, I have a few problems...
1. When submit code, the page refreshes and I don't want to do that.
2.When I fill in all the fields, I add data to the database but also add all the previous attempts with incorrect information. Why?
3. Why can I not see what return my success and error into .ajax in console.log ???
Look the pictures:
I'm developing a website, and right now the registration form of it! But I have something like a problem! I want to create a Username input field, and when the user is typing, check if the username already exists in the database and give some output.
The error is this one: suppose that in the database there is only the username "Manuel". If I type "Manuel" in the input field no message is shown. Now if I type any other character it gives me the message 'The user already exists'. If i delete the last typed character the message goes away. If I type again and have something like "Manuela", the message shows up, if I type again and have "Manuelae" the message goes away
Thanks for your help!!
Here the code
Here the input field: (register.php)
<input type="text" id="username" name="username" maxlength="40" required="required">
<span id="username-info">What's your username?</span>
Here the javascript and jquery code (registration.js)
$(document).ready(function () {
var userExists = new Boolean();
var username = $("#username");
var usernameInfo = $("#username-info");
username.keyup(validateUsername);
}
Here the function validateUsername():
function validateUsername(){
checkUsername();
var minlenght = 5;
var usernameVal = username.val();
if(usernameVal.length < 1){
usernameInfo.addClass("input-error");
usernameInfo.text(messages.FIELD_REQUIRED);
} else if(usernameVal.length < minlenght){
usernameInfo.addClass("input-error");
usernameInfo.text(messages.USERNAME_MIN_WORDS+minlenght+' '+messages.USERNAME_CHARACTERS);
} else if(userExists){
//here i tell the user that the user already exists
usernameInfo.addClass("input-error");
usernameInfo.text('The user already exists');
} else {
usernameInfo.removeClass("input-error");
usernameInfo.text("");
}
}
And here the function checkUsername():
function checkUsername() {
var url = 'processregistration.inc.php';
$.ajax({
type: "POST",
dataType:"json",
url: url,
data: {username: username.val()},
success: function(data){
userExists = data.CHECK; //true if the user exists, false if not
}
});
}
Ajax means Asynchronous JavaScript and XML.
You are doing a check on a value which is actually not received.
You should do something like this :
function validateUsername() {
// remove input-error, text
if (...localcheck...) {
// add input-error, text
}
else if (...otherlocalcheck...) {
// add input-error, text
}
else {
$.ajax({
...
success : function(data) {
if (data.CHECK) {
// add input-error, text
}
}
});
}
}
I think you are on the right track, but I don't think your implementation is correct.
Note: I'm not a javascript hero
$("#filter").keyup( function(e) {
var filter = $("#filter").val(),
timer = $('#filter').data('timeout'),
if(timer) {
clearTimeout(timer);
$('#username').removeData('timeout');
}
$('#username').data('timeout', setTimeout(function() {
var url = 'processregistration.inc.php';
$.POST(url, {username: $('#username').val()}, function(data) {
// you get the picture ;)
updateComponentThatShowsIfUserNameIsTakenFunction(data.CHECK);
});
}, 100));
function updateComponentThatShowsIfUserNameIsTakenFunction(taken) {
$('#username').addClass('input_error');
}
What I did: Removed global variables, they are annoying and error prone. Instead, I'm using a callback named updateComponentThatShowsIfUserNameIsTakenFunction. You can also change it to directly call that function with the "data" of course. I have also added a timeout for you so that you won't call the server EVERY key-up. Every key-up cancels the previous timeout, causing the check to only trigger 100ms after the user is done typing (you don't want to spam your server).
I hope this works and helps you further!
I have a form that submits shopping cart data to a payment gateway (WorldPay) payment processing page. I need to perform a couple of extra logic the moment the custom decides to proceed to the payment but before the form submission itself. Basically, I simply want to generate a unique reference to the order at the very last moment.
Here is the jQuery code for the submit event:
$(function(){
$('#checkout-form').submit(function(e){
var $form = $(this);
var $cartIdField = $('#cartId');
console.log($cartIdField.val());
if($cartIdField.val() == ''){
e.preventDefault();
$.ajax({
url: baseUrl + '/shop/ajax/retrieve-shopping-cart-reference/',
data: {}, type: 'post', dataType: 'json',
success: function(json){
if(json.error == 0){
$('#cartId').val(json.data.cart_reference_number);
$form.submit();
}else{
alert(json.message);
}
}
});
}else{
console.log('Submitting form...'); //Does not submit!
}
});
});
The problem is that during the second submit triggered within the success: clause, the form isn't submitted still. I am assuming event.preventDefault() persists beyond the current condition.
How can I get around this?
For performe the any operation before form submit i used the following menthod hope it wil help
$('#checkout-form').live("submit",function(event){
//handle Ajax request use variable response
var err =false;
var $form = $(this);
//alert($form);
var values = {};
$.each($form.serializeArray(), function(i, field) {
values[field.name] = field.value;
});
//here you get all the value access by its name [eg values.src_lname]
var $cartIdField = $('#cartId');
console.log($cartIdField.val());
if($cartIdField.val() == ''){
$.ajax({
// your code and condition if condition satisfy the return true
// else return false
// it submit your form
/*if(condition true)
{
var err =true;
}
else
{
var err = false;
}*/
})
}
else
{
return true;
}
if(err)
{
return false
}
else
{
return true;
}
})
e.preventDefault() remove default form submit attribute which can not be reverted if applied once.
Use below code instead to prevent a form before submitting. This can be reverted.
$('#formId').attr('onsubmit', 'return false;');
And below code to restore submit attribute.
$('#formId').attr('onsubmit', 'return true;');
Only call e.preventDefault() when you really need to:
if(not_finished_yet) {
e.preventDefault();
}
I have email field in user's settings area. All emails are unique, of course, so I need to check is email not used already by someone else before submitting the form.
Here is the code:
var email = $("input#email-id").val();
$("#form-id").submit(function(){
$.ajax({
url: "/ajax/email?email=" + email,
success: function(data){
if(data != 'ok'){
alert("Email is used already");
return false;
}
}
});
});
So, if data is not 'ok' it must destroy submitting the form because if() returns false, but it doesn't and the form submits as usual and even alert doesn't appear!
I've checked ajax answer and it works fine (returns 'user_already' if email is used).
So what I did wrong?
Thanks!
Since ajax is async by nature you cannot do that. If you really want to do that you can submit the form inside the success handler. Try this.
function submitHandler(){
var email = $("input#email-id").val();
$.ajax({
url: "/ajax/email?email=" + email,
success: function(data){
if(data != 'ok'){
alert("Email is used already");
return false;
}
else{
//Once the data is ok you can unbind the submit handler and
//then submit the form so that the handler is not called this time
$("#form-id").unbind('submit').submit();
}
}
});
return false;//This will prevent the form to submit
}
$("#form-id").submit(submitHandler);
It's because the Ajax request to check the email is asynchronous. It will not complete before the submit event handler is finished. You'd have to do something like this:
$('#form-id').submit(function() {
if($(this).data('valid')) {
//you've already validated, allow the form to submit
return true;
} else {
//send an ajax request and wait for the response to really submit
$.ajax({
url: "/ajax/email?email=" + email,
success: function(data){
if(data == 'ok') {
//submit the form again, but set valid data so you don't do another Ajax request
$('#form-id').data('valid', true);
$('#form-id').submit();
} else {
alert("Email is used already");
}
}
});
return false;
}
//clear the validation flat
$(this).data('valid', false);
});
There's an accepted answer but I thought I'd share another way to do this.
You can use an extra parameter with the .trigger() function to first test the user's email, and if it comes back available then re-trigger the submit event but set a flag to not check the username:
$("#form-id").submit(function(event, forceSubmit){
//the normal submit will not have the extra parameter so we need to initialize it to not throw any errors,
//typeof is great for this since it always returns a string
if (typeof(forceSubmit) == 'undefined') { forceSubmit = false; }
//now check if this is a normal submit or flagged to allow submission
if (forceSubmit === false) {
var $form = $(this);
$.ajax({
url: "/ajax/email?email=" + email,
success: function(data){
if(data != 'ok'){
alert("Email is used already");
} else {
$form.trigger('submit', true);
}
}
});
//since this submit event is for checking the username's availability we return false to basically: event.preventDefault(); event.stopPropagation();
return false;
}
});
.trigger(): http://api.jquery.com/trigger
In your code you have two functions. One is the function passed to submit:
$("#form-id").submit(function() {
// code
});
The other is the function passed to the success handler of the AJAX call:
success: function(data) {
// code
}
You are returning false from the second function. This means that when the first function returns, it is not returning false. But the form submission is stopped, only if the first function returns false.
What you should do is to make the function passed to submit always return false and handle submission programmatically.
This code helps you to achieve this:
var submitHandler = function() {
$.ajax({
url: "/ajax/email?email=" + email,
success: function(data) {
if (data != 'ok') {
alert("Email is used already");
// no need to do anything here
} else {
// success, we should submit the form programmatically
// first we de-attach the handler, so that submitHandler won't be called again
// and then we submit
$("#form-id").unbind('submit').submit();
// now we reattach the handler, so that submit handler is executed if the user
// submits the form again
$("#form-id").submit(submitHandler);
}
}
});
// always return false, because if validation succeeds, we will submit the
// form using JavaScript
return false;
};
$("#form-id").submit(submitHandler);
I already +1 #ShankarSangoli because he got it right however, I don't feel its 100% complete as there is also an error state that can occur upon network issues or server fault.
$('#form-id').submit(function(ev) {
ev.preventDefault(); // cancels event in jQuery typical fashion
$.ajax({
url: "/ajax/email",
data : { email: $("input#email-id").val()},
success : function(d) {
if (d !== 'ok') {
alert('email in use');
}
},
error : function(a,b,c) {
// put your error handling here
alert('a connection error occured');
}
});
});
There are even better ways to handle this as I've written some great form plugins for jQuery that are HTML5 compliant and rival jQuery tools for ease of use.
You can see an example here -> http://www.zipstory.com/signup
Happy coding.
If JSON is involved, the returned data is in data.d - see http://encosia.com/a-breaking-change-between-versions-of-aspnet-ajax/ for an explanation.