Ajax. SyntaxError. Invalid character - javascript

I have an asp.net mvc application. I have view named "Access", controller and I'm tring to call one of controllers method in ajax. And I got an Syntax Error. Method Test was not called at all
Controller method code:
[HttpGet]
public JsonResult Test(string p)
{
return Json(new User() { Name="Nat"}, JsonRequestBehavior.AllowGet);
}
ajax call:
$.ajax({
type: "GET",
url: "Access/Test", // the method we are calling
contentType: "application/json; charset=utf-8",
data: { "p": "test" },
dataType: "json",
success: function (result) {
alert("yes");
alert('Yay! It worked!' + result);
},
error: function (request, status, error) {
alert('Not worked ' + error);
}
});
It is a very simple code but I cann't force it work.I want to understand why my json data is incorrect and I got an Error. And I want to execute my method

You send GET request, so remove data and contentType - they are no needed in GET requests:
$.ajax({
type: "GET",
url: "Access/Test", // the method we are calling
dataType: "json",
success: function (result) {
alert("yes");
alert('Yay! It worked!' + result);
},
error: function (request, status, error) {
alert('Not worked ' + error);
}
});
And remove p from action, or set it to null:
[HttpGet]
public JsonResult Test(string p = null)
{
return Json(new User() { Name="Nat"}, JsonRequestBehavior.AllowGet);
}

AccessContoller.cs
public class AccessController : Controller
{
[HttpGet]
public JsonResult Test(string p)
{
return Json(new User() { Name="Nat"}, JsonRequestBehavior.AllowGet);
}
}
Index or Any Page Call
$(document).ready(function(){
$.ajax({
type: "GET",
url: "Access/Test", //First Controller Name(Access) or After Method Name
contentType: "application/json; charset=utf-8",
data: { "p": "test" },
dataType: "json",
success: function (result) {
alert("yes");
alert('Yay! It worked!' + result);
},
error: function (request, status, error) {
alert('Not worked ' + error);}
});
});

Related

Ajax errorThrown: Internal Server Error but state is 4

I have this ajax call below
$(function(){
$.ajax({
type: "GET",
url: '/CafeTableDetails/GetTotalItems',
data: '{"url":"test"}',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
debugger
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger
alert("some error");
}
});
});
and it can call the action method of my controller in C# MVC /CafeTableDetails/GetTotalItems
public ActionResult GetTotalItems()
{
bool isSuccess = true;
return Json(new { isUpdateSuccess = isSuccess, JsonRequestBehavior.AllowGet });
}
But as the action method return it back as Json, it falls into error. The XMLHttpRequest return state is 4, textStatus = "Error" and errorThrown is "Internal Server Error". How do I troubleshoot this further?
Your ajax method should be :
$.ajax({
type: "GET",
url: "/CafeTableDetails/GetTotalItems",
data: JSON.stringify({ url: 'test' }),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function(response) {
console.log(response);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr.responseText);
}
});
and your controller action method will be:
[HttpGet]
public JsonResult GetTotalItems(string url)
{
// some business logic and return
return Json(url, JsonRequestBehavior.AllowGet);
}

The GET request call returns wrong result

I would like to call my WEB API in .NET Core from the jQuery like below:
[HttpGet("GetText")]
public async Task<IActionResult> GetText()
{
try
{
string welCome = "Test";
JsonSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
return Json(welCome, JsonSettings);
}
catch(Exception ex)
{
throw ex;
}
}
And the jQuery caller:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'GET',
url: "http://localhost:5000/api/mycontroller/GetText?callback=?",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
if (data.success) {
alert('Success -> ' + JSON.stringify(data.statusText));
}
},
error: function (data) {
alert('Error -> ' + JSON.stringify(data.statusText));
}
});
});
</script>
The API is calling successfully but it seems it will then redirect to error function in my Ajax and show the error alert with a "success" as it's statusText. I mean this: Error -> "Success" I am not sure why this happens?
I would like to print welCome as a success result and in the alert command.
Also please note that I am calling this API from another project, I mean the jQuery's AJAX code is inside another project. I am not sure if it is important or not at all.
The jQuery's AJAX Caller path: file:///C:/Users/Me/Desktop/Path/index.html
The API's address: C:\Users\Me\Documents\Visual Studio 2017\Projects\ThisProject\MyAPI
And the URL of this API: url: "http://localhost:5000/api/mycontroller/GetText",
Try the C# Code in the following manner :
[HttpGet("GetText")]
public async Task<IActionResult> GetText()
{
try
{
string welCome = "Test";
return Ok(new { message = welCome });
}
catch(Exception ex)
{
throw ex;
}
}
Try the Jquery Code in the following manner :
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'GET',
url: 'http://localhost:5000/api/mycontroller/GetText',
success: function (response) {
alert('Success' + response.message);
},
failure: function (response) {
}
});

JQuery Ajax Success not being triggered

I'm not sure why my ajax success isn't being triggered/called.
My controller is called and the code is executed fine. I'm not returning anything, so my method is a void! Do I need to return something (ActionResult/JSonResult/etc) to get the success to trigger?
Here is my controller code.
public void DeleteEvent(string eventId)
{
diaryEventService.DeleteDiaryEvent(eventId);
}
Here is my ajax call.
$.ajax({
url: '/ManageSpaces/DeleteEvent',
dataType: 'json',
data: {
eventId: eventId,
},
success: function() {
//var obj = JSON.parse(doc);
var myCalendar = $('#fullcalendar');
myCalendar.fullCalendar();
myCalendar.fullCalendar('removeEvents', eventId);
$("#eventDetails").collapse('toggle');
}
});
Yes, you need to return JsonResult:
[HttpPost]
public JsonResult DeleteEvent(string eventId)
{
diaryEventService.DeleteDiaryEvent(eventId);
return Json("{status:"OK"}");
}
Since you are changing back-end data, set it to POST:
$.ajax({
url: '/ManageSpaces/DeleteEvent',
method: 'POST',
dataType: 'json',
data: {
eventId: eventId,
},
success: function(response) {
if(response.status=="OK"){
var myCalendar = $('#fullcalendar');
myCalendar.fullCalendar();
myCalendar.fullCalendar('removeEvents', eventId);
$("#eventDetails").collapse('toggle');
}else{
console.log("Error occured")
}
}
});

C# Web method is not calling in javascript

i create a web method and now i'm calling this in my java script file but it give an path error,it is not able to find path what i'm giving ..
Web method code is :
[System.Web.Services.WebMethod]
public static int ItemCount(string itemId)
{
int val = 0;
Item itm = Sitecore.Context.Database.GetItem(itemId);
val = itm.Children.Count;
return val;
}
java script function calling like as:
function GetItemCount(itemId) {
var funRes = "";
debugger;
try {
if (itemId != null) {
jQuery.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Views/GetItem.aspx/ItemCount",
data: { itemId: itemId },
dataType: "json",
async: false,
success: function (data) {
funRes = data.result;
},
error: function(err) {
alert(err.responseText);
}
});
}
} catch (ex) {
alert(ex.message);
}
return funRes;}
while i'm giving exact path for the C# method class but it's not working give an error on console, can anyone suggest me what i'm missing here..
There are few rules for ajax to work with asp.net.
Your WebMethod should be public and static.
If your WebMethod expects some parameter(s) than these parameter(s) must be passed as data in ajax.
Name of parameter(s) should be same in WebMethod and in data part of ajax.
Data passed from ajax should be in json string.For this you can use JSON.stringify or you will have to surround the values of parameter(s) in quotes.
Please check the below sample ajax call
function CallAjax()
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/CallAjax",
data: JSON.stringify({ name: "Mairaj", value: "12" }),
dataType: "json",
async: false,
success: function (data) {
//your code
},
error: function (err) {
alert(err.responseText);
}
});
}
[WebMethod]
public static List<string> CallAjax(string name,int value)
{
List<string> list = new List<string>();
try
{
list.Add("Mairaj");
list.Add("Ahmad");
list.Add("Minhas");
}
catch (Exception ex)
{
}
return list;
}
EDIT
If you use GET in ajax than you need to enable your webmethod to be called from GET request. Add [System.Web.Script.Services.ScriptMethod(UseHttpGet = true)] on top of WebMetod
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
public static int ItemCount()
Just Modify the javascript function as below
function GetItemCount(itemId) {
var funRes = "";
debugger;
try {
if (itemId != null) {
jQuery.ajax({
type: "GET",
url: "/Views/GetItem.aspx",
data: 'itemID=' + itemId,
contentType: "application/html",
dataType: "html",
success: function (response) {
funRes= response.result;
}
});
}
} catch (ex) {
alert(ex.message);
}
return funRes;
}
I am not sure it is a solution for every question subject which web method not fire. But I discovered today when there is ' char in the string. Web Method not firing.

AJAX post data is null in controller mvc

I try to send a JSON object back to the server. This is my AJAX call:
$.ajax({
url: '/Home/NewService',
async: false,
type: "POST",
data: JSON.stringify(props),
error: function (jqXHR, textStatus, errorThrown) {
console.log("FAIL: " + errorThrown);
},
success: function (data, textStatus, jqXHR) {
console.log("SUCCES");
}
});
The evaluation of JSON.stringify(props) in the browser's debugger is
"[{"name":"firstName","value":"firstValue"}]"
This is the method in the controller which is being called:
[HttpPost]
public void NewService(dynamic json)
{
Response.Write(json);
}
The problem I have is that always the json variable from above is an empty object.
The success function gets called but when I debug the json var is displayed as empty.
Please tell me what I am doing wrong.
Thank you.
I don't think you can bind to a dynamic type the way you're trying to. You can try to create a class that maps your data, something like:
public class Content
{
public string Name { get; set; }
public string Value { get; set; }
}
Now in your action:
[HttpPost]
public ActionResult NewService(Content[] data)
{
// sweet !
}
And in your js like Olaf Dietsche said you need to specify your contentType:
var props = [
{ "Name": "firstName", "Value": "firstValue" },
{ "Name": "secondName", "Value": "secondValue" }
];
$.ajax({
url: '/Home/NewService',
contentType: "application/json",
async: true,
type: "POST",
data: JSON.stringify(props),
error: function (jqXHR, textStatus, errorThrown) {
console.log("FAIL: " + errorThrown);
},
success: function (data, textStatus, jqXHR) {
console.log("SUCCESS!");
}
});
According to jQuery.ajax(), the default content type is is application/x-www-form-urlencoded. If you want to send the data as JSON, you must change this to
$.ajax({
url: '/Home/NewService',
contentType: 'application/json',
...
});
Use the following code to solve this problem
Ajax Call
function SaveDate() {
var obj = {};
obj.ID = '10';
obj.Name = 'Shafiullah';
$.ajax({
url: '/Home/GetData',
dataType: "json",
type: "Post",
contentType: 'application/json',
data: JSON.stringify({ ID: obj.ID, Name: obj.Name }),
async: true,
processData: false,
cache: false,
success: function (data) {
alert(data.id + ' , ' + data.name);
},
error: function (xhr) {
alert('error');
}
});
}
My controller action method
[HttpPost]
public IActionResult GetData([FromBody] Employee employee)
{
return Json(employee);
}

Categories