Uncaught ReferenceError: data is not defined // can't get the date in ajax - asp.net

Can't load my data, i guess something is wrong with getting the date. Here's my ajax:
function refreshdata(page) {
dates = '{ "date": "2017-05-12T09:14:15Z" }';
if (page == 1) {
$.ajax({
url: semRoute,
type: 'GET',
success: function (result) {
var data = JSON.parse(result);
showData(data);
}
});
}
console.log(page);
}
AjaxController:
public string Get(string date)
{
var obj = new DepDate(date);
return Model.balance.GetDataJSON(obj);
}

Related

Render View with Json Result

Im wondering is it possible to render a view from a json result, basically when the user clicks on a button in my view, i want to go and fetch data from my controller/model using json result, with this data i want to open a view with the new data, is this possible?
AJax Call
$.ajax({
type: 'POST',
url: '#Url.Action("GetAdminSubmissions", "Inspections")',
contentType: "application/json; charset=utf-8",
datatype: JSON,
data: { 'selectedDepartment': deparment, 'searchDate': selectedDate },
success: function (result) {
// on success open view with new updated model
},
error: function (result) {
alert(result);
}
});
}
Controller
public JsonResult GetAdminSubmissions(string selectedDepartment, string searchDate)
{
var result = new List<Checks_Records>();
if (searchDate != null)
{
var enUkCultureInfo = new CultureInfo("en-GB");
var userSelectedDate = DateTime.Today.Date.AddHours(7);
DateTime parsedDate;
if (DateTime.TryParseExact(searchDate, "dd-MMMM-yyyy", enUkCultureInfo, DateTimeStyles.None, out parsedDate))
{
userSelectedDate = parsedDate.AddHours(7);
result = Model.GetListofChecks_Records(userSelectedDate, selectedDepartment);
var json = new JavaScriptSerializer().Serialize(result);
return Json(json, JsonRequestBehavior.AllowGet);
}
}
return error;
}

AJAX data parse to Controller and return back

Here is an AJAX call to the controller:
$.ajax({
type: "GET",
url: '#Url.Action("getChat", "Chat")',
success: function (data) {
alert(data);
$("#data").html(data);
},
error:{
}
});
In the controller code, I have a database query which returns multiple rows.
I want to return that variable back to JSON and print each row separately in AJAX and write that data in HTML.
Here is my Controller code
public ActionResult getChat()
{
var p = (from v in DB.chats where v.chatuserID == id select new { v.status, v.message }).ToList();
return Content(p.ToString());
}
The query is returning data. I am attaching an image that shows the variables content.
public JsonResult getChat()
{
var p = (from v in DB.chats
where v.chatuserID == id select new { v.status,
v.message
}).ToList();
return json(p,JsonRequestBehavior.AllowGet);
}
Now you can loop through the list in you ajax success callback function : here is stuff.
$.ajax({
type: "GET",
url: '#Url.Action("getChat", "Chat")',
success: function (data) {
$.each(data,function(){
console.log("Status "+ data.status +" "+"Message"+ data.message);
});
},
error:{
}
});

Script not works (ASP.NET MVC)

I have script for recording video
Here is code of it
var fileName;
stop.onclick = function () {
record.disabled = false;
stop.disabled = true;
window.onbeforeunload = null; //Solve trouble with deleting video
preview.src = '';
fileName = Math.round(Math.random() * 99999999) + 99999999;
console.log(fileName);
var full_url = document.URL; // Get current url
var url_array = full_url.split('/') // Split the string into an array with / as separator
var id = url_array[url_array.length - 1]; // Get the last part of the array (-1)
function save() {
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
I try to get url with this row var id = url_array[url_array.length - 1]; // Get the last part of the array (-1)
and with this code write to table filename
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
but it not works.
There is my Action method for it
[HttpPost]
public ActionResult LinkWriter(string link, int id) {
Link link_ = new Link
{
Link1 = link,
Interwier_Id = id,
};
db.Link.Add(link_);
db.SaveChanges();
return View();
}
But it not works. Where is my mistake?
UPDATE
As I understood not works this
function save() {
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
link: fileName,
id: id,
},
url: '#Url.Action("LinkWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
alert("lol");
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}

JsonResult has no name, how do I access the values

I have a linq query in my controller that returns values from the database in JSON format. However The JSON object has no name so I tried a couple things but everything returns undefined.
My JSON object looks like:
Object {UserId: 4, UserName: "John", UserPassword: "Password"}
Controller
[HttpPost]
public JsonResult Index(string searchString, string searchPassword)
{
var user = (from u in db.Users where u.UserName.Equals(searchString) && u.UserPassword.Equals(searchPassword) select u).FirstOrDefault();
return Json(user);
}
Ajax
$('#test2').click(function(e) {
e.preventDefault();
var user = "John";
var userpass = "Password";
$.ajax({
url: "#Url.Action("Index", "Users")",
data: { "searchString": user, "searchPassword": userpass },
type: "post",
success: function (data) {
var results = [];
for (var i = 0; i < data.length; i++) {
results[data[i]["Key"]] = data[i]["Value"];
}
alert((result.UserName));
alert((result.UserPassword));
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr, ajaxOptions, thrownError);
}
})
})
The alerts come up with just undefined
You should be able to access the object by just using the properties from your C# object. So in your ajax success function, just use data.UserId or data.UserName
Do this in your ajax success
success: function (data) {
var results = [];
for (var i = 0; i < data.length; i++) {
result.push(data[i].UserId +" "+ data[i].UserName);
}
alert(result);
}

How to handle $.ajax

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.

Resources