RScott RScott - 1 month ago 9
jQuery Question

using SPservices to check current user exists in list

I have created a script with jquery/spservices that checks if the current logged in user ID appears in a column called userid in a custom list. If successful it returns an alert to say current user found.

If the user id is not found however, I'd like another alert to say something like "you haven't registered yet". It does work when finding where the user id, but it seems to not be able to tell that it doesn't exist.

Any assistance would be much appreciated :)

here is the code:

var userName = $().SPServices.SPGetCurrentUser({
fieldName: "UserName"});var query = '<Query>' +
'<Where>' +
'<Eq>' +
'<FieldRef Name="userid" />' +
'<Value Type="User">' + userName + '</Value>' +
'</Eq>' +
'</Where>' +
'</Query>';$(document).ready(function() {
$().SPServices({
operation: "GetListItems",
async: false,
listName: "test",
CAMLViewFields: "<ViewFields><FieldRef Name='userid' /></ViewFields>",
completefunc: function(xData, Status) {
$(xData.responseXML).SPFilterNode("z:row").each(function() {
if (userName == $(this).attr("ows_userid")) {
alert("current user found");
} else {
alert("You need to register before accessing..");
}
});
}
});});</script>

Answer

Can you try with below complete function:

completefunc: function(xData, Status) {

    var matchFound = false; //define flag

    //loop through all rows
    $(xData.responseXML).SPFilterNode("z:row").each(function() {
        if (userName == $(this).attr("ows_userid")) {
            matchFound = true; //set the flag to true indicating matched record
        } 
    });

    if(matchFound)
        alert("current user found");
    else
        alert("You need to register before accessing..");
}