The code below is working for me, but I'm trying to find a way to read all values from the form instead of having to re-create the view model in JavaScript (vm is the name of the parameter of the object).
I tried to serialize the form and pass it in, but maybe my syntax is incorrect.
Any suggestions?
$.ajax({
type: "POST",
dataType: "json",
url: "/post-details-save",
data: addAntiForgeryToken({
vm: ({
Id: $("#PostImageDetails_Id").val(),
Title: $("#PostImageDetails_Title").val(),
Description: $("#PostImageDetails_Description").val(),
CopyrightOwner: $("#PostImageDetails_CopyrightOwner").val(),
CopyrightUrl: $("#PostImageDetails_CopyrightUrl").val(),
SourceName: $("#PostImageDetails_SourceName").val(),
SourceUrl: $("#PostImageDetails_SourceUrl").val(),
SourceLicenseType: $("#PostImageDetails_SourceLicenseType").val()
})
}),
success: postDetailsSaveSuccess,
error: postDetailsSaveError
});
Confirm Form Setup
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { #id = "formID" }))
I have done similar stuff with submitting forms in partial views.
Basically, you need to confirm that your html form is set up correctly:
The AntiForgeryToken
#Html.AntiForgeryToken()
Data Fields
Could look something like the following with the name attribute being important.
<input type="hidden" name="ApproveUserID" id="ApproveUserID" value="#Model.ApproveUserID" />
AJAX The Form
If your form is set up correctly like explained above, you will be able to submit the data via AJAX with something similar to the JS below.
var form = $("#formID");
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(), // data to be submitted
success: function (response) {
if (response == "Success") {
//DO SUCCESS STUFF
} else
{
//DO FAILURE STUFF
}
},
error: function () {
//DO ERROR STUFF
}
});
Pro Tip:
You can always expand the data you send by placing
var formData = form.serialize();
Into a variable and expanding it from there.
Good Luck.
Related
I need a way to generate a new unique id for a user when a person focuses out of a textbox. I am using MVC 5 for this application. Here is my controller, everything in the controller has been unit tested and it does return the string value that I need.
Controller. I was able to visit that URL, and I did download a JSON file with the correct data.
public ActionResult GetNewId()
{
string newId = utils.newEmployeeId();
return Json(new {eId = newId}, JsonRequestBehavior.AllowGet);
}
Javascript, JQuery call to that controller. I do not know how to properly reference the ActionResult. I keep getting undefined errors on eId.
$(function () {
$('#employeeId').focusout(function () {
if($("#employeeId").val() === "NP")
$.ajax({
type: 'GET',
url: '#Html.ActionLink("GetNewId", "Employees")',
data: { 'eId': eId },
dataType: 'json',
success: function (response) {
$("#employeeId").val(eId);
},
error: function (response) {
alert(response);
}
});
});
});
The problem is with yout ajax request:
1.you need to change the url in the reuqest but it like this
{{yourcontroller}/GetNewId}
2.remove the "data: { 'eId': eId }" you dont need it, youre not posting anything to the server.
change your $("#employeeId").val(eId); to
$("#employeeId").val(response.eId);
this will 100% work
When an POST is made to the controller, the controller responds with exactly what I want the browser to render. But the browser does not render the response. I've verified the response is good in Fiddler.
The code below shows what I think is relavent code. The controller action method that returns the response, part of the template that has the mvc helper code, javascript/jquery code that fires the ajax call with the form inputs.
I want to use the FormCollection. Why doesn't the browser render the response and what can I do to fix it?
BoMController
public ActionResult GetBillOfMaterialsView(FormCollection frmColl){
// snipped out model interaction
return PartialView("~/Views/Project/Index.cshtml", project);
}
Index.cshtml
#using (Html.BeginForm("GetBillOfMaterialsView", "BoM", FormMethod.Post, new {id = "frmGetBom"})) {
// selProj input select code removed for brevity
}
function submitGetBoM() {
var frmGetBom = $('#frmGetBom');
$.ajax({
type: 'POST',
url: frmGetBom.attr('action'),
data: frmGetBom.serialize()
});
}
$(document).ready(function() {
$('#selProj').selectmenu( {
select: function(){submitGetBoM()}
}).addClass("overflow");
});
Invoking $.ajax alone doesn't append the response from the server to the document, you have to use the success callback to manually fetch the response and append it.
For example:
$.ajax({
type: 'POST',
url: frmGetBom.attr('action'),
data: frmGetBom.serialize(),
success: function(response) {
$('#someContainerId').html(response);
}
});
Alternatively, use load() that is a shorthand to the above:
$('#someContainerId').load(frmGetBom.attr('action'), frmGetBom.serializeArray());
See Documentation
Your client code doesn't do anything with the returned values from the server:
function submitGetBoM() {
var frmGetBom = $('#frmGetBom');
$.ajax({
type: 'POST',
url: frmGetBom.attr('action'),
data: frmGetBom.serialize(),
success: function() { alert('ok'); }
});
}
This would popup an alert on success.
I am working with mvc4 application. I developed a form using .cshtml file, which inherits the model and has its corresponding controller action.
I am submitting the form using a ajax jquery like,
var body=$('#formId').serialize();
$.ajax({
url: submitAction,
type: "POST",
datatype: "json",
data: body,
success: function (data) {
if (data != null) {
alert("success");
}
});
"body" is fine and it has serialized data and the submitAction is the var which holds my controller action and the controll is transfered there.
EDIT:
My controller looks like,
public JsonResult(ParentModel model) /*here model always hold null values, WHY??*/
{
//stmts..
return Json(new {success=true}, JsonRequestBehaviour.AllowGet);
}
But, there the parameter of my controller action is showing null values. Can someone tell what could be the mistake and how can I resolve it?
$.ajax({
url: submitAction,
type: "POST", <-- you make post, but asp.net mvc controller receives default GET request
data: { model: body},
[HttpPost]
public JsonResult(string model) //<--now you pass string and to Deserialize in ParentModel
{
JavaScriptSerializer jss= new JavaScriptSerializer();
ParentModel pmodel = jss.Deserialize<ParentModel >(model);
return Json(new {success=true}, JsonRequestBehaviour.AllowGet);
}
Try edit data: section in you request,
remove datatype: "json"
And edit type model parameter to string
I have an MVC application with a controller named Angular (I use AngularJS as well), which has an action called GetQuestion. That action returns a JsonResult which looks like this (grabbed from Chrome):
{"game":{"Title":"Diablo III","ImgPaths":["d31.jpg","d32.jpg"]},"Answers":["Diablo III","World of Tanks","Need for Speed"]}
My JS function is like this:
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { alert(data); })
});
But instead of the Json I wrote above, alert window only says [object Object]
Update
Ok, that was fixed, thaks. However as you may suspect, my goal is not to present this data in alert box, but use it somehow. So here's my controller in Angular
function QuestionCtrl($scope) {
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: function (data) {
$scope.answers = JSON.stringify(data.Answers);
$scope.imgPath = JSON.stringify(data.game.ImgPaths[0]);
}
});
}
And then the view:
<div ng-controller="QuestionCtrl">
<img class="quizImage" src="~/Gallery/{{imgPath}}"/>
#using (Html.BeginForm("Answer", "Angular", FormMethod.Post))
{
<p ng-repeat="answer in answers"><input type="radio" name="game" value="{{answer}}"/> {{answer}}</p>
<p><input type="submit" value="Answer"/></p>
}
</div>
And I don't have neither image or the questions. If I hardcode them in controller then it's ok.
An alert will show that, i would suggest using console.log(data)
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { console.log(data); })
});
or as the comments states:
var request = $.ajax({
url: "/Angular/GetQuestion",
dataType: "json",
type: "post",
success: (function (data) { alert(JSON.stringify(data)); })
});
I resolved my second problem like this:
function QuestionCtrl($scope, $http) {
$http.post('/Angular/GetQuestion',null).success(function(data) {
$scope.answers = data.Answers;
$scope.imgPath = data.game.ImgPaths[0];
//console.log($scope.answers);
//console.log($scope.imgPath);
});
}
Note that it's AngularJS.
The reason it's happening is because JSON is an Object in JavaScript. When you type
alert(data);
It will attempt to cast the object to a string which in this case will only output that fact that it's an Object.
To view the contents of an object you can write a simple function to use with an alert or console.log.
function outputProperties(anObject) {
var props = '';
for (var prop in anObject) {
props += '\n' + prop + ' value: ' + anObject[prop];
}
return props;
}
And use it like this
alert(outputProperties(data));
For starters... when ever you are dynamically building the src url for an image (using the {{expression}} syntax from Angular) you need to not use the "src" attribute and use the "ng-src" angular directive. It allows angular time to process your url before the image is loaded.
I´m building a social network with Grails and got stucked
on giving users inner their editprofile
page the chance to paste an youtube-Url into a textfield and by clicking a button a JS regexxes the id out of the URL pasted, an ajax post is fired updating a div with a preview image of the youtube video
the html looks like :
<g:textField name="videoinput" class="videoinput reLef" value="" />
<span class="daten_videouploadbtn reLef" ></span>
<g:render template="/forms/storedVideos" />
the JS looks like :
$('.daten_videouploadbtn').click(function() {
var string = document.editProfileForm.videoinput.value;
var neu = string.replace(/http[s]?:\/\/(?:[^\.]+\.)*(?:youtube\.com\/(?:v\/|watch\?(?:.*?\&)?v=|embed\/)|youtu.be\/)([\w\-\_]+)/i, '$1');
var id = RegExp.$1;
jQuery.ajax({
type:'POST',
data:RegExp.$1,
url:'${createLink(action: 'addVideo')}',
success:function(data,textStatus){jQuery('#storedvideos').html(data);},
error:function(XMLHttpRequest,textStatus,errorThrown){}
});
});
the controller looks like :
def addVideo() {
def videoitems = !!%%-- HOW TO PARSE YOUTUBE-ID HERE -%%!!
render(template:"/forms/storedVideos", model: [newVideo:videoitems])
}
and stored videos looks :
<div id="storedvideos"><span><img src="http://img.youtube.com/vi/${newVideo}/default.jpg" width="225px" height="130px"/></span></div>
i just dont get it how to catch the data of the Ajax Post and update the div with the preview image with the id inside,
can someone give a hint ? it is killing me
You should post the data like this:
jQuery.ajax({
type: 'POST',
data: { value: RegExp.$1 },
...
After that you can access the posted data inside your grails controller with params.value.
I got this working on Grails 2.0.4:
Javascript/Ajax
var data =
{requestId: 12456,
node: "node1",
host: "mynode.com"};
$.ajax({
url: '/myurl',
data: JSON.stringify(data),
type: 'post',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function() ...
},
error: function() ...
}
});
In Grails....
def service(){
def jsonObj = request.JSON
}
I like this approach because request.JSON parses the data and returns a ready to use object.