When a user clicks a save button, a JavaScript function uses AJAX to call the Controller and send over JSON data about the objects.
JavaScript Function
$.ajax({
url: "/Data/sendFridgeItems?items=" + JSON.stringify($scope.items.data),
type: "POST",
data: JSON.stringify($scope.items.data),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
console.log("good!");
},
error: function () {
console.log("error");
}
});
Controller
[HttpPost]
public ActionResult SendFridgeItems(string items)
{
fridge[] fridgeItems = JsonConvert.DeserializeObject<fridge[]>(items);
foreach (fridge item in fridgeItems)
{
bool exists = cookDB.fridges.AsEnumerable()
.Any(x => x.Name == item.Name && x.Purchased == item.Purchased && x.Count == item.Count);
if (!exists)
{
cookDB.fridges.Add(item);
cookDB.SaveChangesAsync();
}
}
return null;
}
It works, but I don't think the way of sending my data through the url parameter is correct in my situation, because the data will be big enough. I wanted to know if there is a better way to send my data to the controller?
I tried to send it this way, but the controller receives null value.
$.ajax({
url: "/Data/sendFridgeItems",
type: "POST",
data: JSON.stringify($scope.items.data),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
console.log("good!");
},
error: function () {
console.log("error");
}
});
JSON of $scope.items.data
[{"id":2,"name":"Item1","count":2,"type":"pcs.","purchased":"12/09/2017","wasted":"15/10/2017","cam":"Freezer","comment":"no comment","$$hashKey":"object:38"},{"id":3,"name":"Item2","count":30,"type":"g.","purchased":"15/01/1880","wasted":"21/03/1882","cam":"Cooler","comment":"commented","$$hashKey":"object:39"}]
$scope.items
$scope.items = {
"count": 2,
"data": [
{
"name": "Item1",
"count": 2,
"type": "pcs.",
"purchased": "12/09/2017",
"wasted": "15/10/2017",
"cam": "Freezer",
"comment": "no comment"
},
{
"name": "Item2",
"count": 30,
"type": "g.",
"purchased": "15/01/1880",
"wasted": "21/03/1882",
"cam": "Cooler",
"comment": "Commented"
}
]
};
Fixed Controller For N.Ivanov's solution (this controller+ N.Ivanov's ajax = solution)
public ActionResult SendFridgeItems(fridge[] items)
{
fridge[] fridgeItems = JsonConvert.DeserializeObject<fridge[]>(items.ToString());
foreach (fridge item in items)
{
bool exists = cookDB.fridges.AsEnumerable()
.Any(x => x.Name == item.Name && x.Purchased == item.Purchased && x.Count == item.Count);
if (!exists)
{
cookDB.fridges.Add(item);
cookDB.SaveChangesAsync();
}
}
return null;
}
The data field in ajax takes in an Object, you are giving it a string. Try and supply only your object, assuming that $scope.items.data is an object. If you give a bit more information on what $scope variable is, then I can give you a better answer.
Code:
$.ajax({
url: "/Data/sendFridgeItems",
type: "POST",
d̶a̶t̶a̶:̶ ̶$̶s̶c̶o̶p̶e̶.̶i̶t̶e̶m̶s̶.̶d̶a̶t̶a̶,̶
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
console.log("good!");
},
error: function () {
console.log("error");
}
});
Hope this helps!
EDIT:
Further inspection after you have provided the contents of $scope.items.data led me to notice that $scope.items.data is an array of objects. So in order for the ajax to work and actually supply valid JSON, try the following code:
$.ajax({
url: "/Data/sendFridgeItems",
type: "POST",
data: { "items": $scope.items.data },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
console.log("good!");
},
error: function () {
console.log("error");
}
});
I have verified that { "item": $scope.items.data } is a valid JSON through JSONLint
Hope this solves your problem!
Try JSON Parse to parse data as Object and send it to controller
$.ajax({
url: "/Data/sendFridgeItems",
type: "POST",
data: JSON.parse($scope.items.data),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
console.log("good!");
},
error: function () {
console.log("error");
}
});
Related
I'm trying to post some data to an API but I'm struggling with javascript.
function pushData() {
let rawdata;
$.ajaxSetup({
async: false
});
$.getJSON('https://api.db-ip.com/v2/free/self', function(result) {
result = rawdata;
})
console.log(rawdata);
let message = {
"ip": rawdata.ipAddress,
"country": rawdata.countryName,
"city": rawdata.city
};
console.log(message);
$.ajax({
url: "https://xxxx.execute-api.eu-west-2.amazonaws.com/get",
headers: {},
/* crossDomain: true,
*/
type: "GET",
success: function(result) {
console.log(result);
},
error: function() {
console.log("error");
}
})
}
$.ajax({
url: "https://xxxx.execute-api.eu-west-2.amazonaws.com/post",
crossDomain: true,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(message),
success: function(result) {
console.log(result);
},
error: function() {
console.log("error pushing data");
}
})
I'm getting Uncaught ReferenceError: message is not defined although I think that message is a global variable, so it should be called successfully on the payload? What I'm I doing wrong here?
Thanks to anyone for his reply in advance, I'm just trying to write a quick script for my API here.
message is a local variable in the pushData() function, not a global variable. But even if it were global, you'd have to call the function before the second $.ajax() call.
Move the second AJAX call inside the function so you can access the variable. And embrace asynchrony, don't fight it with async: false. Nest the successive AJAX calls inside the callback function of the previous one.
function pushData() {
$.getJSON('https://api.db-ip.com/v2/free/self', function(rawData) {
console.log(rawdata);
let message = {
"ip": rawdata.ipAddress,
"country": rawdata.countryName,
"city": rawdata.city
};
console.log(message);
$.ajax({
url: "https://xxxx.execute-api.eu-west-2.amazonaws.com/get",
headers: {},
/* crossDomain: true,
*/
type: "GET",
success: function(result) {
console.log(result);
$.ajax({
url: "https://xxxx.execute-api.eu-west-2.amazonaws.com/post",
crossDomain: true,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(message),
success: function(result) {
console.log(result);
},
error: function() {
console.log("error pushing data");
}
})
});
},
error: function() {
console.log("error");
}
})
}
i want to send 2d array from javascript file to action method.
My javascript function
function _tbdata() {
var dataarr = [];
for(var i = 0; i<svarr.length; i++)
{
var trangthai = $("input[name='" + svarr[i] + "']:checked").val();
var lydo = $("#" + svarr[i]).val();
dataarr[i] = new Array(2);
dataarr[i][0] = trangthai;
dataarr[i][1] = lydo;
}
$.ajax({
url: '/DiemDanh/testMethod',
data: { info: JSON.stringify(dataarr ) },
type: "POST",
traditional:true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('running');
},
error: function (data, textStatus) { alert(textStatus); }
});
}
And my controller
[HttpPost]
public ActionResult testMethod(List<List<string>> info)
{
return RedirectToAction("Index");
}
And when i debug in chrome, i got error
POST http://localhost:56602/DiemDanh/testMethod 500 (Internal Server
Error)
Sorry about my Enligsh is bad, Hope suggest from everybody!!!
I think you should change your javascript. Two dimensional array sholud be [[]]
I've write an example for your code. It works fine.
function Test() {
var dataarr = [[]];
for (var i = 0; i < 1; i++) {
dataarr[i][0] = "A" + i.toString();
dataarr[i][1] = "B" + i.toString();
}
var model = JSON.stringify(dataarr);
$.ajax({
url: '/Home/testMethod',
data: model,
type: "POST",
traditional: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('running');
},
error: function (data, textStatus) { alert(textStatus); }
});
}
Change your ajax like this.
$.ajax({
url: '/DiemDanh/testMethod',
data: { info: JSON.stringify(ngay) },
type: "POST",
traditional:true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert('running');
},
error: function (data, textStatus) { alert(textStatus); }
});
}
change your method parameter with string multi dimensional array it will work because list of list strings parameter won't work it'll not accepting 2d array
[HttpPost]
public ActionResult testMethod(string [][] info)
{
return RedirectToAction("Index");
}
// 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
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);
}
<WebMethod()> Public Shared Function gtet() As String
...
Dim GET = uClass.GetSets(dbuser, dbparam1)
...
End Function
and
$(document).ready(function ()
{
data = { };
var jsondata = $.toJSON(data);
$.ajax({
type: "GET",
url: "index.aspx/gtet",
data: jsondata,
contentType: "application/json; charset=utf-8",
dataType: "text json",
beforeSend: function (xhr)
{
xhr.setRequestHeader("Content-type",
"application/json; charset=utf-8");
},
success: function (cget)
{
alert(cget);
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
window.location.reload();
}
});
}
Am I doing this right? I need to pull the string from Dim GET
Send the json as a parameter.
data: {
"json": jsondata
},
Also, make sure your webmethod is returning valid json.