How to return a MVC View to a $.Ajax JSON POST - ajax

I am sending a $.Ajax POST to a MVC Controller function with parameters and returning a JasonResult successfully. What I need to happen is that the current View be returned (as if it was not a JSON request and I was returning the Viewdata). The Viewdata has been updated and the page needs to be redrawn.
In short, I want the MVC Action to respond back to the $Ajax request correctly, and then have the page redrawn using the updated Viewdata. Hope this makes sense, coming down with a bad cold.

Jason result, awesome.
It doesn't work like that i'm afriad, either you need to not use ajax, or you need to return data and handle it in jquery, or you need to return a partial view.
Partial view is probably the best solution, you can just return a chunk of html and stick it in ur site, very simple to use.

Related

Clarification needed in using Ajax forms and Partial Page

I am newbie to MVC and Web App.
Recently I have went through the article
http://www.c-sharpcorner.com/UploadFile/pmfawas/Asp-Net-mvc-how-to-post-a-collection/
It uses the Ajax Form, to do the partial update towards a particular region alone..
But I have a doubt in that example...
I have seen the partial Page inside the Div with Id "AllTweets"....
<div id="AllTweets">
#Html.Partial("_AllTweets", Model) ***** (XXX)
</div>
And also in the controller action,
try
{
viewModel.Tweets.Add(viewModel.Tweet);
return PartialView("_AllTweets", viewModel); **** (YYYYY)
}
Now my question is,
They are returning the partial view along with the data from the action in the controller.
Whatever the data returned from the controller, the engine will place that data, inside the target div with id "AllTweets"...
But still, why I have to have the statement, #Html.Partial("_AllTweets", Model) inside the Div, since already I am returning the data from the controller...
And also in some of the examples, i have seen the same kind of the code..
But, even if I have removed the code "#Html.Partial("_AllTweets", Model)" inside the div, the code still works fine, and without any problem and i can able to post the data to the action in the controller.
I got totally stuck at this point.
May I kindly know, what is the reason behind it and why so.... So I can understand it more better.
Thanks in advance...
But, even if I have removed the code #Html.Partial("_AllTweets",
Model) inside the div, the code still works fine, and without any
problem and i can able to post the data to the action in the
controller.
Yes it will work fine. The Html.Partial("_AllTweets",Model) renders the partial with the specified model on every page load. After page is loaded, then ajax is used to fill the div with id AllTweets.
Html.Partial("_AllTweets",Model) is usefull when you want to display, for example, already saved tweets from your database to user when the page first loads. And then ajax takes care of later updates.

How to update a view using Ajax in MVC3

I want to update my MVC3 view Using Ajax,
My Code is here Here
Please tell me how i'll add Ajax in my code to update a content of HTML table
The basic outline would be:
Client Side
Call a JavaScript function from your update button.
Within the JavaScript function, use jQuery to make an AJAX call to
an action method on the server.
On success, use the returned JSON to generate the updated HTML and update your containing div, probably using a jQuery selector and the html() method.
Server Side
Create an action method with a return type of JsonResult.
Retrieve whatever data it is you need from wherever.
Return the data using return Json(myData) (you may find it easier to use the JSON.NET Newtonsoft library to get more control over serialising your objects into JSON).
Have a Google into these various steps, completely overhaul your code and see how you get on.

Sinatra + Ajax to load dynamic content

I want to create a page with will be filled with dynamic info using Ajax (JQuery). The info will come from various GETs I need to do in other URLs.
I'll be using Sinatra + JQuery to to that, but as my WEB experience is almost null and don't have any idea how do to it right.
The requisites for this are:
Each time a GET completes, a new line of information should appear on the page.
If the GET could not be complete, a default info appear on the page.
My idea so far is to do something like this:
Have my controller performing each GET inside a thread.
Each time a thread ends, with success or not, I inform the view of the result and render a partial
I'll have as many partial as I need (for each GET I must do)
The first time I load the page I fill in the default info, them I update via AJAX with the successful GET responses
This does not seem the correct approach, so I'm asking someone that already did something similar or has more experience on this some help.
You start off with a simple get('/'){} route that holds the default message (or any other GET route). Then you have your other GET routes that you want to display on your default route. In Sinatra you can check whether a request is an xhr-request or not with a request.xhr? If you have an xhr request you return a json value to your view, otherwise reject the request or render a view with proper html. This is on your sinatra backend. In your views you can use JQuery or any other JS library or plain JS to handle asynchronous data requests. You can use the ajax function in JQuery to request data from your routes and then add them to your DOM. It's as simple as that :)
Now you will have to investigate on the JQuery site how to make ajax requests and how to append data to existing DOMs. That's all there is to it.

RedirectToAction MVC 3 after $.ajax call

From my view I am sending via $.ajax a JSON object to my controller to save it in the database.
If all succeeded i want to redirect to another action which will show a diferent view.
If i use this code:
return RedirectToAction("CreatePage", "Survey", new {id = question.PageId});
The execution goes to the Survey controller which returns a view but it is not shown.
I have read some post which said that it is not posible to redirect via ajax.
The solution I use so far is to redirect via javascript like this:
success: function (ret) {
window.location.href = "/Survey/CreatePage/" + $("#PageId").val();
}
Although this always works, sometimes i need to refresh the CreatePage view to show the last changes made.
Any idea of how to solve this problem better?
Thanks in advance
As mccow002 suggested, I wasn't really needing to make the call via AJAX for that part. After studying the solutions suggested, i realized that i could simple submit it in a form. My confusion came because I have a save and continue editing and a save. For the save and continue I use the AJAX call, but for the save option with the form being submitted is ok.
Thanks very much for your help.
Instead of redirecting to a new page, you can send a rendered html from .net code back to client and load that html in page, like this $("#main").load(renderedHtml).
But for refreshing the page you can write a simple script that run at specified intervals and refresh the page contens.
You could use [OutputCache] on the CreatePage action so that it doesn't cache the page or only caches for so long.
output caching

Codeigniter AJAX and POST

What is the best way to address an AJAX script that sends data to POST in codeigniter? Right now I am loading a view with the AJAX through $this->load->view('AJAX', $data); however there is no UI or user actions in the view. It's simply running through the script and returning POST data a little after the script loads. I receive the POST data in my model where I input the values into the DB and output some other values based on the data.
I need to open a real view, set metatags and re-direct the user to another website afterwards.
How do I address this?
The problem I'm facing is that I cannot open up another view because the AJAX view is the one that's in focus but I need this AJAX view to be temporary that basically does it's thing and sends to POST.
Is there any convention that I can lookup/research to what I'm describing? Let me know what kind of clarification is needed if any.
Some people like to write "ajax" controllers and post to them exclusively, but you don't need to do that. You can handle the request in the same controller that handles the non-ajax request. Personally, I exclusively return json, but you can return chunks of HTML if that works better for you.
Your exact problem is vague (actual code would help clarify), but I think you are on the wrong track. Don't use a view for processing anything ever. Use your Controller layer, this is for handling input and requests.
Example of controller method responding to either ajax or non-ajax request:
function edit_user()
{
$data['status'] = $this->user_model->save();
if ($this->input->is_ajax_request())
{
// return json string with our update status
// Something like: {"status":true}
echo json_encode($data);
exit;
}
// Load the non ajax view with the same data
$this->load->view('users/edit', $data)
}
$this->input->is_ajax_request() is a function of the Input class that reads $_SERVER['HTTP_X_REQUESTED_WITH'] and checks if it's value is XMLHttpRequest. This should only be true if it's an "ajax" request.
You can make life easier by wrapping this in a class or function. No matter what you decide to do, don't use the view layer for processing data.
I think my problem is, how do I address javascript without a view? how do I call the script and/or where do I put the JS code in the controller? I felt it was the wrong direction to address the code in a view but I didn't see how else to do it.
Whenever possible, you should put javascript code in a .js file and use a <script> tag to load it, in an HTML document. The only other exception is putting it in a "view" file (a file that's only purpose is to construct your final HTML output). In other words, follow the same rules of HTML as to where to put javascript, and follow the usual conventions of MVC of where HTML belongs (in the view). Javascript code does not belong in your controller. Javascript is not processing your data, it is sending the data to the server.
I need to open a real view, set metatags and re-direct the user to another website afterwards.
If you want to load a view, then redirect (after a certain amount of time I assume), you can do it with javascript or a <meta> tag (but don't use a meta tag, use js).

Resources