I'm trying to pass some specific data to C# code-behind using AJAX code, but couldn't managed to accomplish it. I've tried using plain text data type and json format, but neither of them are working for me.
The following error occurred when I tried to send the data using json method:
Internal Server Error
when using text method, there is no error appear and the code comes through the success function, but the actually the data is never sent to the method of the code-behind class
And this is the ajax code using json format:
function searchClicked(sCriterion) {
$.ajax({
type: "POST",
url: "TokenRegistration.aspx/GetSearchCritetrion",
data: "{creiterion : " + sCriterion + " }",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
});
}
And this is the ajax code using the text format:
function searchClicked(sCriterion) {
$.ajax({
type: "POST",
url: "TokenRegistration.aspx/GetSearchCritetrion",
data: sCriterion,
contentType: "application/text; charset=utf-8",
dataType: "text",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
});
}
Also here is the my code-behind method that the data should be sent to:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void GetSearchCritetrion(object selectedItem)
{
var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(selectedItem.ToString());
}
I've used the exact same ajax code in another project and it works perfectly, but here i'm not getting where the error is, so any suggestions please?
Replace your code like this
.aspx
<script>
$(function () {
function searchClicked(sCriterion) {
$.ajax({
type: "POST",
url: "Default.aspx/GetSearchCritetrion",
data: "{creiterion : " + sCriterion + " }",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
});
}
searchClicked("1");
});
</script>
and .cs file
[WebMethod]
public static String GetSearchCritetrion(String creiterion)
{
return "ok";
}
and App_Start
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Off;//Its may cause the error
routes.EnableFriendlyUrls(settings);
}
}
in your client side:
function searchClicked(sCriterion) {
//display the parameter
console.log(sCriterion);
if(sCriterion != "" || sCriterion != null)
{
var param= {
"selectedItem" : sCriterion
};
$.ajax({
type: "POST",
url: "TokenRegistration.aspx/GetSearchCritetrion",
data: param,
success: function(result) {
alert("We returned: " + result);
},
error: function(error){
console.log(error);
}
});
}
else
{
alert("No values!!");
}
}
server side:
[WebMethod]
public void GetSearchCritetrion(string selectedItem)
{
//add a breakpoint here....
}
Related
Jquery code:
$('#sendmessage').click(function () {
var data1 = $('#message').val();
$.ajax({
type: "POST",
url: "NotificationTest.aspx/OnSubmit",
data:'{name:'+data1+'}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " +
textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
// alert("We returned: " + result);
$("#noti_Button").val(result); *** here can not catch value***
}
});
});
C# code:
here is my c# code to getting value from jquery and return again.
string is not returned or other thing i ca not underatand.
[WebMethod]
public static string OnSubmit(string name)
{
return name;
}
ERRor:Internal server error.
Make your method static:
[WebMethod]
public static string OnSubmit(string name)
{
return name;
}
I'm trying to pass data to controller for further processing but I get null in controller, however debug of js (ajax) shows the number anyway. What might be the problem?
Ajax:
$('.toggler_btn').on('click', function (event)
{
var id = $(this).attr('data-id');
if ($(this).text() === '+') {
$.ajax({
url: "/List/GetSubItems",
type: "POST",
contentType: "html",
dataType: "text",
data: '{"id":"' + id + '"}', // here it show the data, like 5 or some other number
success: function (data)
{
$('.element_wrapper [data-id="' + id + '"]').html(data);
}
})
$(this).html('-');
}
else $(this).html('+');
});
Controller:
[HttpPost]
public ActionResult GetSubItems(string id) // here I get null
{
int pID = 0;
int.TryParse(id, out pID);
List<H_Table> list = new List<H_Table>();
foreach (var item in db_connection.H_Table.Where(i => i.PARENT_ID == pID))
{
list.Add(item);
}
return PartialView(list);
}
$('.toggler_btn').on('click', function (event) {
var id = $(this).attr('data-id');
if ($(this).text() === '+') {
$.ajax({
url: '/List/GetSubItems',
type: 'POST',
dataType: 'json',
data: '{"id":"' + id + '"}',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('.element_wrapper [data-id="' + id + '"]').html(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("responseText=" + XMLHttpRequest.responseText + "\n textStatus=" + textStatus + "\n errorThrown=" + errorThrown);
}
});
$(this).html('-');
}
else $(this).html('+');
});
Use this one just copy and paste
Change your content type to "text" and change the data as well.
Change data type to "application/json" and data to this :
data :{
id : id
}
Your AJAX request has set contentType: "html" but you are actually sending JSON (with data: '{"id":"' + id + '"}'). And your controller is receiving a string.
So either change your AJAX call to send a raw string:
contentType: "text",
data: { id: id }
...or update your controller to receive JSON. This latter can be achieved by creating something like this:
public ActionResult GetSubItems(ViewModel model)
public class ViewModel {
public string Id { get; set; }
}
EDIT: also, for reference, you might want to see the difference between contentType and dataType.
Good evening,
I'm trying to do a AJAX call in a C# page and I'm dealing with some problems.
My jQuery code is:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "conteudo.aspx/GetNewPost",
data: { ids: "<%=Request.QueryString["idconteudo"]%>" },
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (data) {
alert("ok");
}
});
});
And my code-behind is:
[WebMethod]
public static string GetNewPost(string ids)
{
// some code
return ids;
}
Does someone know what is going on?
PS: The error is Internal Server Error.
Please use code as below
Because you are using text data type from query string, you can make datatype as text
$(document)
.ready(function () {
var q = "<%=Request.QueryString["idconteudo"]%>";
alert(q);// just to check the value
// assuming that you had passed query string value
$.ajax({
type: "POST",
url: "conteudo.aspx/GetNewPost",
data: { "ids": q },
//contentType: 'application/json; charset=utf-8',
dataType: 'text',// data type should be text
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " +
XMLHttpRequest.toString() +
"\n\nStatus: " +
textStatus +
"\n\nError: " +
errorThrown);
},
success: function(data) {
alert("ok");
}
});
});
Edit 1 : If the Web Method is on ASPX page, you shall use below code, so that you get result in Json format
$(document)
.ready(function () {
var q = "<%=Request.QueryString["idconteudo"]%>";
//alert(q);
// just to check the value
// assuming that you had passed query string value
$.ajax({
type: "POST",
url: "conteudo.aspx/GetNewPost",
data: '{ids: "' + q + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " +
XMLHttpRequest.toString() +
"\n\nStatus: " +
textStatus +
"\n\nError: " +
errorThrown);
},
success: function (result) {
alert("ok" + result.d);
}
});
});
try:
var idconteudo = "<%=Request.QueryString["idconteudo"]%>";
...
...
url: "conteudo.aspx/GetNewPost",
data: "{ids: \"" + idconteudo + "\"" }",
contentType: 'application/json; charset=utf-8',
...
...
From what you have given us with your post, I see two things that are incorrect and one other thing that may have just not been posted in your question, but it is in fact in your real source.
1) Your data is written wrong. It should be:
$(document).ready(function () {
var test = "<%=Request.QueryString["idconteudo"]%>";
$.ajax({
type: "POST",
url: "conteudo.aspx/GetNewPost",
data: { 'ids' : test }, // the ids needs to have quotes to be correct syntax
dataType: 'text',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (data) {
alert("ok");
}
});
});
2) You say it's a POST but your method isn't decorated with the [HttpPost] Annotation.
3) Your dataType is set to 'json' but your method is returning a string.. so 'json' should be changed to 'text'.
Hope this helps!
I have problem with saving new record to the database, using C# controller.
Here is the JS code:
<script type="text/javascript">
function save1(input1, input2) {
var lol = document.getElementById('input1').value + " " + document.getElementById('input2').value;
alert(lol);
$.ajax({
url: ' #Url.Action("Saving", "LanguagesController")',
type: "POST",
data: { name: input1, level: input2 },
dataType: "text",
success: function (result) {
alert("Yess!!")
},
error: function (request, error) {
alert("Noooo : " + error);
}
});
alert("End of function");
}
Here is my C# controller:
[HttpPost]
public ActionResult Saving(string name, string level)
{
Language lan = new Language();
lan.name_of_language = name;
lan.level_of_difficality = level;
db.Languages.Add(lan);
db.SaveChanges();
return View(db.Languages.ToList());
}
Thank you in advance
I can't see anything wrong with what you have (but are you really expecting text back?), but this would be better:
HTML:
<a class="btn" data-url="#Url.Action("Saving","LanguagesController")">Save</a>
Javascript:
$('a[data-url]').on('click',function() {
var url=$(this).data('url');
var input1=$('something').val();
var input2=$('somethingelse').val();
save1(url,input1,input2);
});
function save1(url, input1, input2) {
var lol = document.getElementById('input1').value + " " + document.getElementById('input2').value;
alert(lol);
$.ajax({
url: url,
type: "POST",
data: { name_of_language: input1, level_of_difficality: input2 },
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function(result) {
alert("Yess!!")
}).fail(function(jqXHR, textStatus, errorThrown) {
alert("Noooo : " + textStatus + " " + errorThrown);
});
alert("End of function");
}
C#:
[HttpPost]
public JsonResult Saving(Language lan)
{
db.Languages.Add(lan);
db.SaveChanges();
return Json(db.Languages.ToList());
}
PS. difficality is not spelled correctly.
Your problem is you're passing a control rather than a value
function save1(input1, input2) {
var lol = document.getElementById('input1').value + " " + document.getElementById('input2').value;
alert(lol);
$.ajax({
url: ' #Url.Action("Saving", "LanguagesController")',
type: "POST",
data: { name: getElementById('input1').value , level: getElementById('input2').value }, //changed from control to value
contentType: "application/json; charset=utf-8", // define contenttype
dataType: "json", //and the type you're expecting
success: function (result) {
alert("Yess!!")
},
error: function (request, error) {
alert("Noooo : " + error);
}
});
alert("End of function");
}
And at server side, you must get your model as input:
[HttpPost]
public ActionResult Saving(Language lan)
{
db.Languages.Add(lan);
db.SaveChanges();
return db.Languages.ToList();
}
I have the following code and want to use it as an object.
How to i access the properties of the object? currently i am always getting undefined!
function getLoggerInfo()
{
$.ajax({
url: "data.json",
type: "GET",
data: {emGetInfo: "logger"},
dataType: "json",
success: function(response){
//alert("1: " + this.loggerName);
loggerName = response.emGetInfo[0].loggerName;
protocol = response.emGetInfo[0].protocolVersion;
$("#console").text("Logger Name: " + loggerName + " - Protocol Version: " + protocol);
return;
},
error: function(jqXHR, textStatus, errorThrown){
$("#console").text("ERROR: AJAX errors. " + jqXHR + " : " + textStatus + " : " + errorThrown);
return;
},
statusCode: {
404: function() {
$("#console").text("404: The requested JSON file was not found.");
return;
}
}
});
}
// get loggerName...
$(document).ready(function () {
// Get logger info event...
$("#ajax").click(function() {
var loggerInfo = new getLoggerInfo();
alert("Loggername: "+ loggerInfo.loggerName);
});
});
AJAX is asynchronous - so it does not return data ... the following is a (rough) outline of what happens when you use the $.ajax() function
The data is sent to the url
The browser continues - executing other code as required
When the url (called in step 1) finishes being processed the success callback is executed.
Step 3 could be 1 second, 10 seconds, 5 minutes later
you should process the request in the success callback :
$.ajax({
url: "data.json",
type: "GET",
data: {emGetInfo: "logger"},
dataType: "json",
success: function(response){
// process here
loggerName = response.emGetInfo[0].loggerName;
alert(loggerName);
}
});