2

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

6
  • Put the event.preventDefault(); at the top before your ajax function and then var fromData = $('#your_form_id").serialize(); Commented Aug 19, 2016 at 7:35
  • 1
    Your code will be triggered on form submit. If you would like the username to be checked on server before the submit, you should use a different way. For example binding this ajax call on a blur event on username input tag. Commented Aug 19, 2016 at 7:38
  • Yes, it is better to bind your username validation an a different event like blur. Just like what @MarioAlexandroSantini said. Commented Aug 19, 2016 at 7:43
  • okay i already have a blur for my username box, but i don't know how to through the value to server. i am gonna update my form for my blur function too Commented Aug 19, 2016 at 7:58
  • It's even better not to validate it client-side. Users can disable this javascript and still sign up with a duplicate username. Commented Aug 19, 2016 at 7:58

3 Answers 3

1

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:

  1. let the user fill your form
  2. let him hit the submit button
  3. preventDefault behaviour of your browser and build a FormData and put all your values in it
  4. prepare your ajax call
  5. send the FormData with your ajax call to your server
  6. Handle name-check and all other things on server-side
  7. answer the request
  8. 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.

Sign up to request clarification or add additional context in comments.

2 Comments

why doesn't it never gets to execute my script i brought the event.preventDefault(); after $(document).read(function(){ still no luck i even tried alert('hello'); and no result no poping window to say hello. do you know what could be the problem
Hm, just to understand you correctly: You put your $('form').submit() inside your $(document).ready(). Then you escaped the default inside your $('form').submit(function(event){}); and in this function you tried to alert('hello')?
1

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>

Comments

0

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"
      }
    }
  }
});

2 Comments

why doesn't it never gets to execute my script i brought the event.preventDefault(); after $(document).read(function(){ still no luck i even tried alert('hello'); and no result no poping window to say hello. do you know what could be the problem
It's $(document).ready(function(){ not $(document).read(function(){ Maybe is this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.