javascript - Sending AJAX request to server with jQuery - Stack Overflow

I want to send a very basic post request using AJAX to the same url. It should take the username and ch

I want to send a very basic post request using AJAX to the same url. It should take the username and check it against the DB to see if a user with that name exists already, returning a string to that effect. There is something wrong with the javascript function that is sending the request:

function usernameCheck(){
$.post("", 
  {username: $("#username").value}, 
  function(response){
    if(response=="true"){
       $('#passAlert').innerHTML("Sorry, that username is already taken")
    }
});

return !($('#passAlert').value == "Sorry, that username is already taken")
}

If the person is just loading the signup view, it returns the page, otherwise, it is being called to check for a user existing:

def signup(request):
    if request.method == 'GET':
        return render_to_response('signup.html', context_instance=RequestContext(request))
    else: 
    #query db for user with username provided in POST, return if it exists
        user = User.objects.get(username=request.POST["username"]) 
        if user is not None:
            return HttpResponse("true")
        else:
            return HttpResponse("false")

Is there anything you can see as to why the JS is being ignored? Firebug found nothing.

I want to send a very basic post request using AJAX to the same url. It should take the username and check it against the DB to see if a user with that name exists already, returning a string to that effect. There is something wrong with the javascript function that is sending the request:

function usernameCheck(){
$.post("http://omnicloud.me/signup", 
  {username: $("#username").value}, 
  function(response){
    if(response=="true"){
       $('#passAlert').innerHTML("Sorry, that username is already taken")
    }
});

return !($('#passAlert').value == "Sorry, that username is already taken")
}

If the person is just loading the signup view, it returns the page, otherwise, it is being called to check for a user existing:

def signup(request):
    if request.method == 'GET':
        return render_to_response('signup.html', context_instance=RequestContext(request))
    else: 
    #query db for user with username provided in POST, return if it exists
        user = User.objects.get(username=request.POST["username"]) 
        if user is not None:
            return HttpResponse("true")
        else:
            return HttpResponse("false")

Is there anything you can see as to why the JS is being ignored? Firebug found nothing.

Share Improve this question edited Nov 22, 2011 at 16:42 Chris asked Nov 22, 2011 at 8:16 ChrisChris 12.2k19 gold badges94 silver badges150 bronze badges 3
  • possible duplicate of GET return undefined value out function – Quentin Commented Nov 22, 2011 at 8:18
  • Moreover what is that: $("username").value? Should be something like $('#username').val() or $('.username').val() etc. – dfsq Commented Nov 22, 2011 at 8:21
  • Chris, basically there are two errors: you are closing the $.post statement a bit too soon and the response has to be pared to 'true'. Check my answer below. That's all! – zequinha-bsb Commented Nov 22, 2011 at 8:49
Add a ment  | 

3 Answers 3

Reset to default 5

Ajax means "Asynchronous JavaScript and XML" so it does not wait for $.post to finish but just goes on within your code.

To solve this issue you have to use a callback function:

http://api.jquery./jQuery.post/

jQuery.post( url [, data] [, success(data, textStatus, jqXHR)] [, dataType] )

url A string containing the URL to which the request is sent.

data A map or string that is sent to the server with the request.

success(data, textStatus, jqXHR) A callback function that is executed if the request succeeds.

dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).

Sample:

function usernameCheck(){
    $.post("http://omnicloud.me/signup", 
      {username: $("#username").val()}, 
      function(response){
        if(response=="true"){
           $('#passAlert').html("Sorry, that username is already taken")
        }
    });
}

You might also pass an anonymous callback:

function usernameCheck(successCallback){
    $.post("http://omnicloud.me/signup", 
      {username: $("#username").val()}, 
      function(response){
       if(response=="true") successCallback();
    });
}

// Somewhere else in your code:

usernameCheck(function(){
  $('#passAlert').html("Sorry, that username is already taken")
});

First, you have some problems in your view. You need to check whether the POST is from AJAX or a standard POST; otherwise, you won't be able to actually add the user later. (Really the AJAX part should be it's own view, since it really isn't part of the signup process per se, but rather a validation check. Later, you might actually want create a user via AJAX, and you wouldn't be able to because the view wouldn't be able to distinguish between the two different AJAX requests).

Next, get doesn't return None when the object doesn't exist; it raises an ObjectDoesNotExist exception. So, your if statement there won't work; you must use a try block instead.

I've updated your view below, accordingly:

def signup(request):
    if request.method == 'GET':
        return render_to_response('signup.html', context_instance=RequestContext(request))
    elif request.is_ajax(): 
        # query db for user with username provided in POST, return if it exists
        try:
            user = User.objects.get(username=request.POST["username"]) 
        except User.DoesNotExist:
            return HttpResponse("false")
        else:
            return HttpResponse("true")
    else:
        # Normal post, add new user

EDIT: make sure the response sends back a STRING true or a STRING false

EDIT: the response IS SENDING BACK A STRING true or A STRING false

function usernameCheck(){
    var exists;
    $.post("http://omnicloud.me/signup", { username: $("#username").val() }, 
      function(response){
         exists = (response == 'true');
         if(exists){
             $('#passAlert').innHTML = "Sorry, that username is already taken";
             return false;
         } else {
             return true;
         }
    });

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745163879a4614529.html

相关推荐

  • javascript - Sending AJAX request to server with jQuery - Stack Overflow

    I want to send a very basic post request using AJAX to the same url. It should take the username and ch

    2小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信