1

I've a quick question. To call an action through jQuery (to use AJAX), do i have to create a new Action returning json type or is there anyway to use the same action for http request (post) and jQuery too?

Thanks

2 Answers 2

4

It depends on what you want to do with the data returned.

Say, your actions returns Html, using jQuery, you can put the html returned from the server:

$.ajax('/url/', function(data){
    $('#elementID').html(data);
})

Alternatively, you can use the jQuery .load() method:

$('#elementID').load('/url');

If your action returns a redirect, and you want the client page to redirect to a url, then yes, you need to create a new action that will return Json:

public JsonResult SomeAction()
{
    return Json(new {redirect = true, url = "/Path/ToRedirect"});
}

And using jQuery:

$.ajax('/url/', function(data){
    if(data.redirect) {
        window.location = data.url;
    };
})
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the same action:

$.post(
    '/controller/action', 
    { field_a: "Value a", field_b: "Value b" }, 
    function(data) {
        $('#result').html(data);
    }
);

With ajax, you usually want partial views or json as a return value. With regular post, full html page. Why do you want to use the same action in ajax and regular post?

2 Comments

Thanks. I'm now using the Request.IsIsAjaxRequest()) to see if i return a View or other values.
Because i just need to return a string, and i want to first call it from javascript. If javascript is disabled, then i use the form.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.