How to catch JSON result from ASP.NET MVC 4 Controller? - javascript

I'm trying to catch data from the AJAX POST, which I've sent via jQuery to controller endpoint of ASP.NET MVC, like this:
$("form#auth").submit(function() {
var login = $('input[id=login]').val();
var password = $('input[id=password]').val();
$.ajax({
url: "/Home/Auth",
type: "POST",
data: "Login=" + login + "&Password=" + password,
dataType: 'json',
contentType: 'application/json; charset=utf-8'
success: function() {
}
});
I've tested the controller understads what I'm sending to him, but the main problem is with the returning the result for my jQuery function.
I'm returning the result from Controller like this:
http://ideone.com/hNkF3Z
But I don't understand why the server is returning a file for download:
If to open the file, the result is valid: {"Result":"failed"}
I know, that I didn't write a code in a success function in JavaScript, but I think server must not return a file download and also the debugger must stop at the breakpoint, which was defined on last scope } of success function.

What you're seeing is the default form submission. Because you don't prevent the default browser action, the form is still being posted as if the event handler wasn't even there.
Update your JavaScript to prevent the default browser behavior with e.preventDefault()
$("form#auth").submit(function(e) {
e.preventDefault();
/* rest of your code here. */
}

Related

Opening new page passing parameters without showing them on the URL

I'm making a MVC C# Web App, and I began wondering whether you could open other pages that need parameters to function, without actually sending them through the URL, which is unsafe, and can lead to some user messing up another registry of the database.
My issue is though, I've never done such a thing, and I cannot find any example of code that does such a thing. The project is run with C# and JS, and the main things I've tried include:
-Doing so with Ajax:
First of all I have a button that calls for a function:
Link Text|
function openHorario(id, id_schedule, id_tool) {
alert(oid, id_schedule, id_tool);
$.ajax({
type: 'POST',
url: '/Schedules/actionEditStuff',
data: {
id: id,
id_schedule: id_schedule,
id_tool: id_tool
},
async: 'false',
success: function (data) {
//???
}
});
}
I know there's a way to go to a new page with the success Ajax return, but... That also requires for you to send the parameters through URL.
Obviously, that didn't work, because what the action does in the controller is to return a view, not a page. So... I realized that my idea was not very smart, and moved onto somewhere else: Link, but those always end up having to send the parameters visibly through URL.
Is there any way at all to do this in a proper, clean manner?
Thank you!
#Layan - just to illustrate my comment above, - you could implement something along these lines:
your client side invokes via ajax
...
var data = {
id: id,
id_schedule: id_schedule,
id_tool: id_tool
};
$.ajax({
url: '/Schedules/actionEditStuff',
type: "POST",
data: data,
contentType: 'application/json; charset=utf-8',
success: function (view) {
//load returned data into div? or popup?
}
, error: function (xhr, status, error) {
...
}
});
...
and your controller action
public ActionResult actionEditStuff(....parameters...)
{
...
...do your magic ...
return PartialView("~/Views/_PartialViewThatShowsSomething.cshtml", ...pass model...);
}

How can I send an object to the server on form submit without ajax?

I have an application that is written on the top of ASP.NET MVC 5 framework. For one page, I am using this awesome jQuery-QueryBuilder plugin to let the user create filters to narrow down the results of the dataset.
When the user submits the form "by clicking the submit button" I want to call a function builder.queryBuilder('getRules') provided by jQuery-QueryBuilder which returns and object that needs to be sent to the server. I don't want the request to be sent as string. Also I don't want to sent it as ajax request.
Here is what I have done. The following code is not working. When the server receives the request the rules are always null.
$('#submit-form').click(function (event) {
event.preventDefault();
var btn = $(this);
var rules = builder.queryBuilder('getRules');
if (!$.isEmptyObject(rules)) {
$('#QueryBuilder_Rules').val(rules);
btn.closest('form').submit();
}
});
I tried to use AJAX to send the post request to the server like the code below shows. The code below worked fine. However, I don't want to use AJAX, I want to do the same thing using regular form post request
$('#submit-form').click(function (event) {
event.preventDefault();
var btn = $(this);
var rules = builder.queryBuilder('getRules');
if (!$.isEmptyObject(rules)) {
$.ajax({
type: "POST",
url: url,
data: {Rules: rules}
});
}
});
How can I correctly send the rules object as an object not a string to the server using standard post request?
What is the problem in using Ajax?
You may consider doing the following:
$.ajax({
type: "POST",
url: url,
data: JSON.stringify({Rules: rules}),
dataType: "json",
contentType: "application/json",
success: function (json) {
}
[HTTPPost]
public void Rules(YourClass[] array){...}

Jquery serialize : trying to pass a form status to an ASP.NET MVC controller without submitting the form

Working on an ASP.NET MVC application.
A form has several buttons submitting the form.
One of the buttons needs to send to the controller the form's controls status without submitting the form.
I plan to use Ajax and $('#FormID').serialize();
I wrote it this way:
function rechercher() {
var formStatus = $('#FormID').serialize();
var url = '#Url.Action("Search", "ImproItemForm"); //?'+ formStatus;
// alert('formStatus: ' + formStatus); //works fine
alert('url: ' + url);
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data:/* { improItem: formStatus },*/ formStatus ,
contentType: "application/json; charset=utf-8",
success: function (result) {
alert("success" + result);
},
error: function (result) {
alert("failure" + result);
}
});
}
My controller action is as below:
public ActionResult Search(FormCollection improItem)
{
}
If I call ajax this way, it never reaches the controller (and thus triggers the error function.
If I comment this line:
data: formStatus ,
Then it does invoke the controller method but the FormCollection improItem argument has no values of course.
So I suppose that I am not passing the data correctly to Ajax but I do not manage to get this sorted.
thx in advance.
Make sure you specify the correct content type. Right now you seem to have specified application/json; charset=utf-8 but obviously you aren't sending any JSON but rather application/x-www-form-urlencoded which is how the .serialize() method will format the form values. So just get rid of this line:
contentType: "application/json; charset=utf-8",
Usually when you are unsure about what you are sending or receiving instead of trying to explicitly specify it like you did, you'd better don't specify anything and leave jQuery figure it out. The same stands true of course for the dataType: 'json', property. If your controller action doesn't return JSON, this will cause an error. If on the other hand you don't specify the expected return type, then jQuery will simply use the Content-Type response header that the server returned and it will figure it out.
So bottom line: leave it to the framework figure it out unless you know exactly what you are doing.
Ah, and before I forget, please replace this:
public ActionResult Search(FormCollection improItem)
with:
public ActionResult Search(MyViewModel improItem)

I don't understand why Redirect() is not working

I'm using GAE webapp2 I have a form that is validated using jquery, then the data is posted using jquery, and in the response of a valid date I'm trying to do a
self.redirect("/thankyou")
it doesn't work, however it actually shows in the terminal that the post method is done and the get method of class Thankyou is also done. the page never change.
can the query file block the response from the server? or am I doing something wrong?
the reason why I'm suspecting it has something to do with jquery, is because I have almost the same code on another form that is not validated using jquery and the redirect is working just fine.
here is my jquery code.
//validation code on multiple fileds
$("#booking_form").validate();
//adding rules to validation
$("#pax_name").rules("add", {
minlength: 2
});
$("#pax_mobile").rules("add", {
minlength: 10
});
return false;
});
$("#booking_form").validate({
debug: false,
submitHandler: function (form) {
// do other stuff for a valid form
$.post('/booking', $("#booking_form").serialize(), function (data) {
Recaptcha.reload();
});
}
});
Thank you.
You have to handle the redirect in your Javascript. I hope the following will solve your problem:
$("#booking_form").validate({
debug: false,
submitHandler: function (form) {
// do other stuff for a valid form
$.ajax({
type: "POST",
url: '/booking',
data: $("#booking_form").serialize(),
dataType: "json",
success: function(data) {
if (data.redirect) {
// You can here redirect the user to the new page
window.location.href = data.redirect;
}
}
});
}
});
Since you are firing an AJAX request to the server which will fire asynchronously, you cannot redirect from the server. You need to wait for the response and redirect on the client based on the response sent from the server.
Please look at this link which shows how to handle an ajax redirect from the server.
How to manage a redirect request after a jQuery Ajax call

Javascript Detect During Postback

I implemented a system on my ASP.NET Web Forms site for passing notifications to the client. The notifications can be validation messages, success messages, warnings, errors etc. These messages are generated by code on the server side and then retrieved from the server via script on the client side and displayed.
On each page of my site I have embedded a JavaScript function that calls a web service (on the server side) via jQuery AJAX and requests the latest notifications. If there are notifications, they are displayed using Noty. On the server side, messages that have been sent to the client are removed from the queue.
This works pretty well. However, let's say I'm on a page called NewEmployee.aspx and they create a new employee by filling out a new form, and this generates some kind of notification such as "New Employee Created With ID 58478" and also takes them to the ViewEmployee.aspx page. If the postback happens slowly enough, the message will start to display while the user is still on NewEmployee.aspx but before the user arrives at ViewEmployee.aspx. The end result is that the notification is only displayed for a split second and the user never sees it.
I need a way in JavaScript on the client side to detect if the page is performing a postback. If I have that, I can prevent it from calling the webservice during a postback and have it wait until it completes. I want it to look something like this.
setInterval(oneSecondFunction, 1000); //check for messages every 1 second
function oneSecondFunction()
{
var IsPostingBackRightNow=GetIsPostingBackStatus(); //I need your help writing this function
if(!IsPostingBackRightNow)
{
$.ajax({
type: 'POST',
url: 'myurl/MessageService.asmx/GetCurrentMessage',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ sessionid: sessionid, locale: 'en-US' }),
dataType: 'xml',
success: function (msg)
{
//show message via noty if there's a message
}
});
}
}
The post back is passing from the form, so you capture the onsubmit event on the form, and there you open your flag.
Here is how... add that on code behind
Page.Form.Attributes["onsubmit"] = "return GoForPostBack();";
to have this attribute also rendered on your form...
<form ... onsubmit="return GoForPostBack();">
and the javascript
var IsPostingBackRightNow = false;
function GoForPostBack()
{
IsPostingBackRightNow = true;
return true;
}
setInterval(oneSecondFunction, 1000); //check for messages every 1 second
function oneSecondFunction()
{
if(!IsPostingBackRightNow)
{
$.ajax({
type: 'POST',
url: 'myurl/MessageService.asmx/GetCurrentMessage',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ sessionid: sessionid, locale: 'en-US' }),
dataType: 'xml',
success: function (msg)
{
//show message via noty if there's a message
}
});
}
}

Categories

Resources