ajax error not refreshing - ajax

My .jsp page partial code
function runAjax(){
$.ajax({
type: "POST",
url: "Test.html",
data: { testparam1,testparam2},
success: function(data){
document.getElementById("processdata").innerHTML="Success";
},
error: function(e){
document.getElementById("processdata").innerHTML="Error";
}
});
}
In my controller that handles the post, i raise an error on purpose for testing. The client code shows the message 'Error'. With same session, i refresh my page and run it so that the error is not raised. INstead of "Success" I still see 'Error" even though i know the controller worked as expected.
should i be doing this
function runAjax(){
$.ajax({
type: "POST",
url: "Test.html",
data: { testparam1,testparam2},
success: function(data){
document.getElementById("processdata").innerHTML="Success";
},
error: function(request){
document.getElementById("processdata").innerHTML="Error";
}
});
}
and then in the controller
try{
...
}catch(Exception e)
{
response.getWriter().print("An error occured");
}
If in my original code the error is being cached, how do I clear it each time my controller is called?

Related

ajax GET request neihter success nor failure executing

I have the following ajax request:
function getDetails()
{
$.ajax({
type: 'GET',
url: 'http://xxxxxx/get_determined_prize.php',
success: function(result)
{
alert(result);
},
fail: function()
{
console.log("Failure!!");
}
});
}
which calls the following php file containing the following code:
<?php
echo "5";
?>
can someone pinpoint what is the problem with my code? when i debugged the javascript method, during the execution of the ajax request, both the success and failure methods where skipped.
Please follow the link and try this
http://api.jquery.com/jQuery.ajax/
var request= $.ajax({
type: 'GET',
url: 'http://url/get_determined_prize.php',
success: function(result)
{
alert(result);
}
});
request.fail( function()
{
console.log("Failure!!");
});
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

Trap message/exception in jquery to ELMAH

In my MVC3 application, I am returning messages from my stored procs. If it is 'successful', I'm moving forward else displaying a custom error page.
When the message is something else, I want to trap it in ELMAH. The problem that I am facing is that the return message is not really an error so I'm not able to figure out how to handle it. I still want to display the custom error page after catching the error in ELMAH.
Please help.
$.ajax({
url: "../XYZ",
type: 'POST',
dataType: 'text',
async: false,
data: JSON.stringify({ abcData: abcData, strDeb: strDeb, strCre: strCre }),
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (logout != "Logout") {
if (data.toLowerCase() != "successful") {
**//alert(data.toString());
window.location.href = "../Error";**
} else {
window.location.href = "../ABC";
}
}
},
error: function () {
var sessionWindowElement = $('#SessionLayoutLogOutWindow');
sessionWindowElement.data('tWindow').center().open();
}
});

Ajax Call with PUT method

i am trying to make ajax call with PUT method. Below is the code, but i am getting with the error XML Parsing Error: no element found Location: moz-nullprincipal:{c847a4af-f009-4907-a103-50874fcbbe35} Line Number 1, Column 1:
$.ajax({
type: "PUT",
async: true,
url: "http://localhost:8080/karthick/update",
data: JSON.stringify(params),
contentType: "application/json",
dataType: "JSON",
processdata: true,
success: function (json) { //On Successfull service call
},
error: function (xhr) {
alert(xhr.responseText);
}
});
return false;
};
function ServiceFailed(xhr) {
alert(xhr.responseText);
if (xhr.responseText) {
var err = xhr.responseText;
if (err)
error(err);
else
error({ Message: "Unknown server error." })
}
return;
}
But this service is working Good with Rest-client jar. Also my POST method works fine in my browser. Please help me in this.
Regards
Karthick
Usually, this error comes, when making a cross browser request. Try data: JSONP and see if it helps.

How to use an ajax call's response to manipulate a dynamic page?

I am trying to submit a form with the user's inserted data and get the html back from the page called (update.asp).
How do I get the html response and how do I write it to a div on the page? The response would be "success".
If my page throws a 500 or other type of error, how can I handle that?
$('input#btnUpdate').click( function() {
$.ajax({
url: 'update.asp',
type: 'post',
dataType: 'json',
data: $('form#myForm').serialize(),
success: function(data) {
// how do i catch the response? is this the right place?
},
error: function(data) {
// how do I catch the error code here?
}
});
The response from the server in both cases would be passed to the callback as the data variable in your example. Try using console.log(data) inside of your callbacks to see the result in your developer console.
$('input#btnUpdate').click( function() {
$.ajax({
url: 'update.asp',
type: 'post',
dataType: 'json',
data: $('#myForm').serialize(),
success: function(response) {
$("#yourDIV").html(response);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError); //output, 500
}
});
});
More on this: ajax()

asp.net mvc ajax driving me mad

how come when I send ajax request like this everything works
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: ShowMsg("Song deleted successfully"),
error: ShowMsg("There was an error therefore song could not be deleted, please try again"),
dataType: "json"
});
});
But when I add the anonymous function to the success It always showes me the error message although the song is still deleted
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: function () { ShowMsg("Song deleted successfully"); },
error: function () {
ShowMsg("There was an error therefore song could not be deleted, please try again");
},
dataType: "json"
});
});
what if i wanted few things on success of the ajax call, I need to be able to use the anonymous function and I know that's how it should be done, but what am I doing wrong?
I want the success message to show not the error one.
function ShowMsg(parameter) {
$("#msg").find("span").replaceWith(parameter);
$("#msg").css("display", "inline");
$("#msg").fadeOut(2000);
return false;
}
Make sure your action is returning Json data.
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
http://api.jquery.com/jQuery.ajax/
Your action method should surely return Json data. I have the similar code see if that helps.
public ActionResult GetAllByFilter(Student student)
{
return Json(new { data = this.RenderPartialViewToString("PartialStudentList", _studentViewModel.GetBySearchFilter(student).ToList()) });
}
$("#btnSearch").live('click',function () {
var student = {
Name: $("#txtSearchByName").val(),
CourseID: $("#txtSearchByCourseID").val()
};
$.ajax({
url: '/StudentRep/GetAllByFilter',
type: "POST",
data: JSON.stringify(student),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(result) {
$("#dialog-modal").dialog("close");
RefreshPartialView(result.data);
}
, error: function() { alert('some error occured!!'); }
});
});
Above code is used to reload a partial view. in your case it should be straight forward.
Thanks,
Praveen

Resources