Message from webpage undefined - asp.net

I am returning a simple string from a webmethod to a Javascript function.
I am using an AJAX enabled website in ASP.NET 2.0. I get the date in firefox but inside IE 8 it returns undefined.
Do I have to parse the string in the JSON format using some serialize class? In my webmethod, I am just using:
return DateTime.Now.ToString();
$(document).ready(function(){
var pageUrl = '<%=ResolveUrl("~/test/test.aspx")%>';
// Test
$('#<%=trgNo.ClientID%>').change(function(){
var trgId = $(this+'input:checked').val();
$.ajax({
type: "POST",
url : pageUrl+ '/getDet',
data : '{categ: "' +trgId + '"}',
contentType:"application/json; charset=utf-8",
dataType:"json",
success:OnSuccess,
failure: function(msg){
if(msg.hasOwnProperty("d"))
alert(msg.d);
else
alert('error fetching values from database');
}
});
});
function OnSuccess(msg)
{
if(msg.hasOwnProperty("d"))
alert(msg.d);
else
alert(msg);
}
});
Edit
It seems the success function is firing the problem is with response 'alert(msg)' works in firefox but not in IE 8 with asp.net 2.0

Maybe you dont want to use this, but I´m very happy with the asp net ajax build in function, since it builds a header, that works properly on browsers.
$(document).ready(function(){
var pageUrl = '<%=ResolveUrl("~/test/test.aspx")%>';
// Test
$('#<%=trgNo.ClientID%>').change(function(){
var trgId = $(this+'input:checked').val();
var proxy = Sys.Net.WebServiceProxy;
proxy.invoke("", // if current page "", if webservice "/srv.asmx"
"getDet", //method name
false, //post = true, get = false
{ categ : trgId }, //javascript object
OnSuccess, // Success Function
onError, // Error Function
{ yourOwn : userData } // Custom User Data to Handler
);
});
function OnSuccess(response, usercontext)
{
// usercontext.yourOwn === userData;
// response is sent WITHOUT "d", it is removed internally by the proxy
alert(response);
}
});
Dont forget to include the ScriptManager...

Related

MVC 5 JsonResult returns html?

I have been following this tutorial https://www.youtube.com/watch?v=c_MELPfxJug regarding ajax and JsonResult in HomeController
I did the tutorial, however for some reason the controller is returning Html and not json
I did not change one line of code, but it's failing with parseError on the javascript side.
when i look at the response i see an html page, not a json object.
Controller code:
public JsonResult DoubleValue(int? Value)
{
if (!Request.IsAjaxRequest() || !Value.HasValue)
{ return null; }
else
{
int DoubleValue = Value.Value * 2;
var ret = new JsonResult
{
Data =
new { DoubleValue = DoubleValue }
};
return ret;
}
}
cshtml:
#using (Html.BeginForm())
{
#Html.TextBox("txtAmount",0)
<button id="btnDoubleValue">DoubleIT</button>
<div id="lblMessage"></div>
}
#section Scripts{
<script type="text/javascript">
$(function () {
$('#btnDoubleValue').on('click', function() {
$.ajax({
type: 'POST',
url: '#Html.Action("DoubleValue")',
data: { 'Value': $('#txtAmount').val() },
datatype: 'json',
cache: 'false'
}).success(function (data) {
var t = data;
$('#txtAmount').val(data.DoubleValue);
}).error(function (x, o, e) {
$('#lblMessage').html('error was found: ' );
});
return false;
})
});
</script>
}
found the error
I was using Html.Action and not Url.Action -> just human error I suppose
from the reference:
Html.Action - returns the result as an HTML string.
It works now
$.ajax({
type: 'POST',
url: '#Url.Action("DoubleValue")', //<--- Url.Action
data: { 'Value': $('#txtAmount').val() },
datatype: 'json',
cache: 'false'
I guess this must be the default error page, you are probably getting a 500 response and you must use the Network tab of your browser to see the real problem.
In your browser open developer tools using F12 key and navigate to Network tab.
Make the appropriate actions to do the ajax request (click on that button)
Click on the request row
Navigate to Response tab.
From there you can watch the real request your ajax does and the response from the server.

HttpResponseMessage Headers.Location Seemingly Being Ignored

I have the following Web Api method, which works fine as far as creating a new product and setting the location. I know this because I check the response header in Google developer tools and see that it is valid. If I cut and paste the location from tools to the browser, the page loads fine. However, it will not load as a result of returing the response from the method.
public HttpResponseMessage PostProduct(Product product)
{
productsRepository.Create(product);
var response = Request.CreateResponse<Product>(HttpStatusCode.Created, product);
string uri = Url.Link("ProductsIndex", null);
response.Headers.Location = new Uri(Request.RequestUri,"/Products/testview");
return response;
}
The jQuery that calls PostProduct:
$("#createjQButton").click(function () {
var product = { Name: $("#Name").val(), Category: $("#Category").val(), Price: $("#Price").val() };
var json = JSON.stringify(product);
// Send an AJAX request to create a new product
$("#createjQButton").click(function () {
var product = { Name: $("#Name").val(), Category: $("#Category").val(), Price: $("#Price").val() };
var json = JSON.stringify(product);
$.ajax({
url: '/api/productsapi',
cache: false,
type: 'POST',
data: json,
contentType: 'application/json; charset=utf-8'
});
return false;
});
Why is the location being ignored?
Well, I added
statusCode: {
201 : function() {
window.location.replace("/Products/testview");
}
to my jQuery click function and got to the desired page that way. But should not the original way have worked?

Check UserName availability by using AJAX in asp.net

I'm creating a SignUp form,i want to add a feature to the form in which whenever a new user types an username in the text box, it should automatically check if the username is already taken or not(should compare it with usernames exist in SQL server database). I want to implement this feature using AJAX.
Use the following jquery code, don't forget include jquery libraries
$("#<%=txtJournalIdToMove.ClientID %>").blur(function () {
var journalTextBoxId = '<%= this.txtJournalIdToMove.ClientID %>';
var journalId = $("#" + journalTextBoxId).val();
var params = '{"JournalId":"' + journalId + '"}';
$.ajax({
type: "POST",
url: "Default.aspx/PopulateVolumeNo",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// Replace the div's content with the page method's return.
var returnValue = data.d;
if (returnValue == null) {
alert("The given journal id does not exist or is in active in db.");
}
else {
//If success do your functionality
});
}
}
});
});
Try this onchange or on blur event of a textbox. Here I used user-name-box as text box id
$.post('/Server/CheckAvailablity/',
{name:function(){return $('#user-name-box').val()},
function(response){
if(response.status="Y"){
alert('available');
}
else{
alert('not available');
}
}
);
In server side CheckAvailablity method prepare a JSON object like {"status":"Y"} and return

How can I return a value from a function that uses a jQuery ajax call?

I have the following Javascript function that makes a call to an Asp.Net WebMethod that returns true if a username already exists and false if it does not.
The following will give me the correct answer in an alert box but if I change the
alert(result.d) to return result.d
the result of the function is always undefined.
How can I get the function that the Ajax call is contained in to return a value based on the response from the WebMethod?
function doesEnteredUserExist() {
var valFromUsernameBox = $("#txtUserName").val();
var jsonObj = '{username: "' + valFromUsernameBox + '"}';
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: jsonObj,
dataType: 'json',
async: false,
url: 'AddNewUser.aspx/IsUserNameValid',
success: function (result) {
alert(result.d);
},
error: function (err) {
alert(err);
}
});
}
The thing to note is that the ajax function is non blocking. You specify two callback functions, one for success and one for error, one of these functions will get executed when the underlying request is finished.
Your doesEnteredUserExist does not wait for the ajax call to complete, and thus, the return value of the function is undefined.
The proper way to continue execution based on the result of your call is to break your functionality out into a separate function, and call that from your success function.
Ajax is asynchronous so once the function "doesEnteredUserExist" returns, the ajax call is not yet finished. Then later in the success callback you have the value. From there you should continue with your code and display the info to the user.
Store the value of result.d in a variable, then use it for whatever you would like.
Change this:
success: function (result) {
alert(result.d);
},
to this:
success: function (result) {
var resultString = result.d;
},
Now whenever you need result.d, just use the variable resultString. Basically, the ajax call is the only thing that can call the function that you wanted to return the value for, so you need to store that value when the function is called.
Maybe give this a bash
function onSucess (data) {
alert(data.d);
}
function doesEnteredUserExist() {
var valFromUsernameBox = $("#txtUserName").val();
var jsonObj = '{username: "' + valFromUsernameBox + '"}';
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: jsonObj,
dataType: 'json',
async: false,
url: 'AddNewUser.aspx/IsUserNameValid',
success: onSucess,
error: function (err) {
alert(err);
}
});
}
I am guessing that you are trying to set result.d which is out of scope from the call which is why the alert (result.d) works as its in scope.
I may be getting the wrong end of the stick, you could use a global variable (not recommended), set that in the ajax return which you could then read from your function.
May need a bit more info or clarity on what your trying to achieve, as I read the question a couple of ways.
I normally do this (havent tested this):
function ajaxLoad(callback)
$.ajax({
type: 'POST',
async: true,
url: 'url.aspx',
data: d,
cache: false,
contentType: 'application/json',
dataType: 'json',
error: function (xmlHttpRequest, textStatus, errorThrown) {
//error stuff
},
success: function (data) {
if (typeof callback == 'function') { [callback(data)]; }
}
});
}
function callback(data)
{
alert(data);
}
call the function using
ajaxLoad('callback');
something like that!
Inside your success callback function if you return some value it doesn't set the return value for it's parent function. In this case the parent function is $.ajax and it always returns a jqXHR deferred object.
If you are using jQuery 1.5 or later the you can use deferreds. The idea is to save the jqXHR object returned from the AJAX request and wait for it to complete before returning it's value:
var jqXHR = $.ajax({...});
$.when(jqXHR).then(function (result) {
return result.d
});
Docs for $.when(): http://api.jquery.com/deferred.when
An example of doing this would be to return the jqXHR object from your function and then wait for the AJAX request to resolve outside the function:
function doesEnteredUserExist() {
return $.ajax({...});
}
$.when(doesEnteredUserExist).then(function (result) {
//you can access result.d here
});
As #timing has mentioned, by the time the value is returned from thefunction, the ajax call is not complete so everytime you get the undefined.
This is not a solution to the problem, but an alternative method you can try for displaying it would be instead of returning the value, just update the innerHTML of some element like div with the returned text.Below is what I mean:
function doesEnteredUserExist() {
var valFromUsernameBox = $("#txtUserName").val();
var jsonObj = '{username: "' + valFromUsernameBox + '"}';
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: jsonObj,
dataType: 'json',
async: false,
url: 'AddNewUser.aspx/IsUserNameValid',
success: function (result) {
//alert(result.d);
if(result.d==true){ //Just a check for the value whether true or 1 etc..
$("#notifications").html('Username Already Exists'); // Have a div where you can display the message (named it notifications here) , update the notifications div text to notify the user
}else{
$("#notifications").html('Username is Available');
}
},
error: function (err) {
alert(err);
}
});
}
This seems a good example of $.Deferred object usage
the idea is quite simple (really, I promise, :) see steps on the code)
Create a new deferred object
Make your ajax call. If result is false you will reject the deferred otherwise you will resolve it (you could reject it also on error ajax callback)
return the promise
Use .when() helper to check the status of the promise.
I create a fiddle which return randomically true or false in the response
function checkUserExist() {
var dfd = $.Deferred(); /* step 1 */
$.ajax({
url: "/echo/json/",
data: {
"json": JSON.stringify({d: (Math.random() < 0.5) })
},
type: "POST",
success: function (data) {
console.log("result (inside ajax callback) ", data.d);
if (!data.d) { dfd.reject() } else { dfd.resolve(); } /* step 2 */
},
error : ...
});
/* step 3 */
return dfd.promise();
}
$.when(checkUserExist()) /* step 4 */
.fail(function() { console.log("user don't exist (inside fail)"); })
.done(function() { console.log("user already exist (inside done)"); })
fiddle url : http://jsfiddle.net/Gh9cN/
(note: I've changed some internal details so to make it work on jsfiddle)

aspx and jquery.ajax is always returning an error

This code worked fine in mvc2, but moving back to traditional ASPX (because of Sharepoint 2010). I am encountering errors. Can anyone tell me what I am doing wrong for this framework?
This ajax call is in the $.ready
$.ajax({
type: "POST",
dataType: "json",
data: 'siteName=a&siteUrl=b',
url: 'Wizard.aspx/DoesNameUrlExist',
beforeSend: function () { alert("before send"); },
complete: function () { alert("complete"); },
success: function (data) { alert("success"); },
error: function (data) {
if ($("meta[name=debug]").attr("content") == "true") {
//Full Error when debugging
var errDoc = window.open();
errDoc.document.write(data.responseText);
errDoc.document.close();
}
else {
// generic error message for production use
alert("An unexpected error occurred.");
} return false;
}
});
code behind
[WebMethod]
public static string DoesNameUrlExist(string siteName, string siteUrl)
{
//do something
return someString;
}
I get an error everytime.
You need to send JSON to the service and indicate that you're doing so via the contentType header:
$.ajax({
type: "POST",
contentType: 'application/json',
data: '{"siteName":"a","siteUrl":"b"}',
url: 'Wizard.aspx/DoesNameUrlExist',
beforeSend: function () { alert("before send"); },
complete: function () { alert("complete"); },
success: function (data) { alert("success"); },
error: function (data) {
if ($("meta[name=debug]").attr("content") == "true") {
//Full Error when debugging
var errDoc = window.open();
errDoc.document.write(data.responseText);
errDoc.document.close();
}
else {
// generic error message for production use
alert("An unexpected error occurred.");
} return false;
}
});
More info here: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Also, if you're using jQuery 1.4, you can drop the dataType. jQuery will infer JSON automatically based on the response's Content-Type header.
Ajax calls in jQuery will always give you an error if you declare your contentType as json and the response content type is anything but json. If the response from your WebMethod has something different (such as html or text), you'll always get that error. You can set that response type on your method like this:
[WebMethod]
[ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string DoesNameUrlExist(string siteName, string siteUrl)
Outside of WebMethods this can also be achieved like this:
Response.ContentType = "application/json";

Resources