Too many characters in character literal with ajax - c#

I have this simple code WebForm2.aspx which runs an ajax request to get some data, but when I run this code, I'm getting this error: Too many characters in character literal What is going on?
The output I get is:
cccccccccccccccccccccccccc
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication24.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>FirstAjax</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var serviceURL = '/AjaxTest/FirstAjax';
$.ajax({
type: "POST",
url: serviceURL,
data: param = "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>

Probably your error is here:
$.ajax({
type: "POST",
url: serviceURL,
data: param = "", ///// HERE, try: data: {param:""}, but, I don't know what contains `param`
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});

Your problem is wit your data property:
data: param = "",
Use this instead
data: {param: ""},

Related

How to link a JavaScript function to HTML anchor tag

How to link this JavaScript code to an anchor tag of HTML:
<script type="text/javascript">
$(document).on('click', 'a', function () {
$.ajax({
type: 'POST',
url: '#Url.Action("/brandsOfACategory")',
contentType: 'application/json; charset:utf-8',
data: JSON.stringify({ id: this.id })
})
});
anchor tag:
<a id="#c.Key" href ="???" onclick="???">#c.Key</a>
brandsOfACategory action method:
[HttpPost]
public ActionResult brandsOfACategory(string id)
{
var result = db.Items.Where(x => x.Category.Name.Equals(id)).Select(x => x.BrandID).ToList();
var ListOfBrands = db.Brands.Where(t => result.Contains(t.BrandID)).ToList();
return View(ListOfBrands);
}
brandsOfACategory.cshtml is:
#model IEnumerable<OnlineStore.Models.Brand>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Brands in a Category</title>
</head>
<body>
#foreach (var i in Model)
{
#i.Name.ToString();
}
</body>
</html>
You can write the anchor tag like this-
<a id="#c.Key" href ="javascript:void(0);" onclick="postBrands(#c.Key)">#c.Key</a> //replace postBrands with desired function name
Then define the function in the javascript which will contain the post request-
function postBrands(key) {
$.ajax({
type: 'POST',
url: '#Url.Action("/brandsOfACategory")',
contentType: 'application/json; charset:utf-8',
data: JSON.stringify({ id: key })
})
}
You can put in href and then fetch the href in the client side click code:
<a id="#c.Key" href ="#Url.Action("actionName","controllerName")">#c.Key</a>
and in the click event you can write following:
$(document).on('click', 'a', function () {
var Url = $(this).attr("href"); // get href value
$.ajax({
type: 'POST',
url: Url, // use it here
contentType: 'application/json; charset:utf-8',
data: JSON.stringify({ id: this.id })
})

Jquery autocomplete textbox in asp.net

I am trying to implement jquery autocomplete textbox in asp.net. But I am getting the error "Object doesn't support this property or method" though while coding I am getting 'autocomplete' function in intellisense. I have tried to use google api link as well in case my jquery files are not getting loaded correctly, but i am getting the same error. Following is my code:
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
<script src="Scripts/jquery-1.11.2.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui.js" type="text/javascript"></script>
<link href="Styles/jquery-ui.css" rel="stylesheet" type="text/css" />
<script language="JavaScript" type="text/JavaScript">
$(document).ready(function () {
$("[id*=txtPCTrx]").autocomplete({
source: function (request, response) {
$.ajax({
url: "PCAdd.aspx/GetAutoCompleteData",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{'txt':'" + $('[id*=txtPCTrx]').val() + "'}", //json to represent argument
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item,
value: item
}
}))
//debugger;
},
error: function (result) {
alert("Error");
}
});
},
minLength: 1,
delay: 1000
});
</script>
Apart from the above autocomplete function I have many other jquery functions which are working properly in the same page. Please help.

Send Uploading Files Together With Form Data

var formData = new FormData($("form#neweventform")[0]);
$.ajax({
url: "/Event/NewEvent",
type: "POST",
data: formData,//JSON.stringify(saveEventModel),
async: false,
dataType: 'json',
//contentType: 'application/json; charset=utf-8',
cache: false,
contentType: false,
processData: false,
fail: function (r) {
alert('error.');
},
success: function (result) {
}
...
On the controller side I have:
public JsonResult NewEvent(EventModel saveEventModel, List<HttpPostedFileBase> files)
{
}
I receive file in List<HttpPostedFileBase> files object but it's null. May be data is not posted to the server?
I think I'm doing something wrong conceptually. :/
How to upload images together with other form data like name, date, address etc.?..
Is this what you're looking for?
C# MVC controller
public class UploadController : Controller
{
[HttpPost]
public JsonResult FilesList(List<HttpPostedFileBase> myFiles)
{
string message;
if (myFiles == null)
{
message = "myFiles is null";
}
else if (myFiles.Count != 2)
{
message = "myFiles.Count is " + myFiles.Count;
}
else
{
message = string.Format("myFiles[0] is {0}, myFiles[1] = {1}",
myFiles[0] == null ? "null" : myFiles[0].FileName,
myFiles[1] == null ? "null" : myFiles[1].FileName);
}
return Json(new
{
Message = message
});
}
}
HTML + Javascript
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Upload Demo </title>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function ()
{
$('#sendButton').click(function ()
{
var form = $('#myForm')[0];
var formData = new FormData(form);
$.ajax({
data: formData,
processData: false,
contentType: false,
dataType: 'json',
type: 'POST',
url: 'Upload/FilesList',
error: function (jqXHR, textStatus, errorThrown)
{
alert('failure\n' + textStatus);
},
success: function (data, textStatus, jqXHR)
{
alert(data.Message);
}
});
});
});
</script>
</head>
<body>
<form id="myForm">
File 1: <input type="file" name="myFiles" /><br />
File 2: <input type="file" name="myFiles" />
</form>
<button id="sendButton">Submit over AJAX</button>
</body>
</html>

Problems with jquery and C# web service

Output from web service, "http://localhost:6833/Service1.asmx/HelloWorld":
<string xmlns="http://tempuri.org/">
[{"Name":"Pini","Age":"30","ID":"111"},{"Name":"Yaniv","Age":"31","ID":"Cohen"},{"Name":"Yoni","Age":"20","ID":"Biton"}]
</string>
HTML code:
<html>
<head>
<script type="text/javascript" src="jquery-1.7.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "POST",
url: "Service1.asmx/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert("Result: " + msg);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus);
}
});
});
</script>
</head>
<body>
</body>
</html>
When i run index.html in browser i get the Error alert.. Tried alot of things, but cant find out whats missing..
your json in encapsulated in a xml string, i guess thats your problem.
EDIT:
check this post for more information.
Try adding this before your method.
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
below
[WebMethod]

ASP.NET a problem with jQuery's ajax function

I have button and that jQuery script (to start the progress bar):
<script src="../_Files/JScripts/jquery-1.3.2.js" type="text/javascript"></script>
<script src="../_Files/JScripts/jquery-ui-1.7.2.custom.min.js" type="text/javascript"></script>
var intervalID;
$("#<%=this.Button1.ClientID%>").click(
function() {
intervalID = setInterval(updateProgress, 500);
$.ajax({
type: "POST",
url: "CustomerImport.aspx/ExecuteImport",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function()
{
$("#progressbar").progressbar("value", 100);
clearInterval(intervalID);
$("#result").text('ok');
}
});
return false;
}
);
function updateProgress() {
$.ajax({
type: "POST",
url: "CustomerImport.aspx/GetProgress",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) {
$("#result").text = msg.d;
var value = $("#progressbar").progressbar("option", "value");
if (value < 100) {
$("#progressbar").progressbar("value", msg.d);
$("#result").text(msg.d);
}
else {
clearInterval(intervalID);
window.location = window.location;
}
}
});
}
the method:
[System.Web.Services.WebMethod]
public void ExecuteImport()
{
_Presenter.ExecuteImport();
}
the problem is, that method is NOT being invoked. Why ?
When I replace the $.ajax for the e.g alert('ok'); the alert shows, so it works
Did you decorate your service class with the [ScriptService] attribute? Also try changing the data parameter to: data: { }. What does FireBug says about this? Is there a request being sent? If yes what does the server respond?
Also you have a mistake in your url (web services have the ASMX extension). You wrote:
CustomerImport.aspx/ExecuteImport
While it should be:
CustomerImport.asmx/ExecuteImport
Here's a complete working example that you may adapt to your needs:
Web service:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[ScriptService]
public class CustomerImport : WebService
{
[WebMethod]
public void ExecuteImport()
{
}
}
Calling web page:
<%# Page Language="C#" %>
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript" src="scripts/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: 'POST',
url: '/CustomerImport.asmx/ExecuteImport',
data: { },
success: function () {
alert('ok');
}
});
});
</script>
</head>
<body>
<form runat="server">
</form>
</body>
</html>
Add in the error function to the ajax call... Hopefully you'll get some info back, as to why the call failed.
Are you using firebug? Watch the net tab.
$.ajax({
type: "POST",
url: url,
async: false,
data: jsonEncodedParams,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
}, //success
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (textStatus == "timeout") {
alert('The request timed out, please resubmit');
} //if
else {
alert(errorThrown);
} //else
} //error
}); //ajax
Since your server-side endpoint is a "page method", it must be declared as static:
[System.Web.Services.WebMethod]
public static void ExecuteImport()
{
_Presenter.ExecuteImport();
}

Categories