I am working with Jquery AJAX Call in MVC Application. My view looks like this :
<p>
Name #Html.TextBox("Name")
Date #Html.TextBox("Date")
<input type="submit" id="SubmitName" value="Submit" />
</p>
My AJAX call is as follows :
<script type="text/javascript">
function send() {
var Details = JSON.stringify({
StudentName: $("#Name").val(),
DateofJoining: $("#Date").val()
});
$('#target').html('sending..');
$("SubmitName").click(function () {
$.ajax({
url: "/DQR/Details",
type: "POST",
dataType: "json",
contentType: "application/json",
data : Details ,
success: function (data) {
$('#target').html(data.msg);
},
});
})
}
</script>
And my controller looks like this :
[HttpPost]
public ActionResult Details (string StudentName, string DateofJoining)
{
var result = (from dc in _db.Details
where dc.Name== StudentName
select dc.Address);
return Json(result, JsonRequestBehavior.AllowGet);
}
I don't know what I'm missing. The ajax request is not working. Could anyone help me with this ?
Imagining that ur controller name is DQR then you need to write as below:-
$.ajax({
url: "/DQR/Details",
type: "POST",
dataType: "json",
contentType: "application/json",
data : Details ,
success: function (data) {
$('#target').html(data.msg);
},
});
and id should be:-
$("#SubmitName").click(function () {
var Details = JSON.stringify({
StudentName: $("#Name").val(),
DateofJoining: $("#Date").val()
});
$('#target').html('sending..');
//// your ajax call
}});
and what is Send()? i mean the click event should be under $(document).ready(function() {});
I would suggest take simple button rather than "submit" if you are playing client side with that.
Bind click handler properly, move Details object creation in click handler
$(function() {
$("#SubmitName").click(function () {
var Details = JSON.stringify({
StudentName: $("#Name").val(),
DateofJoining: $("#Date").val()
});
$('#target').html('sending..');
$.ajax({
url: "/DQR/Details",
type: "POST",
dataType: "json",
contentType: "application/json",
data : Details ,
success: function (data) {
$('#target').html(data.msg);
}
});
});
});
You can use jQuery $.post method as well.
Here is an example.
var StudentName = $("#Name").val();
var DateofJoining = $("#Date").val();
$.post('/Controller/Action', { 'StudentName': StudentName , 'DateofJoining': DateofJoining }, function(data) {
$('#target').html(data.msg);
}, 'json');
Here is more information about $.post
Related
I'm a newbie working with ajax. I have a problem while sending the data into ajax post.
The output of console.log(obj.Id) and console.log(oke) is 2. Then I tried to send it through data in ajax, but it end up 0 in the controller.
$(function () {
$("body").on('click', '#btnEdit', function () {
alert("clicked ok");
$("#addRowModal").modal("hide");
var obj = {};
obj.Id = $(this).attr('data-id');
oke = $(this).data("id");
console.log(obj.Id)
console.log(oke)
$.ajax({
url: '#Url.Action("Details", "InvoicePPh")',
data: oke,
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("sukses");
},
error: function(response) {
alert("error")
}
});
});
});
And my controller looks like this
[HttpPost]
public JsonResult Details(int id)
{
var obj = dbContext.invoicePPhs.FirstOrDefault(s => s.Id == id);
InvoicePPh pph = new InvoicePPh();
pph2326.TaxForm = obj.TaxForm;
return Json(pph);
}
I want the '2' value that passes into my controller, how can I do that? Thank you for your help.
An alternative way to send your data your Controller method using Ajax would be to wrap your data in a JSON object and then send it to the server for processing. The server will be then deserialize your JSON object and you can access the required properties from that process:
$(function () {
$("body").on('click', '#btnEdit', function () {
alert("clicked ok");
$("#addRowModal").modal("hide");
var obj = {};
obj.Id = $(this).attr('data-id');
oke = $(this).data("id");
console.log(obj.Id)
console.log(oke)
var json = {
oke: oke
};
$.ajax({
url: '#Url.Action("Details", "InvoicePPh")',
data: {'json': JSON.stringify(json)},
type: 'POST',
dataType: "json",
success: function (response) {
alert("sukses");
},
error: function(response) {
alert("error")
}
});
});
});
And your Controller method will be:
using System.Web.Script.Serialization;
[HttpPost]
public JsonResult Details(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
var id= Convert.Int32(jsondata["id"]);
var obj = dbContext.invoicePPhs.FirstOrDefault(s => s.Id == id);
InvoicePPh pph = new InvoicePPh();
pph2326.TaxForm = obj.TaxForm;
return Json(pph);
}
If you just need id in your method parameter just change data in ajax to:
contentType: "application/x-www-form-urlencoded",
data: { 'id': oke },
id is name of parameter from controller method.
Please change the data property in ajax part.
$.ajax({
url: '#Url.Action("Details", "InvoicePPh")',
data: { 'id': oke },
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("sukses");
},
error: function(response) {
alert("error")
}
});
The web service on http://localhost:57501/api/addDatabase has the following code.
[System.Web.Mvc.HttpPost]
public ActionResult Post(addDatabase pNuevaConeccion)
{
pNuevaConeccion.insertarMetaData();
return null;
}
The Ajax function is on a javascript that creates the JSON from the give values on http://localhost:1161/CreateServer.
$(document).ready(function ()
{
$("#createServer").click(function (e) {
e.preventDefault(); //Prevent the normal submission action
var frm = $("#CreateServerID");
var dataa = JSON.stringify(frm.serializeJSON());
console.log(dataa);
$.ajax({
type: 'POST',
url: 'http://localhost:57501/api/addDatabase/',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
//ContentLength: dataa.length,
data: dataa,
datatype: 'json',
error: function (response)
{
alert(response.responseText);
},
success: function (response)
{
alert(response);
if (response == "Database successfully connected") {
var pagina = "/CreateServer"
location.href = pagina
}
}
});
});
});
When I run this code an alert pops up saying "undefined" but if I delete the contentType the alert doesn't show up. The problem is that the variables that the function Post (from the web service) receives are NULL even though I know that the JSON named dataa is not NULL since I did a console.log.
I have seen various examples and pretty much all of them say that I should use a relative URL but the problem is that since there are 2 different domains and when I tried it, it couldn't find the URL since it's not in the same localhost.
Web service should return a JSON format instead of null. like below example.
public JsonResult Post()
{
string output = pNuevaConeccion.insertarMetaData();
return Json(output, JsonRequestBehavior.AllowGet);
}
try to use this code for calling the web method
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: dataa,
url: 'http://localhost:57501/api/addDatabase/',
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
its my old code.(ensure action parameter variable name and post variable name are same)
$('#ConnectionAddres_ZonesId').change(function () {
var optionSelected = $(this).find("option:selected");
var id = { id: optionSelected.val() };
$.ajax({
type: "POST",
url: '#Url.Action("GetParetArea", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(id),
dataType: "json",
success: function (data) {
$('#ConnectionAddres_ParentAreaId').empty().append('<option value="">Select parent area</option>');
$.each(data, function (index, value) {
$('#ConnectionAddres_ParentAreaId').append($('<option />', {
value: value.Id,
text: value.Area
}));
});
},
});
});
public ActionResult GetParetArea(int id)
{
var parents="";
return Json(parents, JsonRequestBehavior.AllowGet);
}
I try to send values from my view to my controller.
The method in my controller is called but the value(s) still remain NULL.
Here is the Javascript part:
GUIRequests.prototype.SetNewItemDeliveryValues = function () {
var modelNumberID = this.GetValue('#ModelNumberID');
this.Request.GetPreOrderIDForModelNumberID(modelNumberID); //InventValueRequest
this.Request.GetShortfallAndOverdeliveryInNewItemDelivery(modelNumberID);
}
InventValueRequest.prototype.GetPreOrderIDForModelNumberID = function (_modelNumberID) {
this.CallAjax("/NewItemDelivery/GetPreOrderIDForModelNumberID", _modelNumberID, CallbackMethods.SetPreOrderID);
}
//Private
InventValueRequest.prototype.CallAjax = function (_url, _data, _successFunctionPointer) {
$.ajax({
type: 'POST',
url: _url,
contentType: 'application/json',
data: JSON.stringify(_data),
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
}
Asp.Net MVC5 (C#) part
[HttpPost]
public ActionResult GetPreOrderIDForModelNumberID(string _modelnumberID)
{
String preOrderID = "";
if (_modelnumberID == null)
{
preOrderID = "No value received";
}
else
{
//Do something
}
return Json(preOrderID);
}
What could be the problem with my code ? why don't I receive any values in my C# part ? It seems that the values get send correctly, at least the payload contains the values I would expect.
_data should have the property _modelnumberID like following.
_data = {'_modelnumberID': '1'}
try below code :
$.ajax({
type: 'POST',
dataType: 'text',
url: _url,
contentType: 'application/json',
data: "_modelnumberID=" + _data,
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
The Ideal solution would be to use a view model.
public class Create
{
public string _modelnumberID{get;set;}
}
And your HttpPost action would be accepting an object of this
[HttpPost]
public ActionResult View(Create model)
{
// do something and return something
}
and ajax will be
$('.submit').click(function () {
var myData = {
_modelnumberID: _data
}
$.ajax({
url: '/Controller/Action',
type: 'POST',
data: myData,
processData: false
}).done(function () {
}).fail(function () {
});
});
$.ajax({
type: 'POST',
url: _url+"?_modelnumberID="+ _data,
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
Try this.
I am calling javascript function on #Html.ActionLink clicked event. The Javascript function calls the jquery function in which I have written the $.ajax method for calling the json controller method. But it is not calling the controller method.......
Here is my code:
View
#Html.ActionLink("Submit", "AdminEvaluate", "Application", new { onclick = "Show('" + Model.applicationList.ApplicationId + "','statusList')" })|
Here, ApplicationId is coming from database and statusList is Radio Button group name from where I need to find the selected radio button.
Javascipt and jQuery code
function Show(appId, appStatus) {
$.fn.gotof(appId,appStatus);
}
Getting parameter from view and passing to jQuery function
jQuery function
$(document).ready(function () {
$.fn.gotof = function (appId, appStatus) {
var selectedItem = $("input[name='" + appStatus + "']:checked").val();
$.ajax({
url: '/Application/UpdateApplicantStatus',
data: { id: appId , status: selectedItem},
traditional: true,
dataType: "json",
contentType: "application/json",
success: function (data) {
alert(data);
}
});
});
Controller Method
public JsonResult UpdateApplicantStatus(int id, string status){
return Json("Correct", JsonRequestBehavior.AllowGet);
}
I have put break point on controller method but it is not coming at a break point.
Thanks in Advance.
May be this sample help you :) let me know
ajax call with type :
$.ajax({
type: "GET",
url: '#Url.Action("UpdateApplicantStatus", "Application")',
contentType: "application/json; charset=utf-8",
data: { id: appId , status: selectedItem },
dataType: "json",
success: function() { alert('Success'); }
});
controller :
public ActionResult UpdateApplicantStatus(int id, string status){
return Json(// blah blah blah ...
}
This should work else let me know
Your ajax call is wrong.
If your controller method signature is
public JsonResult UpdateApplicantStatus(int id, string appStatus)
Then you MUST have parameter names matching with your parameters of your ajax call.
So, instead of
data: { id: appId , status: selectedItem}
Just write
data: { id: appId , appStatus: selectedItem}
If you have any other problem, just post the error(s) you should have in your browser's console.
Maybe parameter names of controller function and ajax calling function should match.
you can try this
data: { id: appId , appStatus: selectedItem},
Do that way actually 3 mistakes 1 was notify by #Mr Code the type is missing 2nd your parameters not match as your function takes one you send the data in wrong format..
$(document).ready(function () {
$.fn.gotof = function (appId, appStatus) {
var selectedItem = $("input[name='" + appStatus + "']:checked").val();
$.ajax({
url: '/ApplicationController/UpdateApplicantStatus',
data:"{'id':'" + appId + "', 'appStatus': '" + selectedItem+ "'}",//here you format is wrong i correct it
traditional: true,
dataType: "json",
contentType: "application/json",
success: function (data) {
alert(data);
}
});
});
sat on this for hours:
When using ajax - json in a js.script file:
the url is written with its real path e.g. - url: '/contoller/Action',
$.ajax({
url: '/NextPage/GetSpDropDown',
data: {'segInputVal': segInputVal},
cache: false,
type: "GET",
dataType: "json",
success: function (result) {
if (result.Success) {
var resultArray = result.Result;.....
If the script is written in your HTML page then you must use
#(Url.Action(Action,controller))
$.ajax({
url: "#(Url.Action("GetSpDropDown", "NextPage"))",
data: { 'segInputVal': segInputVal },
cache: false,
type: "GET",
dataType: "json",
success: function (result) {
if (result.Success) {
var resultArray = result.Result;....
And dont forget not to include the word controller in your controller name.
I have had SO MUCH help from stackoverflow- hope to pay a little back
Can't seem to get the variable getID to work. I'm trying to change the html of the div. I know that the variable has the right value.
$('.cardid').change(function() {
var getID = $(this).attr('value');
$.ajax({
type: "POST",
url: "inc/change_thumbnail.php",
data: "id="+getID,
cache: false,
success: function(data) {
$("#"+getID).html(data);
alert("success");
},
error: function (err) {
alert("error");
}
});
});
Write data in $.ajax as data: {id : getID}, instead of data: "id="+getID,
Use val to get the value of an input :
var getID = $(this).val();
As you're making a POST request, you should also use the data argument to let jQuery properly send the value :
$.ajax({
type: "POST",
url: "inc/change_thumbnail.php",
data: {id:getID},
cache: false,
success: function(data) {
$("#"+getID).html(data);
alert("success");
},
error: function (err) {
alert("error");
}
});
You can try this:
$('[id="'+getID+'"]').html(data);
and yes you should pass it this way:
data:{id:getID}