ajax success returning undefined data object - c#

I am returning a view from my action method which is called by ajax call.
but in ajax success it is returning undefined object. What is the Problem?
$.ajax({
type: "GET",
url: url,
success: function (data) {
if (typeof (data) === 'undefined') {
alert("Error");
return;
}else {
$('#content').html(data);
}
},
error: function () {
alert("Error");
return;
}
});
Backend code is here :-
public ActionResult Index()
{
return view(); //Index is a view containing only "hello world"
}

I think you declare a same variable in your code somewhere named data and assigned it undefined or you assigned "data = undefined" in console window.
If you do this either close the browser tab or browser itself.
And try again it should work.
For more detail refer following links :-
http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html
and
http://code.tutsplus.com/tutorials/javascript-hoisting-explained--net-15092

I am also using asp.net mvc and jquery ajax request in my application as well also tried your ajax code which is perfectly right. Possible reason for your error could be in your return view() like it could not be find.
One most another thing is as you are using ajax request it will not show any error directly for that you have to inspect in your browser console. I hope you will find problem while you inspect in your browser.

Related

Ajax redirect in ASP.NET MVC

I am learning ASP.NET MVC and I am facing an issue in Ajax redirect. In normal post or get call we can return the user to some specific page like:
return RedirectToAction("AllStudents");
but using json, it's different or may be I don't know much about it.
I have posted my code in normal and also converted to Ajax.
What I have tried
Controller code in general:
[HttpGet]
public ActionResult Delete(int id)
{
stude.DeleteStudent(id);
return RedirectToAction("AllStudents");
}
and I have use Ajax which do the work successfully but it is not redirecting the user to another page, like in the above code it redirects the users to another page.
My Ajax controller code:
[HttpPost]
public JsonResult Delete(int id)
{
stude.DeleteStudent(id);
return Json("true",JsonRequestBehavior.AllowGet);
}
My Js code:
// Delete record
$("#del").click(function (e) {
e.preventDefault();
var id = $("#stid").val();
//alert(id);
$.ajax({
method: "POST",
url: "Delete/" + id,
contentType: "application/json; charset=utf-8",
async: true,
data: JSON.stringify(id),
success: function (data) {
console.log(data);
},
error: function (err) {
console.log('Failed to get data' + err);
}
});
});
The action is performed and data is deleted but the browser stop like:
updated
My goal: I want that the data is deleted without the page refresh, like it normally does. Also please share a link, post, something which shows the page refresh using ajax. like I want to refresh a page after every 1 minute but without reloading it.
Update: The data is now deleting but the Red highlighted (page) is not refreshing, I have to manually refresh, which I don't want. I want to refresh it silently without reload it.
if you will refresh the grid only then create a timeout method are follow as:
setTimeout(function() {get grid data by ajax call}, 10000);
if you want to reload the whole page then
create one partial view.
create an action method and return PartialView().
create ajax call and getting response to add in div like divid.html(data);
if you refresh the page every 1 min then create a time out function and create a simple ajax.
setTimeout(function() { ajax call}, 10000);

Unable to redirect to external URL in MVC controller

I am trying to integrate atoms payment gateway in my MVC project. I have been getting this nasty error even after enabling CORS. So I thought perhaps it is the return url that is causing the issue. So I wrote a simple redirect to find out real cause return Redirect("https://google.com"); but i am still getting same error. What am I doing wrong?
public ActionResult TransferFund()
{
return Redirect("https://google.com");
}
Failed to load https://google.com/: Response to preflight request doesn't pass
access control check: No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:25850' is therefore not allowed
access. The response had HTTP status code 405.
I have followed This to redirect
EDIT
<script type="text/javascript">
$(document).ready(function () {
$('#btnatom').on('click', function () {
$.ajax({
type: 'POST',
url: "/AtomPayment/TransferFund",
data: {},
dataType: "text",
success: function (resultData) { alert("Save Complete") }
});
});
});
</script>
[HttpPost]
public ActionResult TransferFund()
{
return new RedirectResult("http://google.com");
string strURL, strClientCode, strClientCodeEncoded;
....
}
You could not make redirect in 'TransferFund' method, becuase of 'POST' method. Do it from jquery. Here corrected code:
<script type="text/javascript">
$(document).ready(function () {
$('#btnatom').on('click', function () {
$.ajax({
type: 'POST',
url: "/AtomPayment/TransferFund",
data: {},
dataType: "text",
success: function (resultData) {
if(resultData == "Ok"){
alert("Save Complete");
window.location = "https://google.com/"
}
}
});
});
});
</script>
[HttpPost]
public ActionResult TransferFund()
{
//do some transfer work
return Content("Ok");
}
let's drill down into the error:
Failed to load https://google.com/: Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin
'http://localhost:25850' is therefore not allowed access. The
response had HTTP status code 405.
you are hitting a Cross Domain request issue.
Google is denying you, for security reasons from reaching it's server. It doesn't matter if you issue POST or GET request, google doesn't recognize your domain and blocks your cross-domain request.
If you use jquery it will work, yes, because you make a request from client-to-client using the window.location property of java script.
if you want to RedirectResult from your controller code, you need to use address at your local domain that will accept the request and won't deny it.
you can read more here about Error 405.
what it means, is:
The administrator can configure each web server so that the individual
methods are either allowed or not allowed. For example, if there’s no
interactive content on the website, it’s only logical that the POST
method isn’t allowed, since the user has no options to enter their own
data and send it to the server. Otherwise, the error message mentioned
above with the status code 405 would appear, informing the browser and
its user that the method is not allowed.
Just Incase anyone needs:
First redirect your other "http://example.com" to another controller ("RedirectController") without httpMethod
[HttpPost]
public IActionResult TransferFund(){
Return Redirect("redirect?url=http://example.com");
}
Now in:
RedirectController.cs
RedirectController(){
public IActionResult Indext(){
var url = Request.Query["url"];
Return Redirect(url);
}
}
or we can redirect to current controller btw

Update the Page without refresh it

Goal:
When you click on the row (1), new data shall display (3.) without the whole webpage will be updated/refreshed.
Problem:
1.
I need advice and I don't know where to find the funciton to display the picture number 2 and how to display the data and new object (3.) without update/refresh the whole webpage?
And
2
How do you create an icon to display loading picture?
Information:
- The page is based on ASP.mvc with C#
Use ajax functionality of either jquery or MVC ajax helpers.
You can find jquery ajax here.
and MVC ajax helper lib here
and here
you can make an ajax call to the server's websevice and it can return one of the well known web format (for e.g. json or XML). When the webservice call returns you can then "inject" the data in your html page with either javascript (dom manipulation) or using MVC helpers.
Here's one that could help..
http://www.asp.net/mvc/tutorials/older-versions/javascript/creating-a-mvc-3-application-with-razor-and-unobtrusive-javascript
You Can use jquery ajax which would call async action method(function). Data is returned the form of Json. You can write code to deserilize data and display it using jquery.
Create a Action method which would return JsonResult as viewresult as
public JsonResult GetJsonData()
{
return Json(new
{ testDataResult =TestDataResultObj.Data
JsonRequestBehavior
}, JsonRequestBehavior.AllowGet);
}
and write following jquery code:-
if (GetDataAsyc()) {
$.ajax({
type: "GET",
data: { testData: testDataResult },
url: url,// url of action method to be called asynch
dataType: "json",
cache: false,
traditional: true,
contentType: "application/json",
success: function (data) {
// on success assign testDataResult to messages //line
$("#MessagesLines").html(testDataResult .Html);
}
},
error: function () {
//Display error message
$("ErrorMsg").html("There was error whey trying to process your request")
}
});
}
Use ajax+PartialViews to update some page sections

FireFox and IE9 tries to download or show json-response instead of letting javascript parse it

Update
My problem was that I used event.preventDefault() instead of return false to hinder the form from posting normally. FF and IE didn't like that and broke the JS by that line. I removed that and appended return false at the end and this solved the problem. Thanks to Darin Dimitrov for the extensive checklist.
Original question
I'm using ASP.NET MVC3 and jquery ajax to post json-data to the server and receive a response. However, when I'm using Chrome it reads the json-response normally, updating the divs that I want etc. With IE and FF it doesn't work though. They read just the response and shows only that on the page.
I saw some other threads mentioning to define the mime type as "text/plain". This changed the previous behavior of prompting the user to download the json-response instead.
This is the javascript for making the post:
$.ajax({
url: $("#formRegister").attr("action"),
type: 'POST',
data: JSON.stringify(user),
dataType: 'json',
contentType: 'application/json, charset=utf-8',
traditional: true,
success: function (data) {
alertMessage(data.Message);
},
error: function () {
}
});
This is the ActionMethod receiving the call and returning a JsonResponse:
[HttpPost]
public JsonResult Register(UserRegisterPackage package)
{
ClientAlert alert = new ClientAlert();
if (package.Password != null)
{
//bool success = Removed for simplicity's sake.
bool success = true;
if (success)
{
alert.Message = "Success!";
}
else
{
alert.Message = "Failed to register";
}
}
else
{
alert.Message = "You need to enter a password!";
}
return Json(alert, "text/plain");
}
As I said, when the content type is defined as text/plain the browser shows only the response and when it's not defined it prompts the user to download the json-response instead.
With FF I seem to get an error about:
"event is not defined
event.preventDefault(); "
This could have something to do with the error.. but I need to prevent the form from posting normally. Is this done differently in FF or IE?
Any ideas?
Things to try:
If this $.ajax call is made inside the .click or .submit handler of some anchor or <form> make sure you return false; at the end in order to cancel the default behavior and leave time for your AJAX request to execute. The attr('action') that you are using leaves me to believe that this is the case.
Remove traditional: true parameter, you are sending a JSON request => it is irrelevant.
Make sure there aren't some other javascript errors on your page as they might stop js execution and proceed into normal form submission
Remove all text/plain from your server if you intend to return JSON. It's meaningless to do something like this and it's definitely not where your problem comes from. Simply use return Json(alert);.
So if you are AJAXifying a form you don't even need any JSON requests, simply:
$('#formRegister').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (data) {
alertMessage(data.Message);
},
error: function () {
}
});
return false;
});
and if you intend to send JSON requests then your code seems fine, jsu make sure there aren't some other JS errors.
I faced the same problem where "JsonRequestBehavior.AllowGet" worked great on chrome, but fails on IE. i tried many formats, but below is the only one worked for IE.
return Json(additionalData, "text/html")
I encountered this when using an older version of jQuery.Validate, something to do with a bug in there setting the incorrect dataType.
Make sure you are using the latest version of jQuery.validate
return Json(alert, "text/plain");
Usually Json(alert) should be enough. Can you try with application/json; charset=utf-8 as a content type?

jQuery does not load response

I normally use ASP.NET MVC 2, but there were some problems with it, so I began to work with ASP.NET MVC 2 + jQuery and everything works. But there is one problem, jQuery doesn't load my reponse. On the ASP.NET MVC side I'm redering a partial view and I also get the respone on the client, but nothing is rendered. How can I solve this?
Here is the jquery code:
function addCredential(state, id) {
var daten = getJson(state, id);
$.ajax(
{
type: "POST",
url: "/Account/SetCredential/",
data: daten,
dataType: "json",
success: function(partialView) {
$('#Credentials').replaceWith(partialView);
location.reload();
}
});
return true;
};
function getJson(state,id) {
var username = $('#username').val();
return {"username": username, "credential_id": id , "state": state };
};
The problem looks like location.reload();
That's reloading your page after you update it with AJAX, effectively returning it's state back to the way it was before you inserted the content with .replaceWith()
UPDATE: looks like you're using dataType: "json" and inserting that into the DOM? That's probably also a problem. If the view is being returned as HTML, you should replace that with dataType: "html"
#Konrad, try using the JSON2 library (http://www.json.org/js.html) to alert the "partialView" object in your success function to see what you're getting prior to reloading the page. Also, make sure $('#Credentials') is returning an object. When I run into issues when trying to select elements on the page, I usually check the length value of the jQuery object that is returned. If length = 0, then you're not getting the element.
UPDATE:
Also, if you're trying to inject HTML into $('#Credentials'), then partialView may not be the correct format. The success function accepts an object argument which comes from parsing of the responseText of the web method you called to get what you call partialView.
UPDATE:
Check http://encosia.com/2010/03/03/asmx-and-json-common-mistakes-and-misconceptions/ for more info using $.ajax. Lots of great info on this blog.
UPDATE:
This is how I use JSON lib to view the data that is returned.
alert(JSON.stringify(partialView));

Categories