jQuery, ajax POST method success returns: Undefined - c#

my script code:
$('#btnSave').click(function() {
var pageUrl = '<%= ResolveUrl("~/TestPage.aspx/SystemEdit")%>';
var ip = $('#editIP').text();
var loc = $('#txtBay').val();
var team = $('#txtTeam').val();
var port = $('#txtPort').val();
var xcel = "", office = "", moni = "";
var parameter={ "ip": ip, "loc": loc, "team": team, "port": port, "excel": xcel, "office": office, "monitor": moni}
$.ajax({
type: 'POST',
url: pageUrl,
data: JSON.stringify(parameter),
contentType: 'json',
success: function(data) {
alert(data);
},
error: function(data,success,error) {
alert("Error:" +error);
}
});
});
my code behind c# code is:
[WebMethod]
public static string SystemEdit(string ip, string loc,string team, string port, string excel,string office, string monitor)
{
return "The Current Time is: "+ DateTime.Now.ToString();
}
my page name is : TestPage.aspx
While clicking the save button I'm getting 'undefined'. I'm not getting the current time from code behind c#.

You need to return json result as below:
return JsonConvert.SerializeObject("The Current Time is: "+ DateTime.Now.ToString());
also put below attribute above method:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
And as you specified json format you should write:
contentType: "application/json; charset=utf-8",
By the way you should use a Webservice here!

I guess setting a json content type should be done this way:
contentType: 'application/json',

If you are using vs2013 then make sure you disable the below line in route.config to get things working.
'settings.AutoRedirectMode = RedirectMode.Permanent
My VB Code Behind:
<WebMethod()>
Public Shared Function GetReport(ByVal Data As String) As String
Try
Return "Hello" + Data
Catch ex As Exception
Return "Failed"
End Try
End Function
Js Script :
$('#btnSave').click(function () {
var char = $(this).text();
var SendData = {};
$.ajax({
type: "POST",
url: "TEST.aspx/GetReport",
data: JSON.stringify(SendData),
data: "{ 'Data': '" + char + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#lbl_test').text(data.d);
},
error: function (data, success, error) {
alert("Error:" + error);
}
});
});

Related

how to resolve ajax post jquery in asp.net page?

when i add alert(file) line after ajax block code work but when i remove alert(file) code not work .
this is work fine :
function Delete(file) {
$.ajax({
type: "POST",
url: "Image.aspx/Delete",
data: '{file: "' + file + '" }',
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
$("#statusBox").text("ok"); //alert(response.d);
},
error: function (response) {
$("#statusBox").text("error"+response.text);
// alert(response.status + ' ' + response.statusText);
},
complete: function () {
// $("#statusBox").text("completed");
}
});
alert(file);
}
if i remove alert(file) line code web method not work.
this my c# asp.net code web method :
[WebMethod]
public static string Delete(string file)
{
try
{
// int lastSlash=file.ind
// Lesson learnt - always check for a valid URI
if (Uri.IsWellFormedUriString(file, UriKind.Absolute))
{
Uri uri = new Uri(file);
file = (uri.LocalPath);
}
//file= file.Remove(0)
//File.Delete(file);
File.Delete(HttpContext.Current.Server.MapPath(#"~\" + file.Replace("/", #"\")));
}
catch (Exception ex)
{
return ex.Message;
}
return "ok";
}
You're sending the request asynchronously,try to make false asynchronous.
for more information take a look at this
I see three (3) errors in your code:
data: '{file: "' + file + '" }',
datatype: "jsondata",
async: "true",
You are not sending a js object to the server.
jsondata is not a valid datatype.
async is a boolean and you are instead assigning a string value.
So the solution from here is:
data: {file: file }, // send a object
datatype: "text", // change to text because you are returning "ok" string
async: true, // remove the quotes
Another suggestion is try with default headers:
contentType: "application/json; charset=utf-8",
Try removing this line and see.

Object obect error on jquery ajax request on dropdown change?

I'm using jquery ajax on dropdown change function.The problem is that even before hitting the url mentioned in the ajax request I'm getting Object object error.
The ajax request is as follows
$("#locationList").change(function () {
var locationNo = document.getElementById('<%=locationList.ClientID%>').value;
$.ajax({
url: "HealthReport.aspx/GetCashsafes",
data: "{ 'Location': '" + locationNo + "'}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Success");
response($.each(data.d, function (key, value) {
$("#CashSafeList").append($("<option></option>").val(value.CashsafeId).html(value.CashsafeDisplaySerialNo));
}));
},
error: function (result) {
alert(result);
$("#CashSafeList").append($("<option></option>").val("-1").html("Select one"));
}
});
});
The server side code is as follows
[WebMethod]
public static string GetCashsafes(string Location)
{
Decimal userId = (Decimal)AMSECSessionData.userId;
List<Cashsafe> lstCashSafe = DropDown.getCashSafeListLocationwise(userId, Convert.ToDecimal(Location));
List<CashSafeSelect> lstCashSafeSelect = new List<CashSafeSelect>();
lstCashSafeSelect = lstCashSafe.Select(item => new CashSafeSelect()
{
CashsafeId=(decimal)item.CashsafeId,
CashsafeSerialNo=item.CashsafeSerialNo.ToString()
}).Distinct().ToList();
System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string sjson=jSearializer.Serialize(lstCashSafeSelect);
return sjson;
}
I've checked the string sjson and the data is returning correctly in json format.
Since the error is showing even before the url is hit,i'm confused on how to proceed further.
Any help will be appreciated.
Change the data like this
data: JSON.stringify({ 'Location': locationNo }),
Then your code will look like
$("#locationList").change(function () {
var locationNo = document.getElementById('<%=locationList.ClientID%>').value;
$.ajax({
url: "HealthReport.aspx/GetCashsafes",
data: JSON.stringify({ 'Location': locationNo }),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Success");
response($.each(data.d, function (key, value) {
$("#CashSafeList").append($("<option></option>").val(value.CashsafeId).html(value.CashsafeDisplaySerialNo));
}));
},
error: function (result) {
alert(result);
$("#CashSafeList").append($("<option></option>").val("-1").html("Select one"));
}
});
});
Edit
Since your dataType is json, you should return json, not string. Change your server side code like this,
[WebMethod]
public static List<CashSafeSelect> GetCashsafes(string Location)
{
Decimal userId = (Decimal)AMSECSessionData.userId;
List<Cashsafe> lstCashSafe = DropDown.getCashSafeListLocationwise(userId, Convert.ToDecimal(Location));
List<CashSafeSelect> lstCashSafeSelect = new List<CashSafeSelect>();
lstCashSafeSelect = lstCashSafe.Select(item => new CashSafeSelect()
{
CashsafeId=(decimal)item.CashsafeId,
CashsafeSerialNo=item.CashsafeSerialNo.ToString()
}).Distinct().ToList();
return lstCashSafeSelect;
}
You dont have to serialize those lists
Issue solved,Thanks to every one who replied especially #Anoop.
Issue was that I've set Autopostback=true for the dropdown where the ajax call is made.I've removed the autopostback property of the dropdown and now the code is working fine.
I wonder how a fresh day,clear mind helps to solve the issues.

Jquery to ashx not working event not fired

I am using the below code to call a ashx page. But it's not working for me. I have place my code here. I always got the error message message "Request Failed". Please help me..
<script type="text/javascript">
function CallLoginHandler(user, pass) {
alert(user);//Got value
alert(pass);//Got Value
$(function(){
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx?MainPage=GetUserDetails&Type=2&user=" + user + "&pass=" + pass + "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnComplete,
error: OnFail
});
return false;
});
}
function OnComplete(result) {
alert([result.Id, result.Name, result.Age, result.Department]);
}
function OnFail(result) {
alert('Request Failed');
}
</script>
remove these lines:
$(function(){ // <----remove this
return false; // and this
}); // and this too
Update to this function:
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx", // updated url
data: { // pass your data like this since type is post
MainPage:"GetUserDetails",
Type:2,
user:user,
pass:pass
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnComplete,
error: OnFail
});
}
and also your url is not correct:
url: "../handler/JQGridHandler...... + pass + "",
// --here you have a blank `""` after pass-----^
and since your type: "post" so you can pass the data like this:
data: {
MainPage:"GetUserDetails",
Type:2,
user:user,
pass:pass
},
Separate your string into a javascript object to be encoded and sent to the server as JSON based on your content type. Also, get rid of $(function(){ in your function call, it's useless here.
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx';
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
MainPage: 'GetUserDetails',
Type: 2,
user: user,
pass: pass
}
success: OnComplete,
error: OnFail
});
If this doesn't work, then the issue is likely one of the following:
The URL address is wrong
The server is evaluating a GET as opposed to a POST request
The server expects, application/x-www-form-urlencoded but you've declared it's json
You have a routing issue
Note: Do not send your user and pass in query string.
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx",
data: {
MainPage: 'GetUserDetails',
Type: 2,
user: user,
pass: pass
},
// DO NOT SET CONTENT TYPE to json
// contentType: "application/json; charset=utf-8",
// DataType needs to stay, otherwise the response object
// will be treated as a single string
dataType: "json",
success: OnComplete,
error: OnFail
});
});
}
Your handler.ashx file
using System;
using System.Web;
using Newtonsoft.Json;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string user= context.Request.Form["user"];
//.....
var wrapper = new { d = myName };
// in order to use JsonConvert you have to download the
// Newtonsoft.Json dll from here http://json.codeplex.com/
context.Response.Write(JsonConvert.SerializeObject(wrapper));
}
public bool IsReusable
{
get
{
return false;
}
}
}
source

Pass html string to server side with Jquery Ajax

i have seen a lot of answers in this site that have helped me a lot but in this one i need to ask guys to help me out.
i have a textarea as a Html editor to pass html content to the server and append it to a newly created Html page( for user POST,etc), but jquery or ASP.NET does not accept the Html content passed by jquery through data: {}
--For Jquery:
$("#btnC").click(function (e) {
e.preventDefault();
//get the content of the div box
var HTML = $("#t").val();
$.ajax({ url: "EditingTextarea.aspx/GetValue",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{num: "' + HTML + '"}', // pass that text to the server as a correct JSON String
success: function (msg) { alert(msg.d); },
error: function (type) { alert("ERROR!!" + type.responseText); }
});
and Server-Side ASP.NET:
[WebMethod]
public static string GetValue(string num)
{
StreamWriter sw = new StreamWriter("C://HTMLTemplate1.html", true);
sw.WriteLine(num);
sw.Close();
return num;//return what was sent from the client to the client again
}//end get value
Jquery part gives me an error:
Invalid object passed in and error in
System.Web.Script.Serialization.JavascriptObjectDeserializer.
It's like jquery doesnt accept string with html content.what is wrong with my code ?
Pass it like this
JSON.stringify({'num':HTML});
You have to stringify the content to JSON properly. HTML may contain synataxes that would make the JSON notation invalid.
var dataToSend = JSON.stringify({'num':HTML});
$.ajax({ url: "EditingTextarea.aspx/GetValue",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: dataToSend , // pass that text to the server as a correct JSON String
success: function (msg) { alert(msg.d); },
error: function (type) { alert("ERROR!!" + type.responseText); }
});
You can use this
var HTML = escape($("#t").val());
and on server end you can decode it to get the html string as
HttpUtility.UrlDecode(num, System.Text.Encoding.Default);
Make sure JSON.stringify,dataType: "json" and, contentType: "application/json; charset=utf-8", is there in the ajax call.
[HttpPost]
public ActionResult ActionMethod(string para1, string para2, string para3, string htmlstring)
{
retrun view();
}
$.ajax({
url: '/Controller/ActionMethod',
type: "POST",
data: JSON.stringify({
para1: titletext,
para2: datetext,
para3: interchangeNbr.toString(),
htmlstring : messageText.toString()
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
cache: false,
success: function successFunc(data) {
},
error: function errorFunc(jqXHR) {
$('#errroMessageDiv').css({ 'color': 'red' }).text(jqXHR.message).show();
}
});

can not invoke webmethod to save handsonTable

I want to save handsontable data into json file,I have a javas cript method to get all data from handsontable as
$('button[name=save]').click(function () {
var str = handsontable.getData();
var value = JSON.stringify(str);
$.ajax({
url: "WebService.asmx/getData",
data: { 'data': value },
dataType: 'json',
contentType: 'application/json',
type: 'POST',
success: function (res) {
if (res.result == 'ok') {
alert('Data saved');
}
else {
alert('Save error');
}
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
}
});
});
But I am not able to invoke WebService.asmx/getData(List data) .
public string getData(List<String> data)
{
return "";
}
What I need to pass in data:??...Please help.
data: { 'data': str },
dataType: 'json',
contentType: 'application/json',
With the contentType setting you are telling the server that you are sending JSON data, but you aren't. { 'data': str } is not a JSON string; it is a standard Javascript object literal. You are invoking the default jQuery behaviour for creating HTTP requests. This means you're sending a regular HTTP request, something like:
?data=thedata
To send actual JSON data, you need to call JSON.stringify:
data: JSON.stringify({ 'data': str }),
dataType: 'json',
contentType: 'application/json',
you must write before methode
[WebMethod]
and change parameters of method from List to string
then you can split it

Categories