Uncaught SyntaxError: Unexpected token < Ajax call web service - javascript

I have a problem with web service web call by js and I need your help.
Thanks
My code service :
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
Ajax call service :
function callServices() {
$.ajax({
type: "POST",
url: "WebService.asmx/HelloWorld",
data: "{}",
contentType: "application/jsonp; charset=utf-8",
dataType: "jsonp",
success: function (msg) {
alert(msg.d);
}
});
};
My problem when I pressed F12 to show:
Click to show

Related

WCF service POST method not working

i am getting following error when i call the wcf service using ajax from another project :
The server encountered an error processing the request. The exception message is 'The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', 'Json'. This can be because a WebContentTypeMapper has not been configured on the binding. See the documentation of WebContentTypeMapper for more details.'. See server logs for more details.
i have created the following wcf service in a project :
IService1.cs -
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
int AddNumbers(int a);
[OperationContract]
string ShowMsg();
// TODO: Add your service operations here
}
service1.cs -
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
public int AddNumbers(int a)
{
return a + 5;
}
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
public string ShowMsg()
{
return "Hello World!";
}
}
and this is how i am consuming it from another project :
$.ajax({
type: "POST",
url: "http://localhost:16748/Service1.svc/AddNumbers",
contenType: 'application/json',
data: JSON.stringify({ a: 4 }),
dataType: 'json',
success: function (data) {
$("#elementsDiv").html(data);
},
error: function (xhr, status, error) {
var err = xhr.responseText;
$("#elementsDiv").html(err);
}
});
can anybody help me with this?
I believe you may have a typo in your ajax call:
contenType: 'application/json',
I think this should be:
contentType: 'application/json',
other than that your code runs fine for me.

Submitting Ajax request from external javascript file in ASP.NET MVC

I am trying to submit an ajax request from an external JavaScript file in ASP.NET MVC. I'm getting a 500. What am I doing wrong?
Ajax call (From external JS file)
$.ajax({
type: "POST",
url: '/Home/AjaxEndpoint',
data: { jsonData: "testing" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
Controller Action Method (That should be catching the request)
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpGet]
public void AjaxEndpoint()
{
var thing = 1 + 2;
}
// AJAX endpoint for GetProducts.js
[HttpPost]
public void AjaxEndpoint(string jsonData)
{
var thing = 1 + 2;
}
}
Error I'm getting
You either need to remove the contentType option
$.ajax({
type: "POST",
url: '/Home/AjaxEndpoint',
data: { jsonData: "testing" },
dataType: "json",
success: successFunc,
error: errorFunc
});
or alternatively, stringify the data
$.ajax({
type: "POST",
url: '/Home/AjaxEndpoint',
data: JSON.stringify({ jsonData: "testing" }),// modify
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
Your ajax call needs to be to an ActionResult in the controller, The controller performs and returns the data to the page
[HttpPost]
public ActionResult ajaxcall(string ids)
{
String Data = code to perform
return Json(Data);
}
this is the basic idea. Javascript makes the call and uses the json data returned on the clients page

Ajax POST 404 Error With asmx

I am attempting to create a webmethod that I can call/POST to from javascript code, but I obtain the following error in console whenever the test() function is called:
"POST http://localhost:53093/TestMethods.asmx/HelloWorld 404 (Not Found)"
I have checked multiple questions similar to mine, but none of the solutions seem to work. Any help would be appreciated.
TestMethods.asmx.cs
[WebService(Namespace = "http://testdomain.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class TestMethods : System.Web.Services.WebService
{
[WebMethod()]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string HelloWorld()
{
return "Hello World";
}
}
Javascript (game.js)
function test()
{
$.ajax({
url: "TestMethods.asmx/HelloWorld",
type: 'POST',
data: "{}",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert(result);
}
});
}
File Structure Image

Calling a C# method from .js file

I have a aspx page and in that i have method UpdateScreenAlertStatus();
I want to have a file called dtml.js and in that i have function openmodelpopup().
I want to call UpdateScreenAlertStatus(); in javscript method openmodelpopup().
function MyMethod() {
$.ajax({
type: "POST",
url: "abc.aspx/UpdateScreenAlertStatus ",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
Call the above ajax in your js function openmodelpopup().
[WebMethod]
public static void UpdateScreenAlertStatus()
{....}
Make it a web method
[WebMethod]
public static string UpdateScreenAlertStatus()
{....}
Refer this MSDN article.
From javascript you can access this as YourPage.aspx/UpdateScreenAlertStatus or through PageMethods in same aspx page. You can call this with the following javascript.
function openmodelpopup() {
$.ajax
({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "YourPage.aspx/UpdateScreenAlertStatus",
success: (function (data) {
$("#statusDiv").text(data.d);
$("#statusDiv").show();
}),
error: (function () {
alert("Error occurred in server!");
})
});
}
I'm assuming here, 1. your C# method is static and marked WebMethod. 2. Code is compiled properly. 3. You are using jQuery. 4. The url in javascript is correct. 5. Your C# method returns a string status. 6. You are trying to update html element statusDiv with that string.

Passing a string from code behind to ajax

I am accessing a method on the server side. The only problem is that I don't have alot of experience in AJAx. I am unable to retrieve the returned string in the ajax from the .cs method
$.ajax({
type: 'GET',
url: '/frmGpsMap.aspx?name=load',
dataType: 'text',
success: function(data) {
alert(data.d);
}
});
protected void Page_Load(object sender, EventArgs e)
{
string crrName = Request.QueryString["name"];
if (!String.IsNullOrEmpty(crrName))
{
if (crrName.ToLower().Equals("load"))
{
string fh= loadKMLFileToString();
hdnUsername.Value = fh;
}
}
}
public string loadKMLFileToString()
{
return "hello world";
}
The alert is returning the html of the page. I want to display the "Hello World" string
To get the code behind method to work with ajax you need to use System.Web.Services.WebMethod. By default you need to use POST unless you specify HTTP GET attribute in code behind
[System.Web.Services.WebMethod]
public static string LoadKMLFileToString()
{
return "Hello World";
}
Here is the ajax method for call
$.ajax({
type: "POST",
url: "frmGpsMap.aspx/LoadKMLFileToString",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response.d),
failure: function(response) {
alert(response.d);
}
});
I hope it helps.
More examples: http://weblogs.asp.net/karan/calling-server-side-method-using-jquery-ajax
I think you can decorate your cs method with the WebMethod attribute and call it directly from ajax. Like this:
$.ajax({
...
url: '/frmGpsMap.aspx?loadKMLFileToString',
...
});
[System.Web.Services.WebMethod]
public string loadKMLFileToString()
{
return "hello world";
}
Cheers! =)

Categories