Charisma V.2.0.0 bundle in ASP.Net Ajax error - ajax

I've integrated the Charisma V.2.0.0 bundle in an ASP.Net C# application. All looks good until I write an .ajax call to a web service. Ajax call, a standard format, works in a basic asp.net page, but from the bundle. It seems like something in his 'bower_components'. I removed reference to bower_components/jquery and am including ajax.googleapis.com... 3.3.1.
Does anyone have experience with this problem? and what might be a solution? I like the UI Muhammad designed and would like to keep developing which is platform.
The axax call looks like this:
// Edit Client button
$(document).on("click", "[id*=btnEditClient]", function () {
// Edit selected client/Event Id - get data from Ajax
//alert($(this).val());
var clientId = $(this).val();
var clientInfo = JSON.stringify({ clientId: clientId });
alert(clientInfo);
$.ajax(
{
url: '<%= ResolveUrl("QRWebService.aspx/GetClientListService") %>',
type: "POST",
data: clientInfo,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// results
alert(result.d);
alert('no error ' + JSON.stringify(result));
$("#myModal").modal()
return true;
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error: ' + textStatus);
}
});
return false;
})
and the result is 'undefined' where the web service never gets called.
The web serivce is:
[WebMethod]
public static DataSet GetClientListService()
{
// returns dataset LIST of Client Id and Name
DataSet ds = new DataSet();
SQLHelper.SqlQuery oQuery = new SQLHelper.SqlQuery();
String strSQL;
try
{
strSQL = "SELECT Clients.ClientId, ClientName FROM Clients ";
strSQL += "WHERE ClientActive=#clientActive";
ds = oQuery.GetDataSet(strSQL);
} catch(Exception ex){
errorMessage = ex.Message;
}
return ds;
} // end GetClientEventList()

Post ASP.NET Calling WebMethod with jQuery AJAX "401 (Unauthorized)". Changing the App_Start from Permanent to:
settings.AutoRedirectMode = RedirectMode.Off;
did the trick. I hope this helps others. Thank you StackOverflow and all those who post solutions to tricky issues.

Related

What is a proper way to POST multiple sets of data through AJAX to .Net Core EF Core

I have seen numerous examples, mostly wrong or outdated concepts written a decade ago. I cant seem to find a way to submit multiple variables to the ef core database using Ajax. I can get it to work with one, but cant seem to get it to work with multiple. Not sure if I am doing something wrong? I just get a syntax error on the var dataObjects
Ajax Call
<script type="text/javascript">
$("#cosubmitbutton").click(function () {
if ($('#CompanyId').val() == "-1" || $('#CompanyId').val() == "0") {
toastr.warning("Please select company / Client!");
return false;
}
var dataObjects = {
CompanyId = $("#CompanyId").val();
TechnicalContact = $("#TechnicalContactId").val();
TCEmailAddress = $("#TCEmailAddressId").val();
NumOfWorkstations = $("#NumOfWorkstationsId").val();
NumOfUsers = $("#NumOfUsersId").val();
NumOfServers = $("#NumOfServersId").val();
NumOfFirewalls = $("#NumOfFirewallsId").val();
NumOfSwitches = $("#NumOfSwitchesId").val();
NumOfAps = $("#NumOfApsId").val();
Domain = $("#DomainId").val();
};
//ObjThreadItem = JSON.stringify({ 'ObjThread': ThreadItem});
console.log("Json Stringify CommonPostData: ", JSON.stringify(dataObjects))
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'JSON',
url: '/Onboarding/Client/CreateClientOverview',
type: "post",
data: JSON.stringify(dataObjects),
success: function (result) {
debugger
toastr.success("Information successfully updated on server!");
location.reload();
},
failure: function (response) {
debugger
console.log(response);
}
});
});
</script>
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult CreateClientOverview(ClientOverview Modal)
{
_context.ClientOverview.Add(Modal);
_context.SaveChanges();
return Json(Modal);
}

ASP.NET Core MVC AJAX call to Action method not working

I am new to AJAX and I am trying to get some data from my controller method into my .js file so I can use that data in my chart.
Everytime I run my project now I get the custom error message: "Error loading data! Please try again."
So that means that it is getting inside the AJAX function, but not successfully.
Also I dont know how to debug this properly to see where it goes wrong.
My .js code in a sepperate file is the following:
var chartData;
$(document).ready(function () {
$.ajax({
url: "/Account/GetChartData",
data: "",
dataType: "json",
type: "POST",
contentType: "application/json; chartset=utf-8",
success: function (data) {
chartData = data.d.toString();
alert("Data is: " + data.d.toString());
},
error: function () {
alert("Error loading data! Please try again.");
}
}).done(function () {
//After complete loading data
drawChart();
});
});
My controller method looks like this:
public static object[] GetChartData()
{
var chartData = new object[2];
//Manually adding some test data
chartData[0] = new object[]
{
"Day",
"Detected Asparaguses",
"String Operations",
"Successful Sting Operations"
};
chartData[1] = new object[]
{
"21-09-2018",
100,
85,
80
};
return chartData;
}
You have specified dataType: "json" but your method does not return json, and you would be getting a 500 (Internal Server Error). Change the method to return a JsonResult
[HttpPost]
public ActionResult GetChartData() // or `JsonResult`
{
var chartData = new object[2];
....
return Json(chartData);
}
and then data in the ajax callback will contain the array of your objects.

jQuery Ajax returns undefined result from asp.net core controller's POST action

Can't make friends out of my AJAX and MVC 6 controller.
This is how I define AJAX call for SetFormValues POST-action:
Index.cshtml
$.ajax({
type: "Post",
url: "Home/SetFormValues",
data: { Name: name, Phone: phone },
dataType: "json",
success: function (result) {
SuccessFunction(result)
},
error: function () {
alert("ALARM!");
},
async: false
})
I see that the controller works and executes SetFormValues action which is defined as the following:
HomeController.cs
[HttpPost]
public JsonResult SetFormValues(string Name, string Phone)
{
string NameErrorStr = string.IsNullOrWhiteSpace(Name) ? "Обязательное поле" : string.Empty;
string PhoneErrorStr = string.IsNullOrWhiteSpace(Phone) ? "Обязательное поле" : string.Empty;
var result = new { NameError = NameErrorStr, PhoneError = PhoneErrorStr };
var jresult = Json(result);
return jresult;
}
Debugger shows that action executes and my resulting JSON object fills correctly:
Finally, his is how SuccessFunction(result) is defined:
Index.cshtml again
function SuccessFunction(result) {
alert("Success function shit executed. result=" +
result + "NameError=" +
result.NameError + ". PhoneError=" +
result.PhoneError);
$("#nameerror").append(result.NameError);
$("#phoneerror").append(result.PhoneError);
}
Function works, alert is raised but result stay 'undefined' no matter what I do:
result = [object Object]
result.val = undefined
Maybe I have to deserialize JSON result properly or fill some properties in it's declaration above, I don't know.
I'm using the lattest libraries for jquery, validate and unobtrusive.
I also tried JSON.parse(result), as it mentioned in the lattest jQuery specification, but it didn't work as well.
Please, help me :)
In asp.net core, by default, the serializer uses camelCase property names for json serialization. So your result will be like this
{"nameError":"some message","phoneError":"some message here"}
Javascript is case sensitive. So use the correct case
$("#nameerror").append(result.nameError);
$("#phoneerror").append(result.phoneError);
For reference : MVC now serializes JSON with camel case names by default
its working perfectly when i have added this line in startup file
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
services.AddDbContext<DataContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DbCrudOperation")));
}
function Edit(id) {
$.ajax({
type: 'GET',
url: "/AjacCrud/EditPahe/" + id,
dataType: 'JSON',
contentType: "application/json",
success: function (response) {
$("#nameEmp").val(response.ID);
console.log(response.ID);
},
error: function (GetError) {
alert(GetError.responseText);
}
});
};

Ajax not returning desired results or not working at all

I have been trying to load return a JsonResults action from a controller in MVC using ajax call. I can see that the alert() function is triggering well but the ajax is not executing. I have search for several sources but to no avail.
public JsonResult FillBusinessLicenceL3(int? selectedID)
{
var bl3_Items = db.LevelThreeItems.Where(l3 => l3.LevelTwoItem_ID == selectedID);
return Json(bl3_Items, JsonRequestBehavior.AllowGet);
}
The below too is the javascript calling for the json method.
<script>
function FillBussLicence_L3items() {
alert("You have clicked me");
var bl2_Id = $('#BussLicenceL2_ID').val();
//alert(document.getElementById("BussLicenceL2_ID").value);
alert(bl2_Id);
$.ajax({
url: 'StartSurvey/FillBusinessLicenceL3/' + bl2_Id,
type: "GET",
dataType: "JSON",
data: "{}", // { selectedID : bl2_Id },
//contentType: 'application/json; charset=utf-8',
success: function (bussLicence_L3items) {
$("#BussLicenceL3_ID").html(""); // clear before appending new list
$.each(bussLicence_L3items, function (i, licenceL3) {
$("#BussLicenceL3_ID").append(
$('<option></option>').val(licenceL3.LevelThreeItem_ID).html(licenceL3.LevelThreeItem_Name));
});
}
});
}
Also, I have tried this one too but no execution notice.
Thanks a lot for your help in advance.
After looking through the browser's console, I noticed that the LINQ query was tracking the database and was creating a circular reference so I changed the query to the following and voila!!
public JsonResult FillBusinessLicenceL3(int? selectedID)
{
var bl3_Items = db.LevelThreeItems.
Where(k => k.LevelTwoItem_ID == selectedID).
Select(s => new { LevelThreeItem_ID = s.LevelThreeItem_ID, LevelThreeItem_Name = s.LevelThreeItem_Name });
return Json(bl3_Items, JsonRequestBehavior.AllowGet);
}
There was nothing wrong with the ajax call to the controller.

Joomla 2.5 Ajax component not working

I've been trying for ages to get Json working in Joomla and I just can't do it. I think I've tried every combination of URL etc so any help would be great:
this is for the admin side structure looks like
admin
-controllers
--orderitem.php
-views
--orderitem
---tmpl
----orderitem.php
-controller.php
function updateNow(newrefresh) {
var dataJSON = JSON.encode (newrefresh);
var request = new Request.JSON({
method: 'post',
url: 'index.php?option=com_customersitedetails&view=orderitem&task=refreshscreen&format=raw',
data: {
json: dataJSON
},
onComplete: function(jsonObj) {
alert("Your form has been successfully submitted ");
}
}).send();
};
Although runs the alert box it doesn't retun JSON just
View not found [name, type, prefix]: orderitem, raw, customersitedetailsView
Any ideas where I can start? thanks
You're missing views/orderitem/view.raw.php containing a CustomersitedetailsViewOrderitem class.
views/orderitem/view.raw.php
class CustomersitedetailsViewOrderitem extends JViewLegacy
{
public function display($tpl = null)
{
$response = 'Your magic response here';
echo $response;
JFactory::getApplication()->close();
}
}
You can look here for proper ajax call in joomla
How to Write PHP in AJAX
inside your controllers you should have a file "mycall.json.php" this file will process and return a json format of your ajax call
Joomla doesn't gives a build in AJAX as part of it's system. my answer is from Josef Leblanc course in lynda.com
http://www.lynda.com/Joomla-1-6-tutorials/Joomla-1-7-Programming-and-Packaging-Extensions/73654-2.html
As I said :
Write this i the frontend JS :
$.ajax({
type: 'GET',
url: 'index.php',
data: {option: 'com_componenetname', task: 'taskname.youroperation', format: 'json', tmpl: 'raw'},
dataType: 'json',
async: true, // can be false also
error: function(xhr, status, error) {
console.log("AJAX ERROR in taskToggleSuceess: ")
var err = eval("(" + xhr.responseText + ")");
console.log(err.Message);
},
success: function(response){
// on success do something
// use response.valuname for server's data
}
,
complete: function() {
// stop waiting if necessary
}
});
in the backend you should have a file under com_componentname/controllers/taskname.json.php
the file should look like this
class ComponentnameControllerTaskname extends JControllerLegacy (Legacy only J3.0)
{
public function __construct($config = array())
{
parent::__construct($config);
$this->registerTask('operationname', 'functionname');
}
public function functionname() {
// do something in backend
echo json_encode(array(''var1' => val1, 'var2' => val2 ) );
}
}
nibra - I use this in all my joomla sites and its working perfect. your comment was wrong, pease give me my credit back

Resources