// something defined deleteArr and pass values to it
var postData = { deleteArr: deleteArr };
if(deleteArr.length > 0)
{
$.ajax({
url: "#Url.Action("Delete", "ASZ01")",
type: "POST",
data: postData,
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("success.");
},
error: function (response) {
alert(deleteArr[0]);
}
});
deleteArr.length = 0;
}
The above code is javascript.
Until $.ajax begin I can confirm that values in array is correct in immediate window,but when it comes to error: I got "undefined".
And the following is my function in controller
public void Delete(List<string> deleteArr)
{
service.Delete(deleteArr);
}
The second question is that I set breakpoint on that function but it can't stop.
I think maybe my ajax form is wrong?
Stringify to JSON, add the dataType: 'json' and then pass and also correct your ""
var postData = JSON.stringify({ deleteArr: deleteArr });
if(deleteArr.length > 0)
{
$.ajax({
url: #Url.Action("Delete", "ASZ01"),
type: "POST",
data: postData,
dataType: 'json'
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("success.");
},
error: function (response) {
alert(deleteArr[0]);
}
});
deleteArr.length = 0;
}
Small change to your postData
var postData = { deleteArr: JSON.stringify(deleteArr) };
Idea is to convert your array data into string format ie:JSON and posting to the server, The default Model binder of MVC framework will handle the part to convert them into List<string> for you
Related
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 am working on a real estate web app in ASP.NET MVC. My problem is in my Reservations section.
I am using AJAX to post in a Controller which returns a JSONResult. Here is my code:
Controller
[HttpPost]
public JsonResult SubmitReservation(ReservationViewModel rvm)
{
return Json(rvm, JsonRequestBehavior.AllowGet);
}
Main AJAX
var rvm = new ReservationViewModel();
getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);
$.ajax({
url: "/Reservations/SubmitReservation",
data: JSON.stringify(rvm),
type: "POST",
dataType: "json",
contentType: "application/json",
success: function () {
console.log(clientData);
console.log(siteData);
console.log(unitData);
//Assignment of data to different output fields
//Client Data
$('#clientName').html(clientData.FullName);
$('#clientAddress').html(clientData.Residence);
$('#clientContact').html(clientData.ContactNumber);
//Site Data
$('#devSite').html(siteData.SiteName);
$('#devLoc').html(siteData.Location);
////House Unit Data
$('#unitBlock').html(unitData.Block);
$('#unitLot').html(unitData.Lot);
$('#modelName').html(unitData.ModelName);
$('#modelType').html(unitData.TypeName);
$('#lotArea').html(unitData.LotArea);
$('#floorArea').html(unitData.FloorArea);
$('#unitBedrooms').html(unitData.NumberOfBedrooms);
$('#unitBathrooms').html(unitData.NumberOfBathrooms);
$('#unitPrice').html(unitData.Price);
$('#reservationDetails').show();
alert("Success!");
},
error: function (err) {
alert("Error: " + err);
}
});
Functions for fetching data
function getBuyerInfo(id, cb) {
$.ajax({
url: "/BuyersInformation/GetBuyerByID/" + id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: cb
});
}
function getSiteInfo(id, cb) {
$.ajax({
url: "/Sites/GetSiteByID/" + id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: cb
});
}
function getUnitInfo(id, cb) {
$.ajax({
url: "/HouseUnits/GetUnitByID/" + id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: cb
});
}
function ReservationViewModel() {
var buyerId = $('#SelectedBuyerID').val();
var siteId = $('#SelectedSiteID').val();
var unitId = $('#SelectedUnitID').val();
var rsvDate = $('#ReservationDate').val();
var me = this;
me.ReservationDate = rsvDate;
me.SelectedBuyerID = buyerId;
me.SelectedSiteID = siteId;
me.SelectedUnitID = unitId;
}
function clientCallback(result) {
clientInfo = result;
clientData = clientInfo[0];
}
function siteCallback(result) {
siteInfo = result;
siteData = siteInfo[0];
}
function unitCallback(result) {
unitInfo = result;
unitData = unitInfo[0];
}
The whole code WORKS well for the second time. However, it does not work for the FIRST time. When I refresh the page and I hit Create, it returns undefined. But when I hit that button again without refreshing the page, it works well. Can somebody explain to me this one? Why does AJAX returns undefined at first but not at succeeding calls? Thanks in advance.
You are calling several ajax requests in your code, inside these functions:
getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);
and finally $.ajax({...}) after them, where you use results from pervious ajax calls.
Your problem is that the first ajax calls do not necessarily return results before your start the last ajax because they are all async. You have to make sure you get three responds before calling the last ajax. Use promises or jQuery when, like this:
var rvm = new ReservationViewModel();
$.when(
$.ajax({
url: "/BuyersInformation/GetBuyerByID/" + rvm.SelectedBuyerID,
type: "GET",
contentType: "application/json",
dataType: "json"
}),
$.ajax({
url: "/Sites/GetSiteByID/" + rvm.SelectedSiteID,
type: "GET",
contentType: "application/json",
dataType: "json"
}),
$.ajax({
url: "/HouseUnits/GetUnitByID/" + rvm.SelectedUnitID,
type: "GET",
contentType: "application/json",
dataType: "json"
})
).done(function ( clientResponse, siteResponse, unitResponse ) {
clientInfo = clientResponse;
clientData = clientInfo[0];
siteInfo = siteResponse;
siteData = siteInfo[0];
unitInfo = unitResponse;
unitData = unitInfo[0];
$.ajax({ ... }) // your last ajax call
});
AJAX calls are asynchronous. You last ajax call will not wait until your above 3 ajax calls finishes its work. so you can make use of $.when and .done here as below..
$.when(
getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);
).done(
$.ajax({
//Ajax part
})
);
I have a dropdown that has a list of ID's in it. The customer will select one and it will reflect a price total on the page. Im creating an ajax call that will update the total when a different ID is pulled from the Dropdown.
$("#BrandId").on('focus', function () {
// Store the current value on focus and on change
previous = this.value;
}).change(function () {
alert("Previous: " +previous);
sel = this.value;
alert("Selected: " +sel);
$.ajax({
cache: false,
type: "get",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("GetBrandCost", "Shocks")',
data: JSON.stringify({ idp: previous, id: sel }),
dataType: "json",
aysnc: false,
success: function (data1) {
alert(data1);
//ShockTotal = $("#ShockTotal").html();
//ShockTotal = ShockTotal / 1;
////ShockTotal = ShockTotal - data1;
//$("#ShockTotal").html(data1);
}
});
});
The alerts are working perfectly but the ajax isnt passing those ID's into the controller, the controller is just receiving nulls.
public decimal GetBrandCost(string idp, string id)
{
decimal costp = 0;
decimal cost = 0;
if (id == "" || id == null || idp == "" || idp == null)
{
return 0;
}
ShockBrand brandp = db.ShockBrands.Find(idp);
costp = brandp.Cost;
ShockBrand brand = db.ShockBrands.Find(id);
cost = brand.Cost;
cost = cost - costp;
return cost;
}
Since they are null I am hitting my if statement and just returning zero inside the success. Most of the things I read were to add the content type but that didnt seem to help in my case, Im sure it is something little.
From browser console, this
$.ajax({
cache: false,
type: "get",
contentType: "application/json; charset=utf-8",
url: 'http://google.com',
data: JSON.stringify({ idp: 1, id: 2 }),
dataType: "json",
aysnc: false,
success: function (data1) {
console.log(data1)
}
});
returns request to http://google.com/?{%22idp%22:1,%22id%22:2}&_=1440696352799, which is incorrect
and without stringify
$.ajax({
cache: false,
type: "get",
contentType: "application/json; charset=utf-8",
url: 'http://google.com',
data: { idp: 1, id: 2 },
dataType: "json",
aysnc: false,
success: function (data1) {
console.log(data1)
}
});
returns http://google.com/?idp=1&id=2&_=1440696381239 (see Network tab)
So don't use JSON.stringify
Why it's gonna work - your asp.net controller action receives simple typed parameters (string, numbers, etc) and jquery is fairly enought smart to determine what are going to send, if it was object inside object it will send it as POST data for POST, and string represenation of object for GET (you have GET request, but for purpose of knowledge, just stick with 2 types of data that can be send, params & data) So when jquery configures url, asp.net understands conventions, and matches request to approciated action
But Don't believe me, check it yourself
chrome dev console is your friend
By removing the
contentType: "application/json; charset=utf-8
and
dataType: "json"
it worked for me. Otherwise, I was always getting value = null in the controller action.
My code for calling ajax with data is now:
$(function () {
$.noConflict();
$.ajax({
type: "POST",
url: "../Case/AjaxMethodForUpdate",
data: {typ: $('#typeID').val()},
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
You can just put it like
var dataReq={ idp: previous, id: sel };
data: dataReq
And no need to use dataType and contentType.
Basically I am trying to extract JSON returned from servlet in JavaScript. I have tested my servlet class already and it did returned some JSON so I guess I no need to post the code for that class. Here is my returned JSON format:
[{"mrtpopAmt":"7000","mrtpopX":"17854.99820","mrtpopY":"35056.35003"},{"mrtpopAmt":"6300","mrtpopX":"29798.58427","mrtpopY":"37036.56434"}]
And in my JavaScript, I am trying to extract mrtpopAmt, mrtpopX and mrtpopY as one object. Then I will add all object into an array:
function getAllMRTPop(time){
var jsonArray;
var Data = JSON.stringify({ time: time });
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time="+ Data + "",
type: "GET",
data: Data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var parsed = JSON.parse(data.d);
console.log(data.d);
$.each(parsed, function (i, jsondata) {
var jsonObject;
jsonObject.put("mrtpopAmt", jsondata.mrtpopAmt);
jsonObject.put("mrtstationX", jsondata.mrtstationX);
jsonObject.put("mrtstationY", jsondata.mrtstationY);
alert(jsonObject);
jsonArray.push(jsonObject);
});;
},
error: function (request, state, errors) {
}
});
}
However, I am getting error message like Unexpected token: u at this line:
var parsed = JSON.parse(data.d);
My URL for the servlet contains two parameter, one is action and the other one is time:
http://localhost:8080/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time=8:00
So I wonder am I passing the parameter correctly by passing it in url and as well as data from the code above?
I wonder which part went wrong? Thanks in advance.
EDIT
So I have updated my JavaScript part to this:
function getAllMRTPop(time){
var jsonArray = [];
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time=8:00",
type: "GET",
data: time,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
//var parsed = JSON.parse(data.d);
$.each(data, function (i, jsondata) {
var jsonObject;
console.log(mrtpopAmt);
jsonObject.put("mrtpopAmt", jsondata.mrtpopAmt);
jsonObject.put("mrtstationX", jsondata.mrtstationX);
jsonObject.put("mrtstationY", jsondata.mrtstationY);
jsonArray.push(jsonObject);
});;
},
error: function (request, state, errors) {
}
});
}
I tried to print out the mrtpopAmt and it did returned something. But there is an error message:
Cannot call method 'put' of undefined
Any ideas?
By specifying dataType: "json", jQuery already knows you will be getting a JSON response, there is no no need to do var parsed = JSON.parse(data.d)
Just do:
var parsed = data.d
Edit:
function getAllMRTPop(time){
var jsonArray = [];
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time=8:00",
type: "GET",
data: time,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
$.each(data, function (i, jsondata) {
var jsonObject = {};
jsonObject.mrtpopAmt = jsondata.mrtpopAmt;
jsonObject.mrtstationX = jsondata.mrtstationX;
jsonObject.mrtstationY = jsondata.mrtstationY;
jsonArray.push(jsonObject);
});;
},
error: function (request, state, errors) {
}
});
}
I think what is happening is that data.d is undefined, so you are getting the odd message about unexpected u.
Try this instead:
var parsed = JSON.parse(data);
Edit And I think you are probably not formatting your request right:
var Data = JSON.stringify({ time: time });
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time="+ Data + "",
Seems to me that would make the final bit: &time={"time":"time"}, so you probably want to look at how you construct Data. Maybe just pass time directly?
url: "/TrackNYP/TrackNYPServlet?action=GetAllMrtPop&time="+ time + "",
I am working on a project and have to send a JavaScript Array as a parameter of a ASP.Net function which parameter is ArrayList.
Below is my code,
JavaScript :
var propertyArray = new Array();
propertyArray.push("2");
propertyArray.push("3");
$.ajax({
type: 'POST',
url: 'Default.aspx/SaveTextProperty',
contentType: 'application/json; charset=utf-8',
data: { propertyArray: propertyArray },
dataType: 'json',
success: function (response) {
var result = "Done";
alert(result);
}
});
Default.aspx :
[WebMethod]
public static bool SaveTextProperty(ArrayList propertyArray)
{
//Some code
return true;
}
Here I need to get JavaScript propertyArray as ASP.Net function named SaveTextProperty's parameter.
How can I get it?
Thank you.
You can use as follow
[WebMethod]
public static bool SaveTextProperty(List<string> arr)
{
//Some code
return true;
}
and jquery
var propertyArray = new Array();
propertyArray.push("2");
propertyArray.push("3");
$.ajax({
type: 'POST',
url: 'Default.aspx/SaveTextProperty',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ arr: propertyArray }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: onSuccess,
failure: onError
});
function onSuccess(response) {
alert(response.d);
}
function onError() {
alert("fail");
}