I'm trying to send part of a model through an ajax call, but doing it simply like my code below, doesn't work. How could I pass this object along?
$.ajax({
url: "/Controller/Action",
type: "GET",
data: #Model.Company,
success: function (result) {
$('#myDiv').html(data);
}
});
This is what my JS puts outs:
MyProj.Domain.Entities.Company
This is my error:
Uncaught ReferenceError: MyProj is not defined
Your syntax would work fine for a primitive variable, but you should serialize your object to Json before sending. And also make sure that script stays in cshtml or aspx page, else '#Html' helper will not work.
$.ajax({
url: "/Controller/Action",
type: "GET",
data: #Html.Raw(Json.Encode(Model.Company)),
success: function (result) {
$('#myDiv').html(data);
}
});
Related
I have tried to use AJAX call in an MVC5 project as many similar examples on the web, but every time there is an error i.e. antiforgerytoken, 500, etc. I am looking at a proper AJAX call method with Controller Action method that has all the necessary properties and sending model data from View to Controller Action. Here are the methods I used:
View:
#using (Html.BeginForm("Insert", "Account", FormMethod.Post, new { id = "frmRegister" }))
{
#Html.AntiForgeryToken()
//code omitted for brevity
}
<script>
AddAntiForgeryToken = function (data) {
data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();
return data;
};
$('form').submit(function (event) {
event.preventDefault();
//var formdata = JSON.stringify(#Model); //NOT WORKING???
var formdata = new FormData($('#frmRegister').get(0));
//var token = $('[name=__RequestVerificationToken]').val(); //I also tried to use this instead of "AddAntiForgeryToken" method but I encounter another error
$.ajax({
type: "POST",
url: "/Account/Insert",
data: AddAntiForgeryToken({ model: formdata }),
//data: { data: formdata, __RequestVerificationToken: token },
//contentType: "application/json",
processData: false,
contentType: false,
datatype: "json",
success: function (data) {
$('#result').html(data);
}
});
});
</script>
Controller: Code cannot hit to this Action method due to antiforgerytoken or similar problem.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public JsonResult Insert(RegisterViewModel model)
{
try
{
//...
//code omitted for brevity
}
}
I just need a proper AJAX and Action methods that can be used for CRUD operations in MVC5. Any help would be appreciated.
UPDATE: Here is some points about which I need to be clarified:
1) We did not use "__RequestVerificationToken" and I am not sure if we send it to the Controller properly (it seems to be as cookie in the Request Headers of Firebug, but I am not sure if it is OK or not). Any idea?
2) Should I use var formdata = new FormData($('#frmRegister').get(0)); when I upload files?
3) Why do I have to avoid using processData and contentType in this scenario?
4) Is the Controller method and error part of the AJAX method are OK? Or is there any missing or extra part there?
If the model in your view is RegisterViewModel and you have generated the form controls correctly using the strongly typed HtmlHelper methods, then using either new FormData($('#frmRegister').get(0)) or $('#frmRegister').serialize() will correctly send the values of all form controls within the <form> tags, including the token, and it is not necessary to add the token again.
If your form does not include a file input, then the code should be
$('form').submit(function (event) {
event.preventDefault();
var formData = $('#frmRegister').serialize();
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "Account")', // do not hard code your url's
data: formData,
datatype: "json", // refer notes below
success: function (data) {
$('#result').html(data);
}
});
});
or more simply
$.post('#Url.Action("Insert", "Account")', $('#frmRegister').serialize(), function(data) {
$('#result').html(data);
});
If you are uploading files, then you need you need to use FormData and the code needs to be (refer also this answer and
$('form').submit(function (event) {
event.preventDefault();
var formData = new FormData($('#frmRegister').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "Account")',
data: formData,
processData: false,
contentType: false,
datatype: "json", // refer notes below
success: function (data) {
$('#result').html(data);
}
});
});
Note that you must set both processData and contentType to false when using jQuery with FormData.
If you getting a 500(Internal Server Error), it almost always means that your controller method is throwing an exception. In your case, I suspect this is because your method is returning a partial view (as suggested by the $('#result').html(data); line of code in you success callback) but you have specified that the return type should be json (your use of the datatype: "json", option). Note that it is not necessary to specify the dataType option (the .ajax() method will work it out if its not specified)
If that is not the cause of the 500(Internal Server Error), then you need to debug your code to determine what is causing the expection. You can use your browser developer tools to assist that process. Open the Network tab, run the function, (the name of the function will be highlighted), click on it, and then inspect the Response. It will include the details of the expection that was thrown.
contentType should be application/x-www-form-urlencoded
Try this code
<script>
$('form').submit(function (event) {
event.preventDefault();
$.ajax({
method: "POST",
url: "/Account/Insert",
data: $(this).serialize(),
contentType:"application/x-www-form-urlencoded",
success: function (data) {
$('#result').html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
});
</script>
I can't find what the error is in an AJAX call.
I have a PHP file output:
[{"value":"123","name":"My Name"}]
and this output is correct. And my AJAX call returns undefined after success:
$.ajax({
type: "POST",
url: "correct_file_location.php",
data: $(this.form).serialize(),
dataType: "json",
success: function (pk) {
alert(pk.value);
$("#label_id_name").text(pk.value);
},
error: function (){
alert("error");
}
});
Since the result is an array of objects, you need to first get the object from the array, and then access the properties of that object.
pk[0].value
should work.
*It is showing undefined because you are getting an array of objects and not only object *
try what #freedomn-m suggested in the comments
Try below code it will be work.
$.ajax({
type: "POST",
url: "correct_file_location.php",
//data: $(this.form).serialize(),
dataType: "json",
success: function (pk) {
var data1 = JSON.parse(pk[0].value);
console.log(data1);
// $("#label_id_name").text(pk.value);
},
error: function (){
alert("error");
}
}) ;
Your code will also work but your php response code must be in javascript object.
Please add below code in 'correct_file_location.php' and check with your ajax code.
'{"value":"123","name":"My Name"}';
this is javascript code to create json variable and i am not able to get how to acess >this json variable at servlet end.
<script>
function()
{ alert("sending");
var Jsonobj=JSON.stringify(folderarray);
alert(Jsonobj);
$.ajax({ url: '/Chandrayan-2014/src/Handler/FolderHandler.java'+param,
type: 'POST',
dataType: 'json',
success: function(result) {
alert('SUCCESS'); } });
alert("sent");
}
May i suggest you to use console.log instead of alert?
also, like cloudwalker said, i see your ajax call is missing the data property
var Jsonobj=JSON.stringify(folderarray);
console.log(Jsonobj);
$.ajax({
'type' : 'POST',
'url' : '/route/to/my/handler',
'data' : Jsonobj,
'success' : function () { console.log('succeed with args %o', arguments); },
'error' : function () { console.log('failed with args %o', arguments); }
});
Note that the dataType property is used to specified the type of data that you're expecting back from the server. Not the type of data you're submiting
I don't see where you're actually passing the jsonobj as a parameter. You'd maybe want something like:
$.ajax({ url: '/myUrl',
type: 'POST',
dataType: 'json',
data: {myJsonObj: Jsonobj} --PASS THE OBJECT HERE
success: function(result) {
alert('SUCCESS'); } });
alert("sent");
I'm also a little confused about your url. Are you trying to link directly to a java source file, or did you just set up a servlet mapping that has .java at the end?
I have an ajax POST that sends data to a controller function and that function returns a string array back to the ajax call as the default 1st parameter in the ajax success method. When I tried to use the returned data, it won't let me print the 1st element to an alert box. How come?
i.e.
$.ajax(
{
type: "POST",
url: "../Home/stringSplitFunct",
data: { 'parameter1': Input },
success: function (response)
{
alert(response[0]);
}
});
In fact, I don't think it even recognize it as a string array.
You need to specify dataType. Read more here.
$.ajax({
type: "POST",
url: "../Home/stringSplitFunct",
data: { 'parameter1': Input },
dataType: 'json',
success: function (response)
{
alert(response[0]);
}
});
Looks like the data is being returned as a raw sting.
Use dataType property for your ajax request
dataType: 'json'
Also avoid using alert as it stops the execution flow. Use console.log instead
ok i'm that far:
app.get('/mypartial', function (req. res) {
res.render('mypartial', {layout: false, data: data});
});
this renders out my jade with the data and sends it as html to the client
now i need to fetch this via js and to render it out using
$('#idofparentelementofyourpartial').html(responseHTML);
so i would need something like:
//// Pseudocode
var locat = window.location.pathname;
on locat change{
prevent default // because i want to use the ajax call (not standart browser call)
ajax({
url: locat,
type: "GET",
dataType: "json",
success: $('#idofparentelementofyourpartial').html(data);
});
}
the strange thing is that "layout: false" still trys to render something: i would expect that it just puts stuff into the dom
You may have a look at jQuery load() to load partial html into a defined container.
ajax({
url: locat,
type: "GET",
dataType: "json",
success: $('#idofparentelementofyourpartial').html(data);
});
Datatype JSON is not what you want.