最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to receive data back from server using ajax? - Stack Overflow

programmeradmin2浏览0评论

Basically I have a form with a username textbox and a submit button in it. Now what I want is that when the user input text in textbox it should get the textbox value and send the username to server so the server could check whether the username is taken by any other user or not. I could do sending the text value to server but I don't know how to receive back some data and turn the textbox border into red and pop an error if the username has been taken.

Here is my code for getting text value and sending it to server:

<!DOCTYPE html>

<html>
 <head>

<script src="../JquerySock.js"></script>
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1">    

<script>
  $(document).ready(function() {
      $('#Registeration_Username_box').on('input', function() {
        console.log('excuted input');
        postUsernameToServer();
    });
  });
  function postUsernameToServer() {
      var formData = {
                'username': $('input[name=UserName]').val(),
              };
              // 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
                })
    }
</script>
 </head>
<body>

<div id="Registeration_Div" class="Registeration_Div">
    <div class="createnewaccount" id="createnewaccount">Create new account</div>
    <form class="Registration_Form" id="Registration_Form" action="../postr" method="POST">

        <span class="Usernameerror_spn" id="Usernameerror_spn">Username has been taken</span>
        <div id="Registeration_Username_DIV" class="Registeration_Username_DIV">
            <input type="text" id="Registeration_Username_box" class="Registeration_Username_box"
                placeholder="Username" name="UserName" maxlength="30" />
        </div>

    </form>
</div>

</body>
</html>

As you can see I have a span box before my username textbox which by default is hidden, but I want it to be shown if the user has been taken.

Basically I have a form with a username textbox and a submit button in it. Now what I want is that when the user input text in textbox it should get the textbox value and send the username to server so the server could check whether the username is taken by any other user or not. I could do sending the text value to server but I don't know how to receive back some data and turn the textbox border into red and pop an error if the username has been taken.

Here is my code for getting text value and sending it to server:

<!DOCTYPE html>

<html>
 <head>

<script src="../JquerySock.js"></script>
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1">    

<script>
  $(document).ready(function() {
      $('#Registeration_Username_box').on('input', function() {
        console.log('excuted input');
        postUsernameToServer();
    });
  });
  function postUsernameToServer() {
      var formData = {
                'username': $('input[name=UserName]').val(),
              };
              // 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
                })
    }
</script>
 </head>
<body>

<div id="Registeration_Div" class="Registeration_Div">
    <div class="createnewaccount" id="createnewaccount">Create new account</div>
    <form class="Registration_Form" id="Registration_Form" action="../postr" method="POST">

        <span class="Usernameerror_spn" id="Usernameerror_spn">Username has been taken</span>
        <div id="Registeration_Username_DIV" class="Registeration_Username_DIV">
            <input type="text" id="Registeration_Username_box" class="Registeration_Username_box"
                placeholder="Username" name="UserName" maxlength="30" />
        </div>

    </form>
</div>

</body>
</html>

As you can see I have a span box before my username textbox which by default is hidden, but I want it to be shown if the user has been taken.

Share Improve this question edited Aug 22, 2016 at 5:33 Mukesh Ram 6,3384 gold badges20 silver badges37 bronze badges asked Aug 21, 2016 at 20:40 kamrankamran 311 silver badge3 bronze badges 3
  • Do you have server-side scripts? (PHP/ASP??) – Scott Commented Aug 21, 2016 at 20:43
  • yes i do it's java ee – kamran Commented Aug 21, 2016 at 20:46
  • Wele to Stack Overflow! You can help us help you by formatting your so we don't have scroll it. This can easily be done by removing non relevant code. Please read Minimal, Complete, and Verifiable example. When your code shows your precise problem with nothing extra, you are showing respect to those who volunteer to help you. – zhon Commented Aug 21, 2016 at 21:08
Add a ment  | 

1 Answer 1

Reset to default 3

Well, first off:

You are requiring the datatype to be JSON. This means on the server side (Is it PHP?) you have to translate it to a JSON object first. In PHP this would be

$data = array("username" => "bla", "taken" => "taken");
echo json_encode($data);

For Java EE you could use this: (source)

int spacesToIndentEachLevel = 2;
new JSONObject(jsonString).toString(spacesToIndentEachLevel);

Using org.json.JSONObject (built in to JavaEE and Android) Now, you have to make sure it returns ONLY the required JSON and nothing else, or you'll get errors.

Then, to get the feedback within your ajax call:

function postUsernameToServer() {
  var formData = {'username': $('input[name=UserName]').val()};
              // 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
                }).done(function(data){ //any name you put in as an argument here will be the json response string.
                   var username = data.username;
                   var taken = data.taken;

                   //check if username is taken
                   if(taken == "taken"){
                     //make input border red
                     $('.yourInput').css({"border-color": "red"});
                   }
                   else{
                     //make input border green
                     $('.yourInput').css({"border-color": "green"});
                   }
              }).error(function(errorData){
                //Something went wrong with the ajax call. It'll be dealt with here
              });;
    }
发布评论

评论列表(0)

  1. 暂无评论