1

I have an web api to post data in the table when data entered in html page through jquery. The web api function is as:

   public HttpResponseMessage Post(User user)
        {

            if (ModelState.IsValid)
            {
                db.Users.Add(user);
                db.SaveChanges();

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, user);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = user.UserID }));
                return response;
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }

And the html page with jquery script is:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>

    <div>
    <h2>All users</h2>
    <ul id="users" />
  </div>

<div>
    <h2>Insert New User</h2>
    First Name : <input type="text" id="firstName"  /><br />
    Last Name : <input type="text" id="lastName"  /><br />
    City  : <input type="text" id="city"  /><br />
    Email : <input type="email" id="email"  /><br />
    Password : <input type="password" id="password"  /><br />
    Phone number:    <input type="number" id="phone"  /><br />
    <input type="button" id="btnsave" value="Save" onclick="Post();" />
    <p id="P1" />
  </div>

    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>

  <script>
      var uri = 'api/user';

      $(document).ready(function () {
          // Send an AJAX request
          getuserlist();
      });


      function getuserlist() {
          $.getJSON(uri)
             .done(function (data) {
                 $('#users').html('');
                 // On success, 'data' contains a list of users.
                 $.each(data, function (key, item) {
                     // Add a list item for the user.

                     $('<li>', { text: formatItem(item) }).appendTo($('#users'));
                 });
             });
      }
      function formatItem(item) {
          return 'email:' + item.email + ' and First Name:' + item.firstName + ' and Last Name: ' + item.lastName;
      }

      function Post() {
          jQuery.support.cors = true;
          var source = {
              'firstName': $('#firstName').val(),
              'lastName': $('#lastName').val(),
              'email': $('#email').val(),
              'phone': $('#phone').val(),
              'city': $('#city').val(),
              'password': $('#password').val()
          }
          $.ajax({
              type: "POST",
              dataType: "json",
              url: "/api/user",
              data: source,
              success: function (data) {
                  var strResult = "<table><th>Returned Message</th>";
                  // $.each(data, function (index, data) {
                  strResult += "<tr><td> " + source.email + " </td></tr>"
                  strResult += "</table>";
                  $("#divResult").html(strResult);
              },
              error: function (x, y, z) {

                  var strResult = "<table><th>Error Message</th>";
                  // $.each(data, function (index, data) {
                  strResult += "<tr><td> " + x.responseText + " </td></tr>"
                  strResult += "</table>";
                  $("#divResult").html(strResult);
                  // alert(x + '\n' + y + '\n' + z);
              }
              //success: function (data) {
              //    //alert(data);
              //    getuserlist();
              //    // alert(jQuery.parseJSON(data));

              //},
              //error: function (error) {
              //    jsonValue = jQuery.parseJSON(error.responseText);
              //    //jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
              //}
          });
      });
  </script>
</body>
</html>

when I click on the button to add anew user,the post() function is not working. the page remains the same,no action,no error.

please help! Thanks!

6
  • Where's your post function ? Commented Feb 26, 2015 at 12:46
  • go down in the script tag Commented Feb 26, 2015 at 12:53
  • oops, sorry I didn't noticed that, Anyways can you please verify error in firebug/fiddler ? Commented Feb 26, 2015 at 12:55
  • And why did you enabled this CORS jQuery.support.cors = true;? are you going for a cross domain request? Commented Feb 26, 2015 at 12:56
  • Nothing is happening when i click the save button...yes I will need it later. Commented Feb 26, 2015 at 13:04

1 Answer 1

1

Firstly the url that you are posting to should be "/api/user/Post".

Output

enter image description here

There are several other JavaScript errors in the posted code that I had to fix. As other's have mentioned in the comments these errors were shown in the console. Knowing how to debug using the developer tools is invaluable and worth investing time to learn them.

Here is the updated code fixed:

  <div>
    <h2>All users</h2>
    <ul id="users" />
  </div>

<div>
    <h2>Insert New User</h2>
    First Name : <input type="text" id="firstName"  /><br />
    Last Name : <input type="text" id="lastName"  /><br />
    City  : <input type="text" id="city"  /><br />
    Email : <input type="email" id="email"  /><br />
    Password : <input type="password" id="password"  /><br />
    Phone number:    <input type="number" id="phone"  /><br />
    <input type="button" id="btnsave" value="Save" onclick="Post();" />
    <p id="P1" />
  </div>

    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>

  <script>
     var uri = 'api/user';

      $(document).ready(function () {
          // Send an AJAX request
          getuserlist();
      });


      function getuserlist() {
          $.getJSON(uri)
             .done(function (data) {
                 $('#users').html('');
                 // On success, 'data' contains a list of users.
                 $.each(data, function (key, item) {
                     // Add a list item for the user.

                     $('<li>', { text: formatItem(item) }).appendTo($('#users'));
                 });
             });
      }
      function formatItem(item) {
          return 'email:' + item.email + ' and First Name:' + item.firstName + ' and Last Name: ' + item.lastName;
      }

      function Post() {
          jQuery.support.cors = true;
          var source = {
              'firstName': $('#firstName').val(),
              'lastName': $('#lastName').val(),
              'email': $('#email').val(),
              'phone': $('#phone').val(),
              'city': $('#city').val(),
              'password': $('#password').val()
          }
          $.ajax({
              type: "POST",
              dataType: "json",
              url: "/api/user/Post",
              data: source,
              success: function (data) {
                  var strResult = "<table><th>Returned Message</th>";
                  $.each(data, function (index, data) {
                      strResult += "<tr><td> " + source.email + " </td></tr>"
                      strResult += "</table>";
                      $("#divResult").html(strResult);
                  });
              },
              error: function (x, y, z) {

                  var strResult = "<table><th>Error Message</th>";
                  $.each(x, function (index, data) {
                      strResult += "<tr><td> " + x.responseText + " </td></tr>"
                      strResult += "</table>";
                      $("#divResult").html(strResult);
                      // alert(x + '\n' + y + '\n' + z);
                  });
              }
              //success: function (data) {
              //    //alert(data);
              //    getuserlist();
              //    // alert(jQuery.parseJSON(data));

              //},
              //error: function (error) {
              //    jsonValue = jQuery.parseJSON(error.responseText);
              //    //jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
              //}
          });
      };
  </script>

I have also made the assumption that your User object is as follows:

public class User
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string email { get; set; }
    public string phone { get; set; }
    public string city { get; set; }
    public string password { get; set; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Mine worked too.There were some validation exception that I have unhandled,that are meant to be handled.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.