my url is look like :
localhost:1336/PartPicker/Part/Mobile/list_view
i want ajax post request. But ajax request is not wroking
my controller action code
public JsonResult getProduct(String partid, String id)
{
return Json("success");
}
my ajax request code
function btn_Click()
{
var sdata = { partid: 'abc', id: 'xyz' };
$.ajax({
type: 'POST',
url: 'getProduct',
data: JSON.stringify(sdata),
contentType: 'application/json;charset=utf-8',
dataType: "jsonp",
processdata: false,
success: function (data) { alert(data);},
error: function (serverdata) { alert("eror " + serverdata.responseText) },
async: false
});
}
route settings
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{partid}/{id}/",
defaults: new
{
controller = "PartPicker",
action = "Part",
partid = UrlParameter.Optional,
id = UrlParameter.Optional
},
namespaces: new[] { " abc.Controllers" }
);
I can't identify why ajax request is not working. Please someone help me
Try this:
var sdata = "{'partid':'abc','id':'xyz'}";
Related
I have a problem where the data in the ajax isn't passing the sessionStorage item. I have tried using JSON.stringify and added contentType: 'application/json' but still it's not passing. Can this be done using POST method? Also, I have debugged and returned those sessionStorages, hence the problem isn't because the sessionStorge doesn't contain data.
Here my function:
function functionA() {
$.ajax({
url: URLToApi,
method: 'POST',
headers: {
sessionStorage.getItem('token')
},
data: {
access_token: sessionStorage.getItem('pageToken'),
message: $('#comment').val(),
id: sessionStorage.getItem('pageId')
},
success: function () {
$('#success').text('It has been added!"');
},
});
}
Check below things in Controller's action that
there should be a matching action in controller
name of parameter should be same as you are passing in data in ajax
Method type should be same the ajax POST of the action in controller.
function AddPayment(id, amount) {
var type = $("#paymenttype").val();
var note = $("#note").val();
var payingamount = $("#amount").val();
$('#addPayment').preloader();
$.ajax({
type: "POST",
url: "/Fixed/AddPayment",
data: {
id: id,
amount: payingamount,
type: type,
note: note
},
success: function (data) {
}
});
}
Here is the working code from my side.
Check with this, and for the header part you need to get it from the Request in action
The solution to this problem has been found. The issue was the sessionStorage, hence I've passed it directly to the URL and now it working as follows:
function functionA() {
$.ajax({
url: 'http://localhost:#####/api?id=' + sessionStorage.getItem('pageId') + '&access_token=' + sessionStorage.getItem('pageToken') + '&message=' + $('#comment').val(),
method: 'POST',
headers: {
sessionStorage.getItem('token')
},
success: function () {
$('#success').text('It has been added!"');
},
});
}
I am creating a web application for event management using .net mvc and jquery.
I created a mvc web app.contoller named SeatPlansController and model named SeatPlanes and I am able to insert the data to database.
But I am not able pass the data from jquery to database using the mvc controller.
My controller action code is as shown below
// GET: SeatPlans/Create
public ActionResult Create()
{
return View();
}
// POST: SeatPlans/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(String seat_id, String seat_no)
{
int id = 10;
SeatPlans S = new SeatPlans();
S.seat_id = seat_id;
S.seat_no = seat_no;
if (ModelState.IsValid)
{
db.SEATPLAN.Add(S);
db.SaveChanges();
// return RedirectToAction("Index");
}
return View(S);
}
In post create controller Id is primary key, so I want to pass seat_id,seat_no as argument and it should update the database.
I used following javascript
function getPerson(id) {
$.ajax({
type: "GET",
url: '#Url.Action("create", "SeatPlanesController")',
contentType: "application/json; charset=utf-8",
data: {eat_id :6, seat_no:8},
dataType: "json",
success: function (result) {
alert(result);
//window.locationre = result.url;
}
});
}
I am able to run the create get method using
http://localhost:52348/SeatPlans/Create
but how can I run post method directly from browser with argument
something like
http://localhost:52348/SeatPlans/Create/2/3t/e
I have changed the script as bellow,it works for GET method but if i made TYPE:"post" it popup an alert box with alert
"localhost:52348 says:
internal server error"
$(document).ready(function () {
$("button").click(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("Create", "SeatPlans", new { Area = "" })',
data: { seat_id: "34", seat_no: "98" },
dataType: "json",
async: false,
success: function (result) {
$("#div1").html(result);
},
error: function (abc) {
alert(abc.statusText);
},
});
});
});
Finally i got the sollution
i changed the script as bellow
//jQuery.noConflict();
// var $j = jQuery.noConflict();
function clickevent()
{
var form = $("#frm");
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
type: "post",
// headers: { "__RequestVerificationToken": token },
url: '#Url.Action("Create", "SeatPlans")',
data: {
seat_id: "34", seat_no: "98"
},
success: function (result) {
$("#div1").html(result);
}
});
}
and change the create post method as bellow
<pre>
public ActionResult Create(String seat_id, String seat_no)
{
int id = 10;
SeatPlans S = new SeatPlans();
S.seat_id = seat_id;
S.seat_no = seat_no;
if (ModelState.IsValid)
{
db.SEATPLAN.Add(S);
db.SaveChanges();
// return RedirectToAction("Index");
}
return View(S);
}
I'm trying to make an ajax call to the controller method. without parameter it works fine. Once i add the parameter i always receive a null parameter to the cotroller. I think i have correctly done the parameter passing in ajax call.
<script type="text/javascript">
$(document).ready(function () {
$('#lstStock').change(function () {
var serviceURL = '<%= Url.Action("GetStockPrice", "Delivery") %>';
var dropDownID = $('select[id="lstStock"] option:selected').val();
alert(dropDownID); // here i get the correct selected ID
$.ajax({
type: "POST",
url: serviceURL,
data: '{"stockID":"' + dropDownID + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data.Result);
}
function errorFunc() {
alert('error');
}
})
});
</script>
Controller:
[HttpGet]
public ActionResult GetStockPrice()
{
return View();
}
[HttpPost]
[ActionName("GetStockPrice")]
public ActionResult GetStockPrice1(string stockID)//I get the null parameter here
{
DeliveryRepository rep = new DeliveryRepository();
var value = rep.GetStockPrice(stockID);
return Json(new { Result = value }, JsonRequestBehavior.AllowGet);
}
It's because you are treating the data as a string
data: '{"stockID":"' + dropDownID + '"}',
you can change it to:
data: { stockID: dropDownID },
in some cases, depending on the parameter declared in your controller method, you need to serialize the data. If you need to do that then this is how you would do it:
var o = { argName: some_value };
$.ajax({
// some other config goes here
data: JSON.stringify(o),
});
try data: { stockID : dropDownID},
$('#lstStock').change(function () {
var serviceURL = '<%= Url.Action("GetStockPrice", "Delivery") %>';
var dropDownID = $('select[id="lstStock"] option:selected').val();
// $(this).val(); is better
alert(dropDownID); // here i get the correct selected ID
$.ajax({
type: "POST",
url: serviceURL,
data: { stockID : dropDownID},
....
Try specifying:
data: { stockID : dropDownID },
It looks like you're passing up "stockID" not stockID.
A good tool to use for this is Fiddler, it will allow you to see if the Controller action is hit and what data was sent upto the server.
How do I retrieve the ID from the following model, after the following JQuery/Ajax posts to it:
JQuery:
$.ajax({
type: 'POST',
url: '/api/searchapi/Post',
contentType: 'application/json; charset=utf-8',
data: toSend,
}).done(function (msg) {
alert( "Data Saved: " + msg );
});
Controller:
// POST api/searchapi
public Void Post(Booking booking)
{
if (ModelState.IsValid)
{
tblCustomerBooking cust = new tblCustomerBooking();
cust.customer_email = booking.Email;
cust.customer_name = booking.Name;
cust.customer_tel = booking.Tel;
bc.tblCustomerBookings.Add(cust);
bc.SaveChanges();
long ID = cust.customer_id;
Return ID; <-- what do I enter here?
}
Return "Error"; <-- and here?
}
How can I get the ID back into the jQuery script, and if the model isn't valid, how do I return an error to the jQuery?
Thanks for any help,
Mark
You could return a JsonResult
[HttpPost]
public ActionResult Post(Booking booking)
{
if (ModelState.IsValid)
{
tblCustomerBooking cust = new tblCustomerBooking();
cust.customer_email = booking.Email;
cust.customer_name = booking.Name;
cust.customer_tel = booking.Tel;
bc.tblCustomerBookings.Add(cust);
bc.SaveChanges();
return Json(new { id = cust.customer_id });
}
return HttpNotFound();
}
and then on the client simply:
$.ajax({
type: 'POST',
url: '/api/searchapi/Post',
contentType: 'application/json; charset=utf-8',
data: toSend,
}).done(function (msg) {
alert('Customer id: ' + msg.id);
}).error(function(){
// do something if the request failed
});
One way to do it is like this:
In your controller:
public Void Post(Booking booking)
{
//if valid
return Json(new {Success = true, Id = 5}); //5 as an example
// if there's an error
return Json(new {Success = false, Message = "your error message"}); //5 as an example
}
In your ajax post:
$.ajax({
type: 'POST',
url: '/api/searchapi/Post',
contentType: 'application/json; charset=utf-8',
data: toSend,
success: function(result) {
if (result.Success) {
alert(result.Id);
}
else {
alert(result.Message);
}
}
});
returning void isn't a good idea, use JsonResult
Because you are using JavaScript, I recommend using JSON.
return this.Json(new { customerId = cust.customer_id});
In order to receive a return value, the controller method must return something other than void.
Does your controller compile? Your post method has a void return type, so it should fail compilation when it sees the return ID and return "Error" commands
I want to send JSON data to an action that will update some data. I then want to either redirect to another action or send back an error message to $.ajax.
Is possible with $.ajax otherwise how can I?
Becase following code does not redirect.
[code]
[HttpPost]
public ActionResult Save(RecipeViewModel postdata)
{
Recipe recipe = postdata.GetRecipe(_user.UserID);
int recipeid = _service.AddRecipe(recipe, null, true);
foreach (Ingredient ing in recipe.Ingredients)
{
ing.RecipeID = recipeid;
_service.AddIngredient(ing, null, false);
}
if (!postdata.Comment.IsEmpty())
{
Comment comment = new Comment();
comment.fldComment = postdata.Comment;
comment.RecipeID = recipeid;
comment.UserID = _user.UserID;
comment.EnteredByName = _user.Names;
comment.EnteredOn = DateTime.Now.ToString();
_service.AddComment(comment, null, false);
}
_service.SubmitChanges();
return RedirectToAction("View", "Recipe", new { id = recipeid });
}
u<script type="text/javascript">
$("#Save").click(function () {
var ingredients = $("#ingredients tr.ingredientdata").map(function (element, index) {
return {
ingredientName: $("td.ingredient", this).text(),
units: $("td.units", this).text(),
measure: $("td.measure", this).text()
};
}).toArray();
var json = {
RecipeTitle: $("#recipetitle").val(),
CategoryID: $("#category").val(),
PrepTime: $("#prepTime").val(),
PrepTimePeriod: $("#lstPrepTime").val(),
CookTime: $("#cookTime").val(),
CookTimePeriod: $("#lstCookTime").val(),
Rating: $("#rating").val(),
Method: $("#method").val(),
Comment: $("#comment").val(),
AccessLevel: $("#accessLevel").val(),
Ingredients: ingredients
};
$.ajax({
url: "/Recipe/Save",
type: "POST",
dataType: 'json',
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
success: function () {
//alert("DONE!!");
}
});
});
[/code]
Malcolm
You need to send back the Url and redirect it from the client script.
success: function (urlData) {
window.location.href = urlData ;
return false;
}
or you may show an error message based on the response received.