0

I am trying to write an ajax user search.I have this text field:

<input type="text" id="userSearch" class="search-query" placeholder="Search">

And this jQuery for it in a .js file:

$("#userSearch").keyup(function () {
        if ($(this).val().length >= 3) {
            $.getJSON('/User/SearchUsers', { displayName: $(this).val() }, function (data) {
                if (data == null) {
                    alert("nothing");
                }
                else{
                    alert("OK");
                }
            });
        }
    });

Here is the UserController and Application and Repository Classes:

[HttpGet]
public ActionResult SearchUsers(string displayName)
{
    return Json(userApp.GetUserBySearch(displayName), JsonRequestBehavior.AllowGet);
}

public List<User> GetUserBySearch(string displayName)
{
    return userRepo.GetUserBySearch(displayName);
}

public List<User> GetUserBySearch(string displayName)
{
    return context.Users.Include("Group").Where(u => u.DisplayName.Contains(displayName)).ToList();
}

But this is not working at all.It doesnt alert at all.So what does it mean?It means that data is null and is not null?! I have tried this too:

var i = 0;
for (i = 0; i <= data.length; i++) {
    alert(data[i].UserId);
}

But It is not working too. I have do something like this for thousand of times but now IT IS NOT WORKING... What shoud I do...?

Hamid Reza
  • 2,913
  • 9
  • 49
  • 76
  • 1
    You can see exactly what you're sending to and receiving from the server using the "Network" tab in your browser's developer tools. (If your browser doesn't have developer tools, switch to a modern browser. IE8+, Chrome, Opera, Safari, Firefox [with the Firebug add-on] all have developer tools.) – T.J. Crowder May 26 '13 at 08:36

2 Answers2

1

I would suggest using Fiddler to test what is happening between the browser and your server.

I would also advise using .ajax instead like this, it allows you to be more explicit and capture errors happening on the server:

var URL = 'yourURLGoesHere';
$.ajax({
    url: URL, type: "post", data: yourdata, dataType: 'json', contentType: "application/json",
    success: function (data, status, jqXHR) {
        console.log('status:', status);
        console.log('jqXHR:', jqXHR);
        console.log('data:', data);
        if (data) {
            //do your OK Stuff
        } else {
            //do your NOT OK Stuff
        }
    },
    error: function (data, status, jqXHR) {
        console.log('responseText:', data.responseText);
        //do your error stuff

    }
});

Update

It looks like the main problem is how you're sending data to the server.

If you're not seeing the details of the 500 error it suggests you're using WebAPI and haven't set it up to show you the error details. This link may help if this is the case.

Here is an updated version of your code using .ajax() and putting displayName in the querystring - the main advantage is that you can capture the error event and handle that accordingly.

$("#userSearch").keyup(function () {
    if ($(this).val().length >= 3) {
        var URL = '/User/SearchUsers/?displayName=' + encodeURIComponent($(this).val());
        $.ajax({
            url: URL, type: "post", dataType: 'json', contentType: "application/json",
            success: function (data, status, jqXHR) {
                console.log('status:', status);
                console.log('jqXHR:', jqXHR);
                console.log('data:', data);
                if (data) {
                    //do your OK Stuff
                } else {
                    //do your NOT OK Stuff
                }
            },
            error: function (data, status, jqXHR) {
                console.log('responseText:', data.responseText);
                //do your error stuff

            }
        });
    }
});
79IT
  • 425
  • 4
  • 9
  • With using your ajax method I recieved a 404 Not Found Error in console and with my method its giving a 500 Internal Server Error.What do you think? – Hamid Reza May 26 '13 at 09:13
  • Are you using WebAPI or MVC? Run your code in debug mode (F5) and set a break point on the controller (F9) - watch what happens. Have you installed Fiddler - because it proxies data through the browser it can often be easier to see exactly what is going on. – 79IT May 26 '13 at 09:16
  • Thank you for spending your time for me.;) – Hamid Reza May 26 '13 at 10:04
0

Put your code inside ready event

$(document).ready(function(){
    $("#userSearch").keyup(function () {
        var value = $(this).val();    
        if (value.length >= 3) {
            $.getJSON('/User/SearchUsers', { displayName: value }, function (data) {
                if (data == null) {
                    alert("nothing");
                }
                else{
                    alert("OK");
                }
            });
        }
    });
});
The Alpha
  • 143,660
  • 29
  • 287
  • 307