Change Password using jQuery AJAX and ASP.NET web service

Few days ago, we received a request via comment on one of the post as how to change password on using AJAX so today we will see how we can accomplish this using jQuery AJAX to make a call to ASP.NET web service to change user's old password leveraging ASP.NET's membership API.

ScreenShot:

Web service:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services;

using System.Web.Security;

 

[WebService(Namespace = "http://www.Devtechie.com/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

[System.Web.Script.Services.ScriptService]

public class MembershipWebService : System.Web.Services.WebService {

 

[WebMethod]

public string ChangePasswordFForUser(string Username, string oldPassword,string newPassword)

{

// creating object for Membership user with provided username

MembershipUser user = Membership.GetUser(Username);

// flag variable to check if password change was successful or not

bool passwordChanged = false;

// calling change password method for MembershipUser providing old password and new password

passwordChanged = user.ChangePassword(oldPassword,newPassword);

if (passwordChanged)

{

// if return true: password is changed

return "Your password is changed!";

}

else

{

// if returned false: password change was unsuccessful

return "Password change was not successful!";

}

 

 

     }

 

}

 

Now add div and html elements to accept user input:

<div id="PasswordChange">

<div id="header">

Change Password

</div>

<div id="content">

Username: <br /><input id="_username" type="text" /><br />

Old Password: <br /><input id="_password" type="password" /><br />

New Password: <br /><input id="_newPassword" type="password" /><br />

<input id="SubmitButton" type="button" value="Submit" /><br />

</div>

<div id="footer">

<span id="Message" />

</div>

 

</div>

 

Time to write some JavaScript:

 

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

<script type="text/javascript">

$(document).ready(function () {

 

$('#SubmitButton').click(function (e) {

// prevent default action for click

e.preventDefault();

// tmp variables to hold data from input elements

var username = $("#_username").val();

var oldPassword = $("#_password").val();

var newPassword = $("#_newPassword").val();

// ajax call to web service

$.ajax({

type: "POST",

url: "MembershipWebService.asmx/ChangePasswordFForUser",

data: "{'Username':'" + username + "', 'oldPassword': '" + oldPassword + "','newPassword':'" + newPassword + "'}",

contentType: "application/json",

async: false,

success: function (data) {

// on success update message span element

$("#Message").html("<b>"+data.d+"</b>");

}

});

 

 

});

 

 

});

</script>

Tags: , , , ,

AJAX | ASP.NET | jQuery