jQuery Ajax success response returns HTML and not my intended value - asp.net

I'm calling the Page Method and it's returning all of the HTML in this page and not the value of 1 or 0.
I don't know why this is. Can someone point me in the right direction ?
JavaScript:
$.ajax({
async: false,
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{}',
url: "main.aspx/IsInfoComplete",
success: function(data, textStatus, jqXHR) {
console.log(textStatus);
console.log(data.d);
// act on return value:
if(data==0) {
// todo -
} else if (data==1) {
// todo -
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
});
Server:
[System.Web.Services.WebMethod()]
public int IsInfoComplete()
{
int returnValue = 0;
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetIsUserInfoComplete";
cmd.Parameters.AddWithValue("#UserName", userName);
conn.Open();
try
{
returnValue = (int)cmd.ExecuteScalar();
}
catch (Exception) { /* todo - */ }
}
return returnValue;
}

One thing you might try is to write your success function like this,
success: function (result) {
if (result!="False") {
//it worked
}
else {
//it failed
}
},
And change your server side method to return a bool. This would probably get you the desired results. I had to do this in something I wrote and it worked just fine. Little silly that you have to check for "False" but it worked.
Note: Case matters when looking for the word "False"

Look's like this is messing it up.. data here is an object and you are trying to compare the data with a 0 or a 1
success: function(data, textStatus, jqXHR) {
console.log(data); // Check the format of data in object
if(data != null){
console.log(data.d); // Generally your actual dat is in here
// act on return value:
if(data.d ==0) {
// todo -
} else if (data.d ==1) {
// todo -
}
}
},
If thats the case is your WebService returning a json object in the first place..
You need to decorate your webservice with this..
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[System.Web.Services.WebMethod()]
public int IsInfoComplete()
{
And set the dataType :'json' in your ajax request

Related

Autocomplete Web Service in ASP.Net web forms

I have a web service for multiple item selection, its working fine but i am getting Undefined data. anyone can tell me solution for it. I am attaching my error screenshot too with this post, please see them below.
Web Service JSON Code
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$("[id*=ctl00_ContentMain_TextBoxSkills]").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<%=ResolveUrl("WebServiceSkills.asmx/GetAutoCompleteData")%>',
data: "{'skill':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("No Result Found");
}
});
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("#ctl00_ContentMain_TextBoxSkills").bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
}
</script>
Web Service:
[WebMethod]
public List<UserRegistration> GetAutoCompleteData(string skill)
{
List<UserRegistration> list = new List<UserRegistration>();
UserRegistrationHelper userRegistrationHelper = new UserRegistrationHelper();
using (DataTable dataTable = userRegistrationHelper.GetSkillsList(skill))
{
if (CommonFunctions.ValidateDataTable(dataTable))
{
foreach (DataRow dr in dataTable.Rows)
{
var SkillsList = new UserRegistration
{
SkillId = Convert.ToInt32(dr["SkillId"].ToString()),
Skills=dr["SkillName"].ToString()
};
list.Add(SkillsList);
}
}
}
return list;
}
Screenshot here:
I got answer for it:
1: Change SQL Query:
select concat('[', STUFF
(
(
SELECT top 15 '","'+ CAST(skillname AS VARCHAR(MAX))
from DNH_Master_Skills where SkillName LIKE '%' + #SkillName + '%'
FOR XMl PATH('')
),1,2,''
),'"]')
2: Change JSON Code:
From: response(data.d); TO: response(Array.parse(data.d));
Now its working feeling happy.

Pass large data using jquery.ajax

I am using asp.net and jQuery 1.6
In my function I am required to pass html tags as a data parameter to my server side method written in C#. In my Database the column has Blob datatype.
I am able to submit data successfully upto 528b but If I submit large data... I'm not able to send at server side.
When I pass small data it works and a row inserted. But If I pass data around 17Kb then this doesn't go to the sever side, but prompt me an undefined error in jquery.
Following is Ajax Code:
$.ajax({
type: "POST",
url: "Post.aspx/savePost",
data: "{Title:'" + Title + "',Html:'" + Html + "'}",
contentType: "application/json",
dataType: "json",
success: function (data) {
if (data == undefined) {
alert("Error : 219");
}
else {
alert(data.d);
}
},
error: function (data) {
if (data == undefined) {
alert("Error : 465");
}
else {
alert("Error : 468 " + data.d);
}
}
});
Following is C# code
[System.Web.Services.WebMethod]
public static string savePost(string Title,string Html)
{
string retMsg = "Not Saved";
Post bp = new Post();
int count = 0;
count = bp.mySavePost(Title,Html);
if (count > 0)
{
retMsg = "Post Save Successfully.";
}
return retMsg;
}
protected int mySavePost(string Title, string Html)
{
int count=0;
try
{
string rawQuery = "INSERT INTO temp_posts (Title,HTML)"
+ " VALUES(?Title,?HTML)";
cmd = new MySqlCommand();
cmd.CommandText = rawQuery;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("?Title", MySqlDbType.VarChar).Value = Title;
cmd.Parameters.Add("?Html", MySqlDbType.Blob).Value = Html;
count = c.insertData(cmd);
}
catch(Exception ex){}
}
Please guide me with you valuable knowledge.
Thanks.
Many Thanks to everyone who put his best effort for this thread.
Finally with the help of one my senior I found where I was lacking in my code.
As I am passing html tags as a data parameter to my server side method written in C# from jQuery.ajax(); I need to encode the data.
As I used the escape() function in javascript to encode it worked. Data is submitted to database.
var encodedHTML = escape(Html); //here encoding Html.
$.ajax({
type: "POST",
url: "Post.aspx/savePost",
data: "{Title:'" + Title + "',Html:'" + encodedHTML + "'}",
contentType: "application/json",
dataType: "json",
success: function (data) {
if (data == undefined) {
alert("Error : 219");
}
else {
alert(data.d);
}
},
error: function (data) {
if (data == undefined) {
alert("Error : 465");
}
else {
alert("Error : 468 " + data.d);
}
}
});
Thanks everyone :)

Redirect from Webmethod in Asp.Net

Am new to Asp.Net Programming, Have just started a web project.
Am calling a WebMethod from Aspx page using JSON like below:
<script type="text/javascript">
function getLogin() {
var userName = document.getElementById('TextBox1').value;
$.ajax({
type: "POST",
url: "Services/LogService.asmx/authenticateLogin",
data: "{'userName':'" +userName.toString()+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d)
},
error: function (xhr, status, error) {
// alert(textStatus);
DisplayError(xhr);
}
});
}
function DisplayError(xhr) {
var msg = JSON.parse(xhr.responseText);
alert(msg.Message); }
</script>
And WebMethod :
[WebMethod]
public string authenticateLogin(string userName)
{
LoginBO loginBO = new LoginBO();
loginBO.userName = userName.ToString().Trim();
string result = "";
try
{
LoginDao loginDao = DAOFactory.GetDaoFactory().getLoginDao();
result = loginDao.selectUser(loginBO);
}
catch (DBConnectionException)
{
//result = "DB Conenction";
throw new Exception("DB Connection is Down");
}
catch (InvalidLoginException)
{
//HttpResponse res = new HttpResponse();
//HttpResponse.ReferenceEquals.Redirect("~/Login.aspx");
throw new InvalidLoginException("Login Is Invalid");
}
catch (Exception)
{
throw new Exception("Uanble to Fetch ");
}
int ctx = Context.Response.StatusCode;
return result;
}
After Successful Authentication, I want to redirect user to another aspx page.
What is the best practice to do ?
Thanks
Samuel
Add a redirect to the success section of your getLogin() function:
success:
function (response) {
alert(response.d);
windows.location.href = "http://url.for.redirect";
}
(Or use some other method for redirecting within jQuery/Javascript).
In your Ajax method
success: function(msg) {
alert(response.d);
window.location = "xyz.aspx";
},
success: function (response) {
alert(response.d)
window.location.href = "some.aspx";.
}
I think it will help you.

passing parameter to server in ExtJs

I am new in ExtJs.
I want to pass the value in my textbox to the server(Servlet) when I click on to the button. But as I am new to it I don't kn how to do it.
Please someone help me into this or suggest me some tutorial or example for this
Ext.Ajax.request can help you.
Code will be look like this:
new Ext.Button({
text: "Send to server",
handler: function () {
Ext.Ajax.request({
url: 'myPage.php',
success: function (){alert('Value has been sent!');},
failure: function (){alert('Failure of sending...');},
headers: {
'my-header': 'foo'
},
params: { foo: myTextField.getValue() }
});
}
})
in the url put your Servlet class name.
If you have a form with multiple buttons, for example Save, Update, Delete, you can to this :
// Your form fields ...
var buttonAdd = new Ext.Button({text:'Add', handler:addFunction});
var deleteAdd = new Ext.Button({text:'Delete', handler:deleteFunction});
function addFunction(){
Ext.Ajax.Request({
url: 'MyServlet', // you can fix a parameter like this : MyServlet?action=add
method: 'POST',
params: {
myField1: myField1.getValue()
// all your params....
}
success: function (result, request){
alert('Succesfully added ' + result.responseText);
},
failure: function (result, request){
alert('Error in server' + result.responseText);
}
});
function deleteFunction(){
Ext.Ajax.Request({
url: 'MyServlet', // you can fix a parameter like this : MyServlet?action=delete
method: 'POST',
params: {
myField1: myField1.getValue()
// all your params....
}
success: function (result, request){
alert('Succesfully added ' + result.responseText);
},
failure: function (result, request){
alert('Error in server' + result.responseText);
}
});
}
And in your Servlet, you can do this :
public void doPost(HttpServletRequest request, HttpServletResponse response){
String action = request.getParameter("action");
if(action.equals("add")){
// Your code for add method goes here
} else if(action.equals("delete")){
// Your code for delete method goes here
}
}

jQuery and ASP.NET Custom Validator

I'm trying to learn jQuery and it occurred to me that existing JS in some of my sites could be replaced with just a few lines of jQuery code. In the following code, I'm trying to set the value of a custom validator by making an AJAX call. The first block of code does not work as it should, whereas the second block works fine. The whole "if it ain't broke don't fix it" answer isn't helpful, I really want to learn jQuery. For the record, I've placed alerts in the code and they both return the exact same result, just one is setting the args and the other is not for some reason.
Why does this code NOT work:
function CheckForUserName(sender, args)
{
args.IsValid = true;
var url = "/somepage.aspx";
MakeCall(url, function(txt) {
if (txt == "false") {
args.IsValid = false;
}
});
}
function MakeCall(url,callback) {
$.ajax({
url: url,
dataType: "text",
success: callback
});
}
This code DOES work:
function CheckForUserName(sender, args)
{
args.IsValid = true;
var call = MakeCall();
if (call == "false")
{
args.IsValid = false;
}
}
function MakeCall()
{
var xmlHttp;
var validation=true;
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="/somepage.aspx";
xmlHttp.onreadystatechange=function ()
{
if (xmlHttp.readyState==4)
{
if (xmlHttp.status==200)
{
return xmlHttp.responseText;
}
else
{
alert(xmlHttp.status);
}
}
};
xmlHttp.open("GET",url,false);
xmlHttp.send(null);
return xmlHttp.responseText;
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
In order to make it work, you need to specify the async option as false:
function MakeCall(url,callback) {
$.ajax({
async: false,
url: url,
dataType: "text",
success: callback
});
}
This works fyi.. ignore my custom javascript namespace functions, but you should get the concept.
<script type="text/javascript">
function VerifyCustomerNumber(s, a) {
var r = ProcessCustomerNumber(a.Value);
a.IsValid = r;
}
function ProcessCustomerNumber(n) {
var u = '/Services/WebServices/Customer.asmx/CountByCustomerNumber';
var d = '{"Number": "' + n + '"}';
$j.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: u,
cache: false,
async: false,
data: d,
dataType: "json",
success: function(r) {
var v = Data.JS.Ajax.ParseJSON(r);
return v;
}
});
}
</script>
Just for the record. Having a custom validator that allows AJAX calls is possible, but is a litle complicated. Here is an article about the issue.
Basically, one must do these things:
Say "Invalid!" immediately.
Show a "processing..." message instead of your "invalid" message.
Start your long-runing process, AKA your AJAX request.
As soon as your request ends, replace the ClientValidationFunction for a dummy function.
Reset the original message.
Update the validation state.
Reset the original validation function but only when the validated control changes.
Here is the final function that accomplishes the task (taken from the article):
//Create our respond functions...
var Respond_True = function (sender, args) { args.IsValid = true; };
var Respond_False = function (sender, args) { args.IsValid = false; };
function AjaxValidator(sender, args, ajaxSettings){
args.IsValid = false;
//This is a reference to our validator control
var $sender = $(sender);
//Save the original message, color and validation function to restore them later.
var originalMessage = $sender.text();
var originalColor = $sender.css("color");
var originalFunction = sender.clientvalidationfunction;
var validatedControl = $("#" + sender.controltovalidate);
//Change the error message for a friendlier one.
$sender.text("Checking...").css({ color: "black" });
var setRespondFunction = function (respondFunction) {
sender.clientvalidationfunction = respondFunction;
//Reconstitute original styles.
$sender.text(originalMessage).css({ color: originalColor });
//Re-validate our control
ValidatorValidate(sender, null, null);
ValidatorUpdateIsValid();
var onChange = function(){
//Reset the original validation function
sender.clientvalidationfunction = originalFunction;
//Re-validate to ensure the original validation function gets called
ValidatorValidate(sender, null, null);
ValidatorUpdateIsValid();
//Ensure the validation function is called just once.
validatedControl.unbind("change", onChange);
};
validatedControl.on("change", onChange);
}
var originalSuccessFunction = ajaxSettings.success;
//Start the AJAX call..
$.ajax($.extend(ajaxSettings, {
success: function(data){
setRespondFunction(originalSuccessFunction(data) ? "Respond_True" : "Respond_False");
}
}));
}
And here is a sample usage:
function MyJavascriptValidationFunctionName(sender, args){
AjaxValidator(sender, args, {
url: ...,
type: ...,
data: ...,
success: function(data){
return /*True or false*/;
}
});
}

Resources