jQuery AJAX form how to get data - asp.net-mvc-3

I have a form in my ASP.NET MVC 3 application that will use jquery to send it's data to the controller action instead of doing a normal postback:
$('.AjaxForm').live("submit", function (event) {
event.preventDefault();
$.validator.unobtrusive.parseDynamicContent('.uiModalContent input');
console.log($(this).attr('action'));
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: data,
success: function (responseHtml) {
alert(responseHtml);
},
error: function (responseHtml) {
alert('error');
},
statusCode:
{
404: function (responseHtml) {
alert('404');
},
500: function (responseHtml) {
alert('500');
}
}
});
});
However I get an error saying data is undefined... How do I get the data from the form and send it? Also does the built-in validation in ASP.NET MVC 3 work with my code or will I have issues? Thanks

You should use form.serialize() to make data value. Your code should be changed to:
url: $(this).attr('action'),
data: $('.AjaxForm').serialize(),

you can use the serialize or serializeArray method with form to pass all parameters with the ajax call.
data: $('.AjaxForm').serialize(),
http://api.jquery.com/serialize/
http://api.jquery.com/serializeArray/

Related

Why i can not call action method with ajax?

I'm new in asp.net mvc want to call action method in the view page,for that purpose write this ajax code:
$('#SaveBTN').click(function (e) {
$.ajax({
url: "/Home/SaveRecord",
type: "POST",
data:'', //JSON.stringify({ 'Options': someData }),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Done");
},
error: function () {
alert("An error has occured!!!");
}
});
});
this is my button:
ثبت نام
and this is my action:
[HttpPost]
public ActionResult SaveRecord()
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
but when run the web application and fire button,get error segment alert in ajax ,How can i solve that problem?thanks all.
With the question and code presented in the way it is there is no way to help. I recommend starting from ground zero and stepping through this tutorial.
Basically that^ link will get you through the basics of using web api in MVC to do AJAX calls and populate the page. There are some other methods however this is the best place for trying to learn what you're studying.

can't get to web api controller action with jquery ajax post

I'm trying to create my first REST application with the web api in mvc4. I have a controller set up with the HttpPost verb but for some reason when I click the link to post the xml string to the controller I get an error - "{"Message":"No HTTP resource was found that matches the request URI '/api/Apply/ApplyToJob'.","MessageDetail":"No action was found on the controller 'Apply' that matches the request."}" Any ideas what I might be doing wrong? Here's the view page...
Post Data
<script type="text/javascript">
window.onload = function () {
$("#lnkPost").on("click", function () {
$.get("/TestResponse.xml", function (d) {
$.ajax({
//contentType: "text/xml",
//dataType: "xml",
type: "post",
url: "/api/Apply/ApplyToJob",
data: {
"strXml": (new XMLSerializer()).serializeToString(d)
},
success: function () { console.log('success'); }
});
});
});
};
</script>
and here's the controller.
public class ApplyController : ApiController
{
[HttpPost]
[ActionName("ApplyToJob")]
public string ApplyToJob(string strXml)
{
return "success";
}
}
Modify your action's parameter like below:
public string ApplyToJob([FromBody]string strXml)
This is because without this FromBody attribute, the string parameter is expected to come from the Uri. Since you do not have it in the Uri the action selection is failing.
Also, looking at your client code, shouldn't you set the appropriate content type header in your request?
Edited:
You can modify your javascript to like below and see if it works:
$.ajax({ contentType: "text/xml",
dataType: "xml",
type: "post",
url: "/api/values",
data: "your raw xml data here",
success: function () { console.log('success'); }
});

Retrieve post value in the controller sent by ajax call

I am unable to retrieve value sent as a post through ajax call in cake php controller file
$.ajax({
type: "POST",
url: "share",
data: country,
dataType: "json",
success: function (response) {
if (response.success) {
// Success!
} else {
console.log(response.data, response.code);
}
}
});
I have tried with the below ways of retrieving the data sent in the above code through POST. But none of them worked.
$this->params
$this->data
$_POST[]
$this->request
The url points to the function in the controller page.
Please can any of you let me know how the value can be retrieved.
When submitting data via ajax and you want cake to pick it up in the usual way just use $('whatever').serialize().
if you don't have an actual form to serialize you can fake it by submitting the data as follows:
$.ajax({
...
data: {
data: country
},
...
});
Note how cake generates fields like data[Model][field]. you don't need the Model part but the data part is important.

Rendering a simple ASP.NET MVC PartialView using JQuery Ajax Post call

I have the following code in my MVC controller:
[HttpPost]
public PartialViewResult GetPartialDiv(int id /* drop down value */)
{
PartyInvites.Models.GuestResponse guestResponse = new PartyInvites.Models.GuestResponse();
guestResponse.Name = "this was generated from this ddl id:";
return PartialView("MyPartialView", guestResponse);
}
Then this in my javascript at the top of my view:
$(document).ready(function () {
$(".SelectedCustomer").change( function (event) {
$.ajax({
url: "#Url.Action("GetPartialDiv/")" + $(this).val(),
data: { id : $(this).val() /* add other additional parameters */ },
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
SetData(data);
}
});
});
function SetData(data)
{
$("#divPartialView").html( data ); // HTML DOM replace
}
});
Then finally my html:
<div id="divPartialView">
#Html.Partial("~/Views/MyPartialView.cshtml", Model)
</div>
Essentially when a my dropdown tag (which has a class called SelectedCustomer) has an onchange fired it should fire the post call. Which it does and I can debug into my controller and it even goes back successfully passes back the PartialViewResult but then the success SetData() function doesnt get called and instead I get a 500 internal server error as below on Google CHromes console:
POST http:// localhost:45108/Home/GetPartialDiv/1 500 (Internal Server
Error) jquery-1.9.1.min.js:5 b.ajaxTransport.send
jquery-1.9.1.min.js:5 b.extend.ajax jquery-1.9.1.min.js:5 (anonymous
function) 5:25 b.event.dispatch jquery-1.9.1.min.js:3
b.event.add.v.handle jquery-1.9.1.min.js:3
Any ideas what I'm doing wrong? I've googled this one to death!
this line is not true: url: "#Url.Action("GetPartialDiv/")" + $(this).val(),
$.ajax data attribute is already included route value. So just define url in url attribute. write route value in data attribute.
$(".SelectedCustomer").change( function (event) {
$.ajax({
url: '#Url.Action("GetPartialDiv", "Home")',
data: { id : $(this).val() /* add other additional parameters */ },
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
SetData(data);
}
});
});

jQuery Ajax request in Grails

How to use jQuery to make Ajax request in Grails pages?
How to setup a URL hitting a method on Grails Controller? Let's say controller:'airport', action:'getJson' and input to the action is 'iata'.
I am able to set static url as http://localhost:8080/trip/airport/getJson but not able to figure out how to pass input for iata specifically.
I am fairly new to Grails and following IBM's 'Mastering the Grails' tutorial series. Do suggest me some good tutorial on using jQuery with Grails.
use the $.ajax method in jquery
$.ajax({
url:"${g.createLink(controller:'airport',action:'getJson')}",
dataType: 'json',
data: {
iata: '.............',
},
success: function(data) {
alert(data)
},
error: function(request, status, error) {
alert(error)
},
complete: function() {
}
});
It's:
$.ajax({
url: '/trip/airport/getJson',
data: {paramName: 'iata'}
});
use your parameter name, that you're expecting in action, intead of paramName, that i've used.

Resources