SyntaxError: JSON.parse: unexpected character error unexpected token < - c#

i have a html button with "button-account" name in html body and want update aspx page with ajax when user click the button
I get this error in google chrom
SyntaxError: JSON.parse: unexpected character
and this in fire fox
SyntaxError: JSON.parse: unexpected character
Here's my Code
<script type="text/javascript" >
$(document).ready(function () {
$("#button-account").bind("click", "accountRegister");
function accountRegister() {
var waitObj = "<span class='wait' > <img src='Resource/Images/loading.gif' alt='' /> </span>";
var user = $("[name='username']").val();
var pass = $("[name='password']").val();
var dataObj = {
"username": user,
"password": pass,
};
$.ajax({
type: "POST",
url: "Checkout.aspx/login",
data: dataObj,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforSend: function () {
$(this).attr("disabled", "true");
$(this).after(waitObj);
},
success: function (msg) {
// Replace the div's content with the page method's return.
alert("success");
$("#checkout").slideUp("slow");
$("#payment-address").slideDown("slow");
},
error: function (msg) {
alert("error");
},
complete: function () {
$(this).attr("disabled", "false");
$(".wait").remove();
},
});
}
});
</script>
and here's my webmethod
[WebMethod]
public static string login()
{
//bool UserIsValid = false;
//string userName = "";
//string pass = "";
//MembershipUser u = Membership.GetUser(userName);
//pass = u.GetPassword();
//if (UserIsValid)
//{
// // returnAsHtml = "true";
//}
//else
//{
// //returnAsHtml = "use is not valid";
//}
JavaScriptSerializer js = new JavaScriptSerializer();
string result = js.Serialize("{ a:'1' }");
return result;
}
and fiddler return 200 status.
but return html. i know this is my mistake. how solve it?
any help is appriciate...

The server probably returns an error-page (e.g. "<html> ...") instead of the JSON response you expected.
Use fiddler, chrome's developer tools or a similar tool to check what the exact answer is, that the server returns.
In response to your comments:
Check what the content of the returned HTML page is. It's probably an error caused by your server-side code (e.g. an unhandled exception) or the server-side configuration.

Change this
var dataObj = {
"username": user,
"password": pass,
};
To this
var dataObj = {
"username": user,
"password": pass
};
You have an extra comma , ("password": pass,) after pass, so it is not able to serialize it properly.
Edit:
Try this
[WebMethod]
public static string login()
{
//bool UserIsValid = false;
//string userName = "";
//string pass = "";
//MembershipUser u = Membership.GetUser(userName);
//pass = u.GetPassword();
//if (UserIsValid)
//{
// // returnAsHtml = "true";
//}
//else
//{
// //returnAsHtml = "use is not valid";
//}
//JavaScriptSerializer js = new JavaScriptSerializer();
//string result = js.Serialize("{ a:'1' }"); // no need to serialize
return "{ a:'1' }";
}

so sorry!!!
in other section a called this
$('#button-login').live('click', function () {
$.ajax({
url: 'Checkout.aspx?login',
type: 'post',
data: $('#checkout #login :input'),
dataType: 'json',
beforeSend: function () {
$('#button-login').attr('disabled', true);
$('#button-login').after('<span class="wait"> <img src="Resource/Images/loading.gif" alt="" /></span>');
},
complete: function () {
$('#button-login').attr('disabled', false);
$('.wait').remove();
},
success: function (json) {
$('.warning, .error').remove();
if (json['redirect']) {
location = json['redirect'];
} else if (json['error']) {
$('#checkout .checkout-content').prepend('<div class="warning" style="display: none;">' + json['error']['warning'] + '</div>');
$('.warning').fadeIn('slow');
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});

Related

Ajax call to async method returning file successfully but success/complete part of an Ajax request is not getting executed

I am trying to export selected records in to a file and reload the page to update the records in a current view. I am calling web api asynchronously to get all the records. An AJAX call is executing an action in a controller successfully and returning expected data without any error but none of the 'success', 'complete' or 'error' part of ajax function is executing. There are no errors in a developer tool of the browser, no exception, nothing unusual so its getting trickier for me to investigate this issue further. Can I request your a suggestions on this please? Thanks
View :
#Html.ActionLink("Export records", "Index", null, new { Id = "myExportLinkId")
Script :
$("a#myExportLinkId").click(function (e) {
var selected = "";
$('input#myCheckBoxList').each(function () {
if (this.checked == true) {
selected += $(this).val() + ',';
}
});
if (selected != "") {
$.ajax({
url: '/MyController/MyAction',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
'MyString': 'stringValue'
},
success: function (data) {
alert("success");
},
error: function () {
alert("error");
}
});
})
And the action/method looks like this :
[HttpGet]
public async Task<ActionResult> ExportNewOrders(string OrderIdString)
{
//code to create and store file
//actually want to send the file details as json/jsonResult but for testing only returning
//string here
return Json( "Success", "application/json", JsonRequestBehavior.AllowGet);
}
Finally I have resolved this with Promisify functionality of an AJAX call. Obviously the json response I was returning had an issue so I have replaced
return Json( "Success", "application/json", JsonRequestBehavior.AllowGet);
to
return new JsonResult(){
Data = new { success = true, guid = handle, fileName = exportFileName },
ContentType = "application/json",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
which has fixed the bug and the success function of ajax call got executed.
But other than this there were issues to wait until the file download (which involved encryption decryption, server validations etc) completes and then refresh the page. This I have resolved by implementing an ajax call with Promisify fuctionality. You can find codepen example here and the original post here.
Here is the complete code.
View/HTML
#Html.ActionLink("Export", "yourActionName", null, new { Id = "exportRequest", #onclick = "letMeKnowMyFileIsDownloaded();" })
Script/Ajax
function letMeKnowMyFileIsDownloaded() {
return new Promise(function (resolve, reject) {
$("a#exportRequest").on("click", function () {
$.ajax({
url: this.href + "?param=whatever params you want to pass",
dataType: "json",
data: {
'param1': 'value'
},
success: function (data) {
var a = document.createElement("a");
var url = '/yourControllerName/Download?fileGuid=' + data.guid + '&filename=' + data.fileName;//window.URL.createObjectURL(data);
a.href = url;
a.download = data.fileName;
document.body.append(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
resolve(true);
},
error: function (error) {
reject(error);
}
});
});
});
}
letMeKnowMyFileIsDownloaded()
.then(function (bool) {
if (bool) {
//alert("File downloaded 👇");
window.location.reload(1);
}
})
.catch(function (error) {
alert("error");
});
I have used nuget package ClosedXML to handle excel file functionality. Using the stream to create and download the data in excel file without storing the file physically on the server.
And in the controller
//can be async or sync action
public async Task<ActionResult> Index(YourModel model)
{
//do stuff you want
var exportOrders = your_object;
//using DataTable as datasource
var dataSource = new DataTable();
//write your own function to convert your_object to your_dataSource_type
dataSource = FormatTypeToDataTable(exportOrders);
if (dataSource != null && dataSource.Rows.Count > 0)
{
//install ClosedXML.Excel from nuget
using (XLWorkbook wb = new XLWorkbook())
{
try
{
var handle = Guid.NewGuid().ToString();
wb.Worksheets.Add(dataSource, "anyNameForSheet");
string exportFileName = "yourFileName" + ".xlsx";
MemoryStream stream = GetStream(wb);
TempData[handle] = stream; exportFileName);
return new JsonResult()
{
Data = new { success = true, guid = handle, fileName = exportFileName },
ContentType = "application/json",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
catch (Exception ex)
{
//ModelState.AddModelError("", ex.Message);
}
}
}
}
public virtual ActionResult Download(string fileGuid, string fileName)
{
if (TempData[fileGuid] != null)
{
var stream = TempData[fileGuid] as MemoryStream;
var data = stream.ToArray();
return File(data, "application/vnd.ms-excel", fileName);
}
else
{
return new EmptyResult();
}
}

Send a binary excel file data from memory stream and generic handler to client side and prompt save

Currently I am using JQuery AJAX and connect it to the Generic Handler (.ashx), inside the Generic Handler, I am doing the template for the Excel File that is going to save the computer (prompt save). i can achieve that while using the .aspx.cs , the reason I am doing from Generic Handler (.ashx), is because I don't know any way to hide the loading overlay after the dialog box for us to save to the computer is appear. (means the loading overlay just stick there). $(element).show() or $(element).hide() is to show or hide the loading overlay.
I am using EPPlus Library to generate the template for Excel File, however I don't know how to pass the object into client side and then prompt to save, it keeps gives me an error.
The problem I was encountered while using the Generic Handler is always gives me the parsererror message.
Here is the code that I am using:
JQuery AJAX:
var loading = $("#loading");
$("#template").click(function () {
loading.show();
$.ajax({
type: "POST",
url: "TemplateService.ashx?Month=" + $("#Month").val() + "&Year=" + $("#Year").val(),
data: {},
contentType: "application/json",
dataType: "json",
success: function (data) {
loading.hide();
console.log(data);
alert("Success");
},
error: function (xhr, text) {
loading.hide();
console.log(JSON.stringify(xhr.responseText));
console.log(JSON.stringify(text));
alert("There is a problem while processing your request");
}
});
});
Generic Handler (.ashx):
public class TemplateService : IHttpHandler, IRequiresSessionState
{
private int Month = 0;
private int Year = 0;
public void ProcessRequest(HttpContext context)
{
Month = Convert.ToInt32(context.Request.Params["Month"]);
Year = Convert.ToInt32(context.Request.Params["Year"]);
try
{
string MonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(Month);
string fileName = string.Format("{0} - {1} {2}.xlsx", "Excel Template", MonthName, Year);
using (var package = new ExcelPackage())
{
package.Export();
using (var stream = new MemoryStream())
{
context.Response.Clear();
context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
package.SaveAs(stream);
stream.WriteTo(context.Response.OutputStream);
context.Response.Write(stream);
}
}
}
catch (Exception)
{
ProcessResponse(context, Response());
}
}
private string Response(bool isSuccess = false)
{
string status = (isSuccess) ? Constant.SUCCESS : Constant.FAILED;
return JsonConvert.SerializeObject(new
{
Status = status
});
}
private void ProcessResponse(HttpContext context, string response)
{
context.Response.Clear();
context.Response.ContentType = "application/json";
context.Response.Write(response);
}
public bool IsReusable
{
get
{
return false;
}
}
}
Export function:
public void Export(this ExcelPackage package)
{
try
{
package.Workbook.Worksheets.Add("Excel Template");
var workSheet = package.Workbook.Worksheets["Excel Template"];
var columnNames = new string[]
{
"First Column",
"Second Column",
"Third Column"
};
var headerRow = new List<string[]>()
{
columnNames
};
var cells = workSheet.Cells[1, 1, 1, 3];
cells.LoadFromArrays(headerRow);
cells.AutoFilter = true;
cells.AutoFitColumns();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
HTML:
<form>
<asp:Button ID="Submission" runat="server" OnClick="Submission_Click" Text="Upload" />
<input type="button" id="Template" value="Template" />
</form>
<script type="text/javascript">
var loading = $("#loading");
$("form").submit(function () {
loading.show();
});
$("#template").click(function () {
loading.show();
$.ajax({
type: "POST",
url: "TemplateService.ashx?Month=" + $("#Month").val() + "&Year=" + $("#Year").val(),
data: {},
contentType: "application/json",
dataType: "json",
success: function (data) {
loading.hide();
console.log(data);
alert("Success");
},
error: function (xhr, text) {
loading.hide();
console.log(JSON.stringify(xhr.responseText));
console.log(JSON.stringify(text));
alert("There is a problem while processing your request");
}
});
});
</script>
Your answer much appreciated.
Thank you.

asp.net | values sent trough ajax received as null in handler

I am trying to send the 'file' attachment to handler(and send it with email)
This is the code I am using to send it to handler(JS)
When I debug it I see the right values including the file(debug in java-script).
function sendCv_click() {
var settings = {
'data': getData("sendCv"),
'url': "Handlers/SendCV.ashx",
'contentType': 'false',
'processData': 'false'
};
sendCV(settings);
};
function getData(){
data = {
'fullName': $('#txt_sendCv_fullName').val(),
'cvFile':$('#fu_sendCv_upload')[0].files[0],
'email': $('#txt_sendCv_email').val(),
'checkBox': $('#sendCv_chkBox:checked').length
}
function sendCV(settings) {
$.ajax({
type: "POST",
contentType: settings.contentType,
processData: settings.processData,
data: settings.data,
url: settings.url,
dataType: "json",
success: function(data) {
...
},
error: function(data, xhr) {
...
});
}).always(function() {
...
});
}
}
How can I get them in the handler page?
like that I get them as Null, why?
public void ProcessRequest(HttpContext context)
{
string fullName = context.Request.Form.Get("fullName"); //It's Null
string email = context.Request.Form.Get("email");//It's Null
string chkBox_ad = context.Request.Form.Get("checkBox"); //It's Null
/////how can i get the file here ??
bool mailSent = Mail.SendCV(fullName, email, chkBox_ad);
context.Response.ContentType = "text/plain";
if (mailSent)
{
context.Response.Write("true");
}
else
{
context.Response.Write("false");
}
}
This might work...
var postedFile = context.Request.Files[0];
var parser = new MultipartParser(context.Request.InputStream);
if (parser.Success) {
byte[] content = parser.FileContents;
string filename = parser.Filename;
}
MultipartParser is opensource class - see http://multipartparser.codeplex.com/SourceControl/latest#MultipartParser.cs

Posting JSON object to asp.net server

i am trying to post some json data to to my asp.netserver on my localhost. The page to receive the code should be the master page, however i tried that and got "Error 403: Forbidden" so i tried my hands on a web service instead and now i am having a whole load of other issues. My main issue is that i could do this rather simply in PHP but i have no idea how to go about this in ASP.NET.
This is my js file:
// Get User Login Credentials
function authenticate() {
$(document).ready(function () {
var user = $('.login-box form #txtLoginUsername').val().trim();
var pass = $('.login-box form #txtLoginPass').val().trim();
// alert(user + " : " + pass);
$.ajax({
type: "POST",
url: "postback.asmx/Verify",
data: {
user: user,
pass: pass
},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function() {
if (response)
{
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () {});
}
}
});
});
}
Now i call this function on a button click event, i do not add my server code because it comprises of several lines of code i picked up from the net and tried to mash up to get my page to work, which it didn't. I would like to know a simple appropriate method of getting JSON objects from a post and return a value/array from my server.
Please i do not wish to use any asp.net server controls for certain reasons i am unable to disclose, but i have been restricted from using such controls.
You can´t put your WebMethod in an masterPage. Ajax is client side and you are getting the same error if you tried to acess site.master in your browser.
"Description: The type of page you have requested is not served because it has been explicitly forbidden. The extension '.master' may be incorrect. Please review the URL below and make sure that it is spelled correctly. "
You can implement your WebMethod in other file .aspx and call by ajax.
I wrote an little example.
cs
[WebMethod(enableSession: true)]
public static void Verify(string user, String pass)
{
throw new Exception("I´m here");
}
js
function authenticate() {
$(document).ready(function () {
var user = $('#txtLoginUsername').val().trim();
var pass = $('#txtLoginPass').val().trim();
// alert(user + " : " + pass);
var data = {};
data.user = user;
$.ajax({
type: "POST",
url: "default.aspx/Verify",
data: JSON.stringify({
user: user,
pass: pass
}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function () {
if (response) {
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () { });
}
}
});
});
}
pay attention how Json is passing to data
data: JSON.stringify({
user: user,
pass: pass
}),
To call webservice, try pass json this way.
When you call web service there are same error message in browser´s console?
I think this is will help you.
You can use JSON.stringify() method as explained in follow
var jsonData=your Jason data;
Data:JSON.stringify(jsonData)
courtsey:
http://www.dotnetlines.com/forum/tabid/86/forumid/6/postid/72/scope/posts/Default.aspx#72
You can do like this.
[WebMethod]
public string Verify(string user,string pass)
{
//DataTable dt = YourMethod_ReturningDataTable();
//retrun dt.toJson();
//But in your case
bool IsAllowedtoLogin = true;
return IsAllowedtoLogin.toJson();
}
For this (toJson) method you have create a static class.This will convert even datatable to json format.
public static string toJson(this DataTable dataTable)
{
string[] StrDc = new string[dataTable.Columns.Count];
string HeadStr = string.Empty;
for (int i = 0; i < dataTable.Columns.Count; i++)
{
StrDc[i] = dataTable.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
StringBuilder Sb = new StringBuilder();
Sb.Append("{\"" + dataTable.TableName + "\" : [");
for (int i = 0; i < dataTable.Rows.Count; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < dataTable.Columns.Count; j++)
{
TempStr = TempStr.Replace(dataTable.Columns[j] + j.ToString() + "¾", dataTable.Rows[i][j].ToString());
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("]}");
return Sb.ToString();
}
Note that data parameters are case sensitive. i.e user , pass .
$.ajax({
type: "POST",
url: "default.aspx/Verify",
data: "{'user':'"+yourvariable+"','pass':'"+yourvariable+"'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
data = JSON && JSON.parse(data.d) || $.parseJSON(data.d);
if (data == "true") {
alert('Works');
}
else {
$(".ui-widget").slideDown(1000, function () { });
}
}
});

How can I return JSON via C# and parse it in JavaScript?

I am using a web service that gets data from my active directory and returns an array of objects to my javascript. The problem is the I am the response encapsulated in Object with _type included when I just want to return the value of the object like this
([{ value: "one", label: "Foo" }, { value: "two", label: "Bar" }]).
But I am receiving this
[Object { __type="Service+NameDTO", value: "one", label: "Foo"}, Object { __type="Service+NameDTO", value: "two", label: "Bar"}]
Here is my c#
public NameDTO[] GetCompletionList(string prefix)
{
var nameList = new List<NameDTO>();
DirectorySearcher search = new DirectorySearcher();
string strPath = search.SearchRoot.Path;
DirectoryEntry entry = new DirectoryEntry(strPath);
search.PageSize = 1000;
search.Filter = "(&(objectClass=user)(objectCategory=person)(displayName=*" + prefix + "*))";
foreach (SearchResult sResultSet in search.FindAll())
{
if (sResultSet.Properties["mail"].Count > 0)
{
var dto = new NameDTO()
{
label = (string)sResultSet.Properties["displayName"][0],
value = (string)sResultSet.Properties["mail"][0],
};
nameList.Add(dto);
}
}
NameDTO[] myArray = nameList.ToArray();
return myArray;
}
public class NameDTO
{
public string label { get; set; }
public string value { get; set; }
}
and my javascript
<script type="text/javascript">
$(document).ready(function () {
$('#tokenfield').tokenfield({
autocomplete: {
source: function (request, response) {
$.ajax({
url: '<%#ResolveUrl("~/Service1.asmx/GetCompletionList") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return data
}))
},
success: function(response) {
$.each(response, function(key, val) {
alert(val.id);
});
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
search: function () {
var term = this.value;
if (term.length < 3) {
return false;
}
},
focus: function () {
// prevent value inserted on focus
return false;
},
},
});
});
</script>
You probably need some typical JSON builder.
Server-side, you can make dictionaries, arrays, etc and throw everything into a
JsonMapper.ToJson(jsonDict)
call.
This function in my project indirectly calls JsonSerializer(), the Newtonsoft JSON handler. Very useful for both serializing and deserializing the JSON.
I may be misinterpreting your question, though; a bit vague.
http://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx is pretty darn relevant here, and very useful.
It came up that you might need this:
var jsonString = #Model; //or however you get your string.
var json = JSON.parse(jsonString);

Categories

Resources