Ajax post parameters ASP.NET MVC 3 - ajax

Hello guys i have the next ajax call for login. I serialize the form and send the data to server and return redirect url link. My problem is that my url after post is like
http://localhost:50802/?username=&password= and not http://localhost:50802/Home
$.ajax({
type: "POST",
url: "Login/Login",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: loginJson,
cache: true,
async: false,
complete: function (result) {
alert(result.link);
window.location.replace = "/Home/Index";
},
error: function () {
$("#username").val("");
$("#password").val("");
alert("Wrong Username or Password!");
}
}); //end ajax call

It looks like you wrote this $.ajax call in the .click event of a submit button or in the .submit event of a form without canceling the default action by returning false from the callback or by calling preventDefault on the argument. Here's how your code should look like:
$('#id_of_your_form').submit(function(e) {
e.preventdefault(); // <-- That's what I am talking about and what you forgot
$.ajax({
type: "POST",
url: "Login/Login",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: loginJson,
cache: true,
async: false,
complete: function (result) {
window.location.replace = "/Home/Index";
},
error: function () {
$("#username").val("");
$("#password").val("");
alert("Wrong Username or Password!");
}
}); //end ajax call
});
Also async: false,????? You know what this does, do you? That's not AJAX. That's a blocking synchronous call to your webserver during which the client browser would be frozen like during the Ice Age 2 ruining all user experience.

Try returning false at the end of your submit function
$('#id_of_your_form').submit(function(e) {
$.ajax({
type: "POST",
url: "Login/Login",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: loginJson,
cache: true,
async: false,
complete: function (result) {
window.location = "/Home/Index";
},
error: function () {
$("#username").val("");
$("#password").val("");
alert("Wrong Username or Password!");
}
}); //end ajax call
return false; });
Another option would of course be to return the correct redirectlink from the controller instead of overriding it in the java script.

Related

laravel and sweetalert and rederect to

i use laravel 5.8 and i have a a problem if i insert or update a page than i go not back to the page list.
postcontroller :
i use : return response()->json('Post Created');
and i use a ajax file whit this code :
$.ajax({
type: 'POST',
url: this.action,
data: new FormData(this),
dataType: 'json',
contentType: false,
cache: false,
processData:false,
success: function(response){
Sweet('success',response)
success(response)
},
error: function(xhr, status, error)
{
$('.errorarea').show();
$.each(xhr.responseJSON.errors, function (key, item)
{
Sweet('error',item)
$("#errors").html("<li class='text-danger'>"+item+"</li>")
});
errosresponse(xhr, status, error);
}
})
});
i get a nice message if it is insert or updated but it not go back to my list, hope you understand what i mean.
if you want to redirect after success do something like this:
$.ajax({
type: 'POST',
url: this.action,
data: new FormData(this),
dataType: 'json',
contentType: false,
cache: false,
processData:false,
success: function(response){
Sweet('success',response)
success(response)
window.location.href = "url you want to redirect to";
},
error: function(xhr, status, error)
{
$('.errorarea').show();
$.each(xhr.responseJSON.errors, function (key, item)
{
Sweet('error',item)
$("#errors").html("<li class='text-danger'>"+item+"</li>")
});
errosresponse(xhr, status, error);
}
})
});

Go to new view on AJAX success using ActionResult

I have an AJAX call that posts data to the server to save to the DB. When this is complete, I want to call another ActionResult in the success callback to switch the user to a brand new view. This needs no data passed to it, I just need the success in the Ajax to call this method. Is this possible? I played with some of the URL helpers but I can seem to make this work, it just does nothing.
$.ajax({
url: 'Mapping/',
type: 'POST',
data: JSON.stringify({
data
}),
contentType: 'application/json; charset=utf-8',
success: function(result) {
if (result.success === true) {
alert('Yes');
} else {
alert('No');
}
},
failure: function() {
alert('No');
}
So this would be in the first part of the success callback where it is currently set at aler('Yes').
Do something like this:
$.ajax({
url: 'Mapping/',
type: 'POST',
data: JSON.stringify({
data
}),
contentType: 'application/json; charset=utf-8',
success: function(result) {
if (result.success === 'true') {
window.location.href = 'Success/';
} else {
//handle the failure from the response
}
},
failure: function() {
//handle the failure of the request itself
}

Replace Ajax Callback with Jquery callback

How to replace the following ajax callback method with a jquery callback method ?
function PostCall() {
$('#txtRes').val('Please Wait......');
var reqval = $('#txtReq').val();
$.ajax({
url: "myPage",
type: 'post',
data: "{'name':'" + reqval + "'}",
async: true,
contentType: "application/json",
success: function (result) {
$('#txtRes').val(result);
}
});
}
Just append the success at the end of your ajax statement (for example):
}.success(function(){
})
If you want to stick with Ajax go the jQuery 1.8 way and try this:
function PostCall() {
$('#txtRes').val('Please Wait......');
var reqval = $('#txtReq').val();
$.ajax({
url: 'myPage',
type: 'post',
data: "{'name':'" + reqval + "'}",
dataType: 'json',
async: true,
contentType: "application/json",
})
.done(function(result) {
$('#txtRes').val(result);
})
.fail(function(jqXhr, textStatus) {
console.log('Error: ...' + textStatus);
})
.always(function() {
});
}
The .done() function replaces your success callback.
If Ajax is not an option for you check out:
WebSockets
Http POST Requests (requires the whole page to be reloaded)

Ajax success not working

I have this:
public ActionResult GetBear(int bearId)
{
return Json(bear);
}
Here is the ajax call to it:
$.ajax({ url: "correctUrl", dataType: 'json', data: { bearId: 2}, contentType: "application/json; charset=utf-8", success: function (data) {
alert("something")
}
GetBear gets executed, but the success method is not entered. What is the porblem?
I added error field and it says Internal server error. Why? I'm not comunicating with a server.
Try this, check if you get alert or not ?
$.ajax({
type: "POST",
url: "correctUrl",
dataType: 'json',
data: {bearId: 2},
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("something")
},
error: function(data) {
//AJAX request not completed
alert("it shows error");
}
And check if page(correctUrl) exist on which you send ajax request..
First check URl Since you wrote function executing
change your function return type from ActionResult to JsonResult

MVC2: Ajax call runs always in error function. Why? Whats wrong?

aspx site:
<script type="text/javascript">
function AjaxTest() {
var codeVal = "hello world";
if (codeVal) {
$.ajax({
type: "POST",
url: "CheckAge",
data: { code: codeVal },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert("in ajax success");
},
error: function () {
alert("error");
}
});
}
}
Its double checked that the javascript function is called.
Controller:
[HttpPost]
public JsonResult CheckAge(String code)
{
return Json("abc");
}
It ended up always in the ajax - error - function.
The Controller function isnt called anyway. Why?
Why get I always an error?
What is wrong?
Check your url that you are posting to. It seems that you are missing the controller part. E.g. it should read /{controller}/{action}.
If that script is directly in the view (i.e. not in an external javascript file) you could have something like:
$.ajax({
type: "POST",
url: <%= Url.Action("CheckAge", "ControllerName") %>,
data: { code: codeVal },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
alert("in ajax success");
},
error: function () {
alert("error");
}
});
Also, I find it advantageous to use firebug to debug ajax stuff. You can set break points in your javascript and also see all the requests and responses.
HTHs,
Charles
EDIT: Try simplifying things... e.g.
$.post('<%= Url.Action("CheckAge", "ControllerName") %>',
{ code: codeVal },
function (data) {
alert("in ajax success");
},
"json");

Resources