i want jquery to take a JsonResult from my MVC controller but it does'nt receive any data!
If I put the output into a textfile and enter its link its working so I think my jQuery is fine.
Then I was testing with other browsers like chrome and I saw NOTHING. The requested page was just emtpy.. no errors. Also IE seems to have problems receiving my string.. only firefox displays the string but why?
public JsonResult jsonLastRequests()
{
List<Request> requests = new List<Request>();
while (r.Read())
{
requests.Add(new Models.Request()
{
ID = (int)r[0],
SiteID = r[1].ToString(),
Lat = r[2].ToString(),
City = r[4].ToString(),
CreationTime = (DateTime)r[5]
});
}
r.Close();
return Json(requests);
}
I found out that also if I want to return the JSON as string its not working!
Its working with a string in all browsers now.. but jQuery is still not loading anything
var url = "http://../jsonLastRequests";
var source =
{
datatype: "json",
datafields: [
{ name: 'ID' },
{ name: 'SiteID' },
{ name: 'Lat' },
{ name: 'CreationTime' },
{ name: 'City' },
],
id: 'id',
url: url
};
var dataAdapter = new $.jqx.dataAdapter(source, {
downloadComplete: function (data, status, xhr) { },
loadComplete: function (data) { },
loadError: function (xhr, status, error) { }
});
I fixed my problem by adding:
access-control-allow-origin:*
public HtmlString jsonLastRequests()
{
List<Request> requests = new List<Request>();
while (r.Read())
{
requests.Add(new Models.Request()
{
ID = (int)r[0],
SiteID = r[1].ToString(),
Lat = r[2].ToString(),
City = r[4].ToString(),
CreationTime = (DateTime)r[5]
});
} r.Close();
System.Web.Script.Serialization.JavaScriptSerializer jSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return new HtmlString(jSerializer.Serialize(requests ));}
I have done same approch like this
$.ajax({
type: 'POST',
url: '/home/GetSurvey',
data: {
XmlPath: $("#xmlpath").val()
},
dataType: 'json',
success: function (jsonData) {
jsonStringQuestionaire = jsonData;
LoadSurvey();
},
error: function () {
alert('Error loading ' + id);
}
});
questionaireJsonList = eval(jsonStringQuestionaire);
Related
I've tried all other solutions pertaining to the problem, but still can't find what i'm missing for my code. Here's my AJAX() Code.
var group = JSON.stringify({ 'listofusers': listofusers });
console.log("listofusers : " + JSON.stringify({ 'listofusers': group }));
(Assuming I have my listofusers object ready, and yes i've checked the console and it has data inside.)
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: "POST",
url: url,
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
//doSend(JSON.stringify(data));
//writeToScreen(JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
Here's my Server Side Controller.
[HttpPost]
public IActionResult GetMesssage(List<UserModel> listofusers)
{
var g = listofusers;
}
Just a simple fetch from the controller, so I could verify that the data from client side has really been sent.
I've tried the [FromBody] attribute, but still no luck in fetching the data from the server-side.
Here is a working demo like below:
1.Model:
public class UserModel
{
public int Id { get; set; }
public string Name { get; set; }
}
2.View(remove Content-type):
<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = { 'listofusers': listofusers };
console.log(group);
$.ajax({
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>
3.Console.log(group):
4.Result:
Update:
Another way by using json:
1.View(change group from JSON.stringify({ 'listofusers': listofusers });
to JSON.stringify(listofusers);):
<script>
var listofusers = [
{ id: 1, name: 'aaa' },
{ id: 2, name: 'bbb' },
{ id: 3, name: 'ccc' }
];
var group = JSON.stringify(listofusers);
console.log(group);
$.ajax({
contentType:"application/json",
dataType: 'json',
type: "POST",
url: "/home/GetMesssage",
data: group,
success: function (data) {
console.log("output : " + JSON.stringify(data));
},
error: function (data) {
console.log("error : " + JSON.stringify(data));
},
});
</script>
2.Controller(add FromBody):
[HttpPost]
public IActionResult GetMesssage([FromBody]List<UserModel> listofusers)
{
//...
}
You can try this one.
First stringify the parameter that you want to pass:
$.ajax({
url: url,
type: "POST",
data: {
listofusers: JSON.stringify(listofusers),
},
success: function (data) {
},
error: function (error) {
}
});
Then in your controller:
[HttpPost]
public IActionResult GetMesssage(string listofusers)
{
var jsonModel = new JavaScriptSerializer().Deserialize<object>(listofusers); //replace this with your deserialization code
}
What we're doing here is passing your object as a string then deserializing it after receiving on the controller side.
Hope this helps.
I found the solution to my problem guys, but I just want a clarification that maybe there's a work around or another solution for this one.
I've studied the data passed by "JSON.stringify();" from AJAX() and it's somehow like this.
"[[{\"ID\":0,\"UserID\":1014,\"Level\":\"support\",\"Department\":\"\",\"Facility\":\"Talisay District Hospital\",\"Firstname\":\"Joseph\",\"Middlename\":\"John\",\"Lastname\":\"Jude\",\"LoginStatus\":false,\"IPAddress\":\"192.168.110.47:12347\"},{\"ID\":0,\"UserID\":1014,\"Level\":\"support\",\"Department\":\"\",\"Facility\":\"Talisay District Hospital\",\"Firstname\":\"Joseph\",\"Middlename\":\"John\",\"Lastname\":\"Jude\",\"LoginStatus\":false,\"IPAddress\":\"192.168.110.47:15870\"}]]"
to which I was wondering that if the JSON format is a factor in parsing the data from the controller side. (Which of course is stupid since there's only one JSON format. (or maybe there's another, if there is, can you please post some source for reference.))
so I tried Serializing a Dummy Data in my model in "JsonConvert.Serialize()" Method and the output JSON data is like this.
[{"ID":0,"UserID":1014,"Level":"support","Department":"","Facility":"Talisay District Hospital","Firstname":"Joseph","Middlename":"John","Lastname":"Jude","LoginStatus":false,"IPAddress":"192.168.110.47:12347"},{"ID":0,"UserID":1014,"Level":"support","Department":"","Facility":"Talisay District Hospital","Firstname":"Joseph","Middlename":"John","Lastname":"Jude","LoginStatus":false,"IPAddress":"192.168.110.47:16709"}]
and I tried sending the output JSON Data from JsonConvert.Serialize() Method to controller via AJAX() and it worked! And I feel so relieved right now as this problem was so frustrating already.
If there's something wrong with what I found, please respond with what might be wrong or correct. Thank you!
So, I have my JSON file, but I need to send a certain URL to my JSON aswell with a loop.
this is where I set everything:
function setMainObjectArray() {
var exercises = [];
var eBlocks = $('.eBlock');
eBlocks.each(function(i, eBlock) {
var exObject = {
word: $(eBlock).find('input.ExerciseGetWordInput').val(),
syllables: []
};
$(eBlock).find('input.syllable').each(function(j, syll) {
exObject.syllables.push($(syll).val());
});
exercises.push(exObject);
});
return exercises;
}
this is my ajax save function:
function saveExerciseAjaxCall() {
console.log(setMainObjectArray());
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: {
id: getUrlParameter('id'),
getExerciseTitle: $('#getExerciseTitle').val(),
language: $('#languageSelector').val(),
application: 'lettergrepen',
'main_object': {
title: $('#getExerciseTitle').val(),
language: $('#languageSelector').val(),
exercises: setMainObjectArray()
},
dataType: 'json'
}
}).done(function(response) {
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(errorThrown);
console.log(textStatus);
});
}
and I think I need to loop something like this through my function setMainObjectArray()
var audioId = MEDIAARRAY.audio.lowercase.indexOf(exObject['exerciseGetWordInput'].toLowerCase() + '.mp3');
var audio_link = '';
if (audioId > -1) {
exObject['audio'] = 'https://TheUrlServer' + MEDIAARRAY.audio.path + MEDIAARRAY.audio.files[audioId];
}
But I have no idea how to implement this into my function setMainObjectArray. I am not entirely sure if the loop is even written the correct way, i'm quite new to javascript and from there on to put it in my ajax call (since it's a link).
I have the following script. It runs, it passes the variables to the controller, the controller executes correctly, but for whatever reason the success function does not fire and therefore does not refresh my html. Instead the error fires off. Nothing is jumping out at me as to the cause. Thanks for the help!
$(function() {
$("#btnUpdateTick").unbind('click').click(function () {
var currenttick =
{
"TicketID":#Html.Raw(Json.Encode(Model.TicketID)),
"Title": $("#Title").val(),
"Creator": $("#Creator").val(),
"StatusID": $("#StatusID").val(),
"Description": $("#Description").val(),
"newComment":$("#txtAddComment").val(),
Cat:
{
"CatID":$("#ddCurrTickCat").val()
}
}
//var newcomment = $("#txtAddComment").val();
var conv = JSON.stringify(currenttick);
$.ajaxSetup({cache:false});
$.ajax({
url: '#Url.Action("UpdateTicket", "HelpDesk")',
data: JSON.stringify({ticket:currenttick}),
type: "POST",
dataType: "json",
contentType: "application/json",
success: function (data) {
$("#loadpartial").html(data);
},
error: function (data){alert("turd")}
});
});
});
My controller:
[HttpPost]
public PartialViewResult UpdateTicket(Tickets ticket)
{
////Tickets.UpdateTicket(currenttick);
if (ticket.newComment != "")
{
Comments.addCommentToTicket(ticket.TicketID, ticket.newComment,UserPrincipal.Current.SamAccountName.ToString());
}
Tickets model = new Tickets();
ViewBag.CategoryList = Category.GetCategories();
ViewBag.StatusList = TicketStatus.GetStatusList();
model = Tickets.GetTicketByID(ticket.TicketID);
model.TicketComments = new List<Comments>();
model.TicketComments = Comments.GetCommentsForTicketByID(ticket.TicketID);
//model.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
//ViewBag.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
return PartialView("TicketDetails", model);
}
Your controller is returning a view instead of json. You should be returning a JsonResult instead. Try this:
[HttpPost]
public JsonResult UpdateTicket(Tickets ticket)
{
////Tickets.UpdateTicket(currenttick);
if (ticket.newComment != "")
{
Comments.addCommentToTicket(ticket.TicketID, ticket.newComment,UserPrincipal.Current.SamAccountName.ToString());
}
Tickets model = new Tickets();
ViewBag.CategoryList = Category.GetCategories();
ViewBag.StatusList = TicketStatus.GetStatusList();
model = Tickets.GetTicketByID(ticket.TicketID);
model.TicketComments = new List<Comments>();
model.TicketComments = Comments.GetCommentsForTicketByID(ticket.TicketID);
//model.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
//ViewBag.TicketComments = Comments.GetCommentsForTicketByID(ticketID);
return Json(model);
}
If you want to return Partial view from ajax call then modify ur ajax request as :
$.ajax({
url: '#Url.Action("UpdateTicket", "HelpDesk")',
data: JSON.stringify({ticket:currenttick}),
type: "POST",
dataType: "html",
success: function (data) {
$("#loadpartial").html(data);
},
error: function (data){alert("turd")}
});
Now "data" in ur success function will have html returned from PartialViewResult().
What I'm trying to do is possibly quite simple, however beeing not very familiar with jQuery I can't figure out how to do it.
I want to send some Data as JSON to an ASP.NET Controller. The Data contains some Strings and a list of Objects.
The Code would look somewhat like this:
View:
$(document).ready(function () {
var stuff = [
{ id: 1, option: 'someOption' },
{ id: 2, option: 'someOther' },
{ id: 3, option: 'anotherOne' }
];
things = JSON.stringify({ 'things': things });
var dataRow = {
'String1': 'A String',
'String2': 'AnotherOne'
}
dataRow = JSON.stringify(dataRow);
var sendData = dataRow + things;
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Backend/DoStuffWithStuff',
data: sendData,
success: function () {
alert('Success!');
},
failure: function (response) {
alert('Fail! :(');
}
});
});
Controller:
public class Stuff
{
public int id { get; set; }
public string option{ get; set; }
}
public void DoStuffWithStuff(string String1, String2, List<Thing> things)
{
//Do my Stuff
}
Any Ideas would be great! :)
You do not need to stringify the json data.
You just create an object you van to send and than
var jsonObject = {
'string' : 'string',
'object' : {
'stirng': 'string'
}
};
$.ajax({type: "POST", url: DotNetScript, data: jsonObject})
.done(function(dataBack){
//what to do with data back
});
It actually doesn't look too bad so far! Just a few things...
[HttpPost]
public void DoStuffWithStuff(string String1, String2, List<Stuff> things)
{
//Do my Stuff
}
In here, you don't actually give a type to string2. I'm going to assume this is a typo, but that's the minor part here.
Also, in that method, notice it has the HttpPost on the top. In your javascript here:
$.ajax({
...
type: 'POST',
...
});
You specify POST, so you must make the method support post (You could also get away with GET in this case by changing type to GET, then removing the attribute, but i'm not sure what your "stuff" entails...)
var stuff = [
{ id: 1, option: 'someOption' },
{ id: 2, option: 'someOther' },
{ id: 3, option: 'anotherOne' }
];
things = JSON.stringify({ 'things': things });
var dataRow = {
'String1': 'A String',
'String2': 'AnotherOne'
}
dataRow = JSON.stringify(dataRow);
var sendData = dataRow + things;
You didn't actually pass stuff into your method, which may be helpful...
Here is the ajax method re-written with the proper JSON pass (for what you're trying to do here).
$(document).ready(function () {
var stuff = [
{ id: 1, option: 'someOption' },
{ id: 2, option: 'someOther' },
{ id: 3, option: 'anotherOne' }
];
var dataRow = {
String1: 'A String',
String2: 'AnotherOne'
things: stuff
}
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Backend/DoStuffWithStuff',
data: sendData,
success: function () {
alert('Success!');
},
failure: function (response) {
alert('Fail! :(');
}
});
});
Trying to build xml out of form values. Earlier I was building it with the help of jQuery. jQuery has a bug and then I have to build XML with plain javascript. But Now when I submit the form, browser hangs and request does not reach the controller.
Controller
#RequestMapping(value="/save",method=RequestMethod.POST,consumes={"application/json", "application/xml", "text/xml", "text/plain"})
#ResponseBody public String handleSave(#RequestBody String formData)
{
System.out.println("comes here");
System.out.println(formData);
return "SUCCESS";
}
jQuery
$('form').submit(function () {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data: collectFormData(),
headers: {
"Content-Type":"application/xml"
},
dataType: 'application/xml',
success: function (data) {
alert('Success:'+data)
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('jqXHR:'+jqXHR+'\n'+'textStatus:'+'\n'+textStatus+'errorThrown:'+errorThrown);
}
});
return false;
});
CollectFormData
function collectFormData()
{
$rootElement = $('<FormXMLDoxument/>');
xmlDoc = document.implementation.createDocument("", "", null);
root = xmlDoc.createElement($('form').attr('name'));
$('form').find('div.section').each(function(index, section) {
sectionElement = xmlDoc.createElement($(section).attr('name'));
$(section).find('input').each(function(i, field) {
fieldElement = xmlDoc.createElement($(field).attr('name'));
fieldText=xmlDoc.createTextNode($(field).val());
fieldElement.appendChild(fieldText);
sectionElement.appendChild(fieldElement);
});
root.appendChild(sectionElement);
});
console.log((new XMLSerializer()).serializeToString(root));
return root;
}
Everything works fine if I implement collectFormData with jQuery but then I loose camel casing on element names.
Old collectFormData
function collectFormData()
{
$rootElement = $('<FormXMLDoxument/>');
$formElement = $.createElement($('form').attr('name'));
$('form').find('div.section').each(function(index, section) {
var $sectionElement = $.createElement($(section).attr('name'));
$(section).find('input').each(function(i, field) {
console.log($(field).attr('name'));
var $fieldName = $.createElement($(field).attr('name'));
$fieldName.text($(field).val());
$sectionElement.append($fieldName);
});
$formElement.append($sectionElement);
});
$rootElement.append($formElement);
console.log('Form XML is '+$rootElement.html());
return $rootElement.html();
}
My question related to jQuery bug