c# - Problems during AJAX call with Jquery - javascript

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!

Related

The jqXHR object returned by the ajax call

Either the success event or the error event will get the returned jqXHR object, but I can only access the jqXHR object in the error event.
$.ajax({
type: 'POST',
url:'https://fakeurl',
data: formData,
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
success: function(textStatus, jqXHR) {
alert('textStatus: ' + textStatus + ' jqXHR.status: ' + jqXHR.status);
},error: function(jqXHR) {
console.log('jqXHR.status: ' + jqXHR.status);
}
});
The output in error event got jqXHR.status: 0.
And the output in success event is textStatus: [object Object] jqXHR.status: undefined.
From the jQuery ajax docs:
success
Type: Function( Anything data, String textStatus, jqXHR jqXHR )
...
So, if you want to access the jqXHR object in the success callback, you'll need to define three parameters for the function to accept like so:
success: function(data, textStatus, jqXHR) {
alert('data: ' + data + 'textStatus: ' + textStatus + ' jqXHR.status: ' + jqXHR.status);
if you want to get back the submitted data, the first argument of success function is the submitted data and the second is the textStatus, the third one for jqXHR which that has all the properties of the response object
$.ajax({
type: 'POST',
url:'https://fakeURL',
data: formData,
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
success: function(data, textStatus, jqXHR) {
alert('textStatus: ' + textStatus + ' jqXHR: ' + jqXHR.status);
},error: function(error) {
console.log('error.status: ' + error.status);
}
});

can not pass and retrive parameter value when calling an aspx file using jquery ajax;

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;
}

unable to pass data to c# code using AJAX

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....
}

AJAX cross-domain request IE 8+

How to correct rewrite the Ajax request to make it work in IE 8 +, using XDomainRequest?
$.ajax({
type: "GET",
url: url,
success: function(xml) {
$('.post-msg').append(processXml(xml, config));
},
error: function(jqXhr, textStatus, errorThrown) {
var errorMsg = "Request on url: " + url + " failed: " + textStatus + " error:" + errorThrown;
alert(errorMsg);
}
});
Use this plugin for IE8-9 Xdomain support.
https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest

jQuery.ajax converter not called

I'm having trouble with jQuery.ajax converters - I can't get my converter to be called.
I've got this jQuery AJAX code (simplified for the question) :
$.ajax({
url: "http://myurl/myservice",
dataType: "JSONP",
cache: false,
success: function (data, textStatus, jqXHR) { /* do stuff */ },
error: function (jqXHR, textStatus, errorThrown) { /* do stuff */ },
timeout: 5000,
converters: { "JSONP": myConversionFunction }
});
When I use this code, the converter function myConversionFunction isn't being called. I want to use the converter to convert dates in the response as show in other SO questions but just can't get it firing.
Using fiddler I've checked the response and it is JSONP, with content type "application/x-javascript".
Any ideas what I'm doing wrong?
Thanks,
Chris.
I think you can't overwrite jQuery's default converters like json. Introduce your own converter instead (and include text in your specifier, as in this case it's a conversion from text to your output):
$.ajax({
url: "http://myurl/myservice",
dataType: "jsonp myConversion",
cache: false,
success: function (data, textStatus, jqXHR) { /* do stuff */ },
error: function (jqXHR, textStatus, errorThrown) { /* do stuff */ },
timeout: 5000,
converters: {
"text myConversion": function(value) {
console.log("pre-processing...");
/* do stuff */
return value;
}
}
});
​
I use code like this to manage the 'd' data of asp.net:
$.ajaxSetup({
data: "{}",
dataType: "jsonp",
type: "POST",
contentType: "application/json",
converters:
{
"json jsonp": function(msg)
{
return msg.hasOwnProperty('d') ? msg.d : msg;
}
},
error: function(xhr, textStatus, errorThrown)
{
var errorMessage = "Ajax error: " + this.url + " : " + textStatus + " : " + errorThrown + " : " + xhr.statusText +
" : " + xhr.status;
if (xhr.status != "0" || errorThrown != "abort")
{
alert(errorMessage);
}
}
});
perhaps you need to make it lower case like:
converters:
{
"json jsonp": function(msg)
{
return yourfunction(msg);
}
}

Categories