skip to Main Content

This is the error I am getting in my console;

GET http://localhost:1089/api/Employee/EmailAlreadyExist?%[email protected]%22 404 (Not Found)

This my ajax code where I am sending the user email while creating a new user, and I want this method to let me know if the email already exist in database or not;

function CheckAvailability() {
    var email = $("#officialemail").val();
    $.ajax({
        type: "GET",
        url: 'http://localhost:1089/api/Employee/EmailAlreadyExist',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(email),
        success: function (response) {
            var message = $("#message");
            if (response) {
                //Email available.
                message.css("color", "green");
                message.html("Email is available");
            }
            else {
                //Email not available.
                message.css("color", "red");
                message.html("Email is NOT available");
            }
        }
    });
}

function ClearMessage() {
    $("#message").html("");
};

and I am passing this entire function in another fucntion in which I am passing the email parameter in attempt of creating a new user along with all of the other parameters with their values;

$('.empOfficialDetails').click(function (ev) {
    ev.preventDefault();

    CheckAvailability()

    var data = new Object();
    data.UserName = $('#username').val();
    data.UPassword = $('#userpass').val();
    data.OfficialEmailAddress = $('#officialemail').val();
    data.Departments = $('#departments :selected').text();
    data.Designation = $('#designation :selected').text();
    data.RoleID = $('#role').val();
    data.Role = $('#role :selected').text();
    data.ReportToID = $('#reportToID').val();
    data.ReportTo = $('#reportTo :selected').text();
    data.JoiningDate = $('#joindate').val();
    data.IsAdmin = $('#isAdmin :selected').val() ? 1 : 0;
    data.IsActive = $('#isActive :selected').val() ? 1 : 0;
    data.IsPermanent = $('#isPermanent :selected').val() ? 1 : 0;
    data.DateofPermanancy = $('#permanantdate').val();
    data.HiredbyReference = $('#hiredbyRef :selected').val() ? 1 : 0;
    data.HiredbyReferenceName = $('#refePersonName').val();
    data.BasicSalary = $('#basicSalary').val();
    data.CurrentPicURL = $('.picture').val();

    if (data.UserName && data.UPassword && data.OfficialEmailAddress && data.Departments && data.Designation && data.Role && data.IsAdmin && data.IsPermanent) {
        $.ajax({
            url: 'http://localhost:1089/api/Employee/EmpOfficialDetails',
            type: "POST",
            dataType: 'json',
            contentType: "application/json",
            data: JSON.stringify(data),
            beforeSend: function () {
                $("#dvRoomsLoader").show();
            },
            complete: function () {
                $("#dvRoomsLoader").hide();
            },
            success: function (data) {
                var ID = parseInt(data);
                if (ID > 0) {
                    //var id = data;
                    $(".HiddenID").val(data);
                    //var id = $(".HiddenID").val();
                    $('#official').css('display', 'block');
                    $('#official').html("Employees Official details added successfully...!");
                    $('#official').fadeOut(25000);
                    $("#dvRoomsLoader").show();

                    $('.empOfficialDetails').html("Update &nbsp; <i class='fa fa-angle-right rotate-icon'></i>");
                }
                else {
                    $('#official').find("alert alert-success").addClass("alert alert-danger").remove("alert alert-success");
                }
            },
            error: function (ex) {
                alert("There was an error while submitting employee data");
                alert('Error' + ex.responseXML);
                alert('Error' + ex.responseText);
                alert('Error' + ex.responseJSON);
                alert('Error' + ex.readyState);
                alert('Error' + ex.statusText);
            }
        });
        
    }
    return false;

});

and in my controller I am using an inline query to check for similar email in my database;

[Route("api/Employee/EmailALreadyExist")]
    [HttpGet]
    public bool EmailAlreadyExist(string email)
    {
        string retval;
        var con = DB.getDatabaseConnection();
        Employee emp = new Employee();
        string query = "IF EXISTS (SELECT 1 FROM Employee WHERE OfficialEmailAddress = @OfficialEmailAddress)";
        SqlCommand com = new SqlCommand(query, con);
        com.Parameters.AddWithValue("@OfficialEmailAddress", email);

        email = emp.OfficialEmailAddress;
        SqlDataReader rdr = com.ExecuteReader();
        if (rdr.HasRows)
        {
            retval = "true";
        }
        else
        {
            retval = "false";
        }
        return Convert.ToBoolean(retval);
    }

all of the help I get is highly appreciated and sugesttions for making this code better are all warmly welcomed

thank you

3

Answers


  1. From your url

    http://localhost:1089/api/Employee/EmailAlreadyExist?%[email protected]%22

    it looks like you aren’t passing email parameter correctly.

    You can pass it like

    http://localhost:1089/api/Employee/[email protected]

    or change your route a bit to support your url

    [Route("api/Employee/EmailAlreadyExist/{email}")]

    Login or Signup to reply.
  2. I can see that there is a typo in the route. The L in EmailALreadyExist is capitalized. But you are calling it with a lowercase letter.

    Also, I am seeing a missing semicolon in the Ajax code, check that out too.

    Login or Signup to reply.
    1. Your code uses a GET method that can’t have a body. So it had to append an URL parameter to it. In ASP.NET it should be named. But your method has not named parameters. So it is not found. Add the parameter name to your payload (name "email"). to your JSON – replace in your JS function CheckAvailability data: JSON.stringify(email), with data: JSON.stringify({email: email}),. Then jQuery should call for api/Employee/EmailALreadyExist?email=.... that will match public bool EmailAlreadyExist(string email).
    2. It is better to use a POST method to hide the email in the request body. Then your original code could have a C# smaller update:
      public bool EmailAlreadyExist([FromBody]string email). It will map the single parameter from the body to the C# email variable.
    3. There is a point to separate your logic from the controller. "Thin controller" could validate parameters, a service will contain your "business logic".
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search