I hvae a webmethod called using jquery ajax. I hits the error callback. Fine - I thought I will analyze the error - but it is coming as undefined.
What are the possibilities for the error values to be undefined? How to fix this, if it is a trivial error?
Note: xhr,status and error are undefined.
Note: I am using Chrome version 35 and IE 8
CODE
$(document).ready(function () {
function errorFunction(xhr, status, error) {
console.log(xhr);
if (xhr == 'undefined' || xhr == undefined) {
alert('undefined');
} else {
alert('object is there');
}
alert(status);
alert(error);
}
$.ajax({
type: "POST",
url: "admPlantParametersViewEdit.aspx/GetResult",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
alert(msg.d);
},
error: errorFunction()
});
});
You need to pass a reference to the function so change this:
error: errorFunction()
to this:
error: errorFunction
When you put the parens there, you were actually calling the function immediately and passing it's return. Without the parens, it is just a reference to the function that can be called later by the jQuery ajax infrastructure.
To further understand what was happening, your code error: errorFunction() was calling errorFunction() immediately with no arguments (which is what you were seeing in your debugging) and then fetching the return value from that function (which is undefined) and then putting that into your data structure which was passed to the ajax call. So essentially, you were doing the equivalent of this:
$(document).ready(function () {
function errorFunction(xhr, status, error) {
console.log(xhr);
if (xhr == 'undefined' || xhr == undefined) {
alert('undefined');
} else {
alert('object is there');
}
alert(status);
alert(error);
}
// obviously, not what you intended
errorFunction();
$.ajax({
type: "POST",
url: "admPlantParametersViewEdit.aspx/GetResult",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
alert(msg.d);
},
// also not what you intended
error: undefined
});
});
If you aren't using errorFunction() in other places, then a more common way to do this is to define it inline like you did with the success handler like this:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "admPlantParametersViewEdit.aspx/GetResult",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
alert(msg.d);
},
error: function(xhr, status, error) {
console.log(xhr);
if (xhr == 'undefined' || xhr == undefined) {
alert('undefined');
} else {
alert('object is there');
}
alert(status);
alert(error);
}
});
});
Related
I think it is simple question. I've tried to search but still not found an answer yet.
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
success();
}
messageBox(result.d);
},
error: error
});
},
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
I want to show message after success() performed.
That means the comment left already then show message.
Thanks anyway!
P/s: I read a topic about jQuery Callback Functions at https://www.w3schools.com/jquery/jquery_callback.asp.
Can we use it in here? If we can, how to use?
You can try like this
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
success();
}
$.when(this).then(setTimeout(function(){ messageBox(result.d)}, 200));
// if you dont want use set timeout then use
// $.when(this).then(messageBox(result.d), 200));
},
error: error
});
},
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events.
Considering your implementation of var success = function() you may try with following approach:
Modify the success() to accept callback function as follows:
var success = function(callback) {
self.removeComment(commentId);
if(parentId)
self.reRenderCommentActionBar(parentId);
if(typeof callback == "function")
callback();
};
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
//passing the callback function to success function
success(function(){
messageBox(result.d);
});
}
},
error: error
});
},
I am quite green when it comes to AJAX and am trying to get an email address from an ASP.Net code behind function
When using the below code I am getting the error as per the title of this issue.
This is the code I am using
$('.txtRequester').focusout(function () {
console.log("textBox has lost focus");
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Default.aspx/FindEmailAddress",
data: '{id: "' + $("txtRequester").val + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
});
which is an adaptation of the code from this site.
ASP.Net Snippets
When changing the line
success: OnSuccess to success: alert(response) or success: alert(data)
I get the error up, but if I use success: alert("ok") I get the message saying ok so I suspect that I am getting into the function as below.
<System.Web.Services.WebMethod()> _
Public Shared Function FindEmailAddress(ByVal id As String) As String
Dim response As String = GetEmail(id)
Return response
End Function
I would be extremely grateful if someone to help me and let me know where I am going wrong on this one.
thanks
I think you have can check the state of failure by using this code below as I think there is wrong syntax used by you.
$('.txtRequester').focusout(function () {
console.log("textBox has lost focus");
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Default.aspx/FindEmailAddress",
data: JSON.stringify({id: ' + $(".txtRequester").val() + ' }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, status, header){
console.log(data);
},
error: function (response) {
alert(response.d);
}
});
}
});
then definitely you will get error response, if your success won't hit.
You have not called the function thats why its never get called.
$('.txtRequester').focusout(function () {
console.log("textBox has lost focus");
ShowCurrentTime();
});
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Default.aspx/FindEmailAddress",
data: '{id: "' + $("txtRequester").val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
Onsuccess(response);
},
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
This will help :)
use ajax directly ,
$('.txtRequester').focusout(function () {
console.log("textBox has lost focus");
var cond = $(".txtRequester").val();
$.ajax({
type: "POST",
url: "Default.aspx/FindEmailAddress",
data: {id:cond},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response){
alert(response.d);
},
failure: function (response) {
alert(response.d);
}
});
});
Change $('.txtRequester') to $('#txtRequester')
and
Change $("txtRequester").val to $('#txtRequester').val()
i am writing this code in my html page to hide one id in that page..alerts are also not working..method is not called
*<script>
alert("yo");
$(function checkUsertype(email_id)
{
alert("yup")
var usertype = $("#txtusertype").val();
$.ajax({
alert("hide")
url: 'rest/search/userType?email_id='+email_id,
type : "GET",
datatype : 'json',
cache : false,
success : function(data)
{
if(usertype=='webuser')
{
$("#themer").hide();
}
},
error : function(xhr, data, statusText,errorThrown)
{
}
});
})
alert("yo");
<script/>*
This is the problem.
$.ajax({
alert("hide")
You're trying to alert inside the ajax which is Syntax error. Try removing the alert inside ajax and it should work.
You can use alert in success, error callbacks as follow:
$(function checkUsertype(email_id) {
var usertype = $("#txtusertype").val();
$.ajax({
url: 'rest/search/userType?email_id=' + email_id,
type: "GET",
datatype: 'json',
cache: false,
success: function(data) {
alert('In Success'); // Use it here
console.log(data); // Log the response
if (usertype == 'webuser') {
$("#themer").hide();
}
},
error: function(xhr, data, statusText, errorThrown) {
alert('In Error'); // Use it here
console.log(errorThrown); // Log the error
}
});
});
I suspect that I have a missing bracket but I can't find one if there is
$(document).ready(function () {
$("#additional_info_submit").click(function (e) {
e.preventDefault();
jQuery.ajax({
type: "POST",
url: "advice_response.php",
//contentType: "text/json; charset=utf-8",
dataType: "json",
data: $('#form').serialize(),
success: function (response) {
alert('yay');
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
});
});
The json_encode on the advice_response.php was missing a semi colon at the end.
I had the same problem for "PUT" method but I'm using Web Api server side so I had to change in my Web Api Controller Put Method from this :
return Request.CreateResponse(HttpStatusCode.OK);
to this:
return Request.CreateResponse(HttpStatusCode.OK, MyUpdatedObject);
I'm trying to call a function when I get success from my ajax call, but it's not working. This is what I've tryed so far.
function dtMRPReasonCode(dt) {
var data = null;
jQuery.ajax({
type: "POST",
data: {},
url: "Index.aspx/getMRPReasonCodeReport",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d) {
console.log(dt);
console.log(msg.d);
buildTableBody(dt, msg.d);
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert("Error: dtMRPReasonCode");
}
});
return false;
}
function buildTableBody(dt, obj) {
dt.fnClearTable();
data = [];
$(obj).each(function(index, value) {
element = [];
element.push(value.Metric);
element.push(value.Region);
element.push(value.Plant);
element.push(value.Customer);
element.push(value.IMAC);
element.push(value.NotFilled);
element.push(value.Filled);
element.push(value.Total);
data.push(element);
});
dt.fnAddData(data);
}
Thanks in advance!
Edit #1
I used console.log in order to show you what I got from dt and msg.d (Image)
Edit #2
If I paste the commands from buildTableBody function in the success: handler instead of calling buildTableBody function in the success: handler it actually works:
function dtMRPReasonCode(dt) {
var data = null;
jQuery.ajax({
type: "POST",
data: {},
url: "Index.aspx/getMRPReasonCodeReport",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
dt.fnClearTable();
data = [];
$(msg.d).each(function(index, value) {
element = [];
element.push(value.Metric);
element.push(value.Region);
element.push(value.Plant);
element.push(value.Customer);
element.push(value.IMAC);
element.push(value.NotFilled);
element.push(value.Filled);
element.push(value.Total);
data.push(element);
});
dt.fnAddData(data);
},
error: function(xhr, ajaxOptions, thrownError) {
alert("Error: dtMRPReasonCode");
}
});
return false;
}
But it makes no sense to me, since this actually should work in both ways.
Pretty sure you have a typo on your function call
buildTableBody(td, msg.d);
should be
buildTableBody(dt, msg.d);
Also what is the return type from Index.aspx/getMRPReasonCodeReport? If it is string, you've got to unescape the string before you can treat it as JSON.
Try removing contentType : "application/json utf-8" from your AJAX call. That is the type of the data sent to the server. It is likely that you want the default content type.
Unless your server-side resource was configured to accept json it likely accepts application/x-www-form-urlencoded
http://api.jquery.com/jQuery.ajax/