This is doubtless a newbie question but I cannot find one that's similar. I want to pass a model to an action through a JS function. I have the Ajax script:
var modelDataJSON = '#Html.Raw(Json.Encode(Model))';
$.ajax({
url: '#Url.Action("Action1", "Home")',
type: 'POST',
data: modelDataJSON,
dataType: 'json'
});
And I have for the action:
public ActionResult Action1(MyModel modelDataJSON)
{
return Content(modelDataJSON.ToString());
}
It's not doing anything. What have I missed? Again, sorry for the newbie question but I have already been stuck for too long on it.
Perhaps there's a misunderstanding. What I'm asking is how you redirect to the Action1 URL using a JS script. If it runs then it will display the content because it's a content action.
Don't use Ajax if you want to load a new page.
To make a POST request, you need to submit a form.
The best way to approach this is to use a plain, regular HTML form and not involve JS at all.
If you really want to involve JS then you can generate a form.
var f = document.createElement("form");
f.action = myURL;
f.method = "POST";
// append inputs to the form to pass the data in modelDataJSON here
document.body.appendChild(f);
f.submit();
Note that you can't send a JSON payload this way (but despite the variable name being modelDataJSON, your Ajax would have been sending standard form encoded data anyway).
Related
I was using antiforgerytoken within my razor view, and it was working fine. Then I moved the same code to AJAX, and it has started giving weird problems.
The AJAX POST request works fine, but the action SendData() which is called from the AJAX has a redirect to a different View (return View("Close");), which does not work anymore. It worked perfectly fine when the SendData() was called from the form directly.
Working code:
#using(Html.BeginForm("SendData", "Controller", FormMethod.Post)) {
#Html.AntiForgeryToken():
}
Not working code:
#using(Html.BeginForm("", "", FormMethod.Post, new
{
id = "__AjaxAntiForgeryForm"
}))
{
#Html.AntiForgeryToken()
}
JS File:
var form = $('#__AjaxAntiForgeryForm');
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
type: 'POST',
url: '/Controller/SendData',
data: {
__RequestVerificationToken: token
},
cache: false,
success: function(result) {}
});
The Action SendData() executes fine, but the redirect within this action doesn't work anymore.
I advise you use .serialize() instead of the following line.
var token = $('input[name="__RequestVerificationToken"]', form).val();
It is generic and thus will automatically adapt to any model changes.
For a working example of Antiforgery used alongside Ajax check this answer. The question was asked for MVC3 but it should work perfectly well as long as you're using an MVC version above 3.
The result param in the success: function (result) part of the ajax call will receive whatever was returned by your SendData action. If the SendData action uses a return View([...]); then you will probably get some html code in your result var. You could also return json data as follow return Json([...]).
If you actually want to have a redirect be made by the result of your Ajax call you should return the URL that you want to use as the redirection's target as follow return Content("http://target.url.for.redirect.com"); and then in your success callback, using the location.replace method, do this:
success: function(result)
{
document.location.replace(result);
}
This way the URL returned by the Ajax controller will be used to execute a redirection.
NOTE if you wish to ALWAYS redirect the user after the form is sent you should not use ajax at all ! A regular POST form would be far better suited for the job.
I figured out the problem, as per the comment from Stephen Muecke. The AJAX calls don't allow redirects, as the whole point behind AJAX is to stay on the same page and make a background JS call.
I am coding some basic crud application in Symfony2 where I want to implement some type of search function on a certain page.
The idea is that I want to launch a search query by entering something in an inputfield which is going to fire an ajaxcall (I could not think of anything better). The response of that ajaxcall has to be a kind of popup list with clickable items that is placed into another field on the initial page when clicking an item.
I have two questions:
Is there a better approach than ajax and how can I resolve the problem of the 'popup list' thing.
Second: I can make post ajaxcalls in Symfony2 with this kind of code:
var data = 'test';
$.ajax({
url: "{{ path('test_oost') }}",
data: { data: data },
method: "post",
success: function(data) {
//some things here
}
But I thought it is a bit strange to use post and I wanted to use get.. Apparently this is not working as I can not retrieve my data in the controller..
EDIT: I forgot to post my controller where I am handling the ajax call, here is the code:
public function testGetAction(Request $request)
{
$data = $request->request->get('data');
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('EuropsimProductBundle:SimProfile')->find($data);
return new Response($entity); }
This is working fine with method: "post", but failing when I try to use "get".
I also read about typeahead and this is really close to what I meant, the thing is I want a custom little popup or something because the ajax is supposed to return an array of objects with multiple attributes that has to be shown and where mulitple items are selectable. You can see it as two steps where you first launch the searchquery which bring you to a kind of popup or something where you can select the desired rows for further use on the page.
Thanks in advance!
Hicy
You have to use method $request->query:
For GET method:
$data = $request->query->get('data');
For POST method:
$data = $request->request->get('data');
This really is not much a Symfony2 related question... but...
This code is javascript, if you want to use GET just change method to GET,
var data = 'test';
$.ajax({
url: "{{ path('test_oost') }}",
data: { data: data },
method: "get",
success: function(data) {
//some things here
}
Then in Symfony create the route test_oostand do whatever you want on the controller to send "data" in the response.
Then on te success method process this data accordingly and create the needed view.
EDIT: Based on your new edit, you have an error accessing your data parameter, you should use query instead request
$data = $request->query->get('data');
In a Ruby on Rails application, I want to be able to place a User's username in a input text box, press an 'Add' button, and have them appear underneath with their details. Then, I can simply remove them from the list if I want using another button.
How does one connect Javascript and Rails database to complete such a task specifically with those buttons? While Javascript isn't a strength of mine, I'm more puzzled by how to extract and modify the Rails database using Javascript. For reference, I'm also using MongoDB.
What would be the best way to approach this?
Here is the jQuery and AJAX code that I'm using to 'POST' to the server endpoint 'admin/popular/users.json', but I'm not sure how to get Rails to create a new user in the database using my Popular::User model.
$(document).ready(function() {
$('.add-to-popular-users-button').click(function(event){
event.preventDefault();
var addToPopularUsersBtn = $(this);
var userToBeAdded = $('input[name=popular_user]').val();
var data = { 'popular_user': {'username': userToBeAdded, 'category': 'popular'} };
var url = "/admin/popular/users.json";
$.ajax({
url: url,
data: data,
dataType: 'json',
type: 'POST',
success: function(e) {
alert('Great success!');
}
});
});
});
Here's my Popular::User model:
class Popular::User
include Mongoid::Document
include Mongoid::Timestamps
POPULAR = 'popular'
field :category, default: POPULAR
index :user_id
belongs_to :user
validates_presence_of :user_id
validates_uniqueness_of :user_id
def self.popular
user_ids = self.where( :category => POPULAR ).map(&:id)
User.where(:_id.in => user_ids)
end
I am not familiar with rails framework, but you can do it using ajax. You can send an ajax post request to controller method which will creae a user, create a table row(or recreate the table), and returnd html place in table.
A simple example is:
$.ajax({
type:'post',
data:{} //user data,
dataType: 'json', //or any other
url: 'page_or_method', //page or method that will return html
success: function (data) {
$('div#userTable').html(data); //in case data contains the table
}
});
Read about $.ajax method (jQuery), or you can use XMLHttpRequest if you don't whant to use jQuery.
So, I was able to figure this out with a bit of testing. But, basically, you can either do this with AJAX/jQuery or with Rails inherent RESTful architecture, i.e., HTTP verbs like calling :delete, and associating it with a particular UI button.
One important idea that you should recognize with AJAX is that whatever data you send to the right server endpoint with a 'POST' or 'DELETE' verb or what have you, it will get picked up by the appropriate controller action. In other words, if I'm sending data via 'POST' to the '/popular/users.json' endpoint to create something, the def create method will be able to manipulate data afterwards. Then, you can assign the data to an ivar in the controller action to be interpreted and manipulated in the UI view corresponding to the controller action.
Here's the thing: I have an array which I must send to another page... not using an AJAX request. I'm trying to redirect my user to this new page, or maybe to open a popup with the new page, but this new page must receive the array data on a POST request.
How do I do this in javascript? I have no problem JSON encoding my array before sending it, I just don't know how to redirect my user to a new page with the data "attached", in javascript.
I'm using ExtJS4, so if there's anything on Ext.util, I have no problem using it.
Thanks.
You can do this (using javascript)
make a new FORM
set the action as the new page
set the method as POST
add a hidden field
set the value of the field to this Value you want to send
Pragmatically submit the form
You can Ajax POST to the target page's url:
Ext.Ajax.request({
url:'/target/url/', async:false, method:'POST',
jsonData: {
jsonArray: yourJsonArray
}
success: function() {
console.log('posted successfully');
}
});
async:false loses the asynchronous functionality; simply remove it if you don't need your POST to be synchronous.
All the examples of json I can find online only show how to submit json arrays w/ the jquery command $.ajax(). I'm submitting some data from a custom user control as a json array. I was wondering if it's possible to submit a json array as a regular post request to the server (like a normal form) so the browser renders the page returned.
Controller:
[JsonFilter(Param = "record", JsonDataType = typeof(TitleViewModel))]
public ActionResult SaveTitle(TitleViewModel record)
{
// save the title.
return RedirectToAction("Index", new { titleId = tid });
}
Javascript:
function SaveTitle() {
var titledata = GetData();
$.ajax({
url: "/Listing/SaveTitle",
type: "POST",
data: titledata,
contentType: "application/json; charset=utf-8",
});
}
Which is called from a save button. Everything works fine but the browser stays on the page after submitting. I was thinking of returning some kind of custom xml from the server and do javascript redirect but it seems like a very hacky way of doing things. Any help would be greatly appreciated.
This is an old question but this might be useful for anyone finding it --
You could return a JsonResult with your new titleId from the web page
public ActionResult SaveTitle(TitleViewModel record) {
string tId = //save the title
return Json(tId)
}
and then on your ajax request add a success function:
function SaveTitle() {
var titledata = GetData();
$.ajax({
url: "/Listing/SaveTitle",
type: "POST",
data: titledata,
contentType: "application/json; charset=utf-8",
success: function(data) { window.location = "/Listing/Index?titleId=" + data; }
});
}
That would redirect the page after a successful ajax request.
I just saw that you mentioned this at the end of your post but I think it is an easy and quick way of getting around the issue.
Phil Haack has a nice post discussing this scenario and shows the usage of a custom value provider instead of an action filter.
I don't understand why you would want to post Json if you're wanting to do a full page post. Why not just post normal form variables from the Html form element?