jquery -jtable- listAction get object from javascript function - html

Is it possible that listAction not call server function use AJAX , and the function will call to javascript function that return object ?
$('#ExecActDelays').jtable({
actions: {
listAction://get object from javascript no call server method
},
///...
can help me?

thank
i solve my proble, by edit jquery.jtable.js
my script:
function getObject(){
var result={};
result.Result="OK";
var array=[];
//...
{
array.push(new object...);
}
result.Records=array;
return result;
}
$('#ExecActDelays').jtable({
actions: {
listAction: getObject()
},
and in jquery.jtable.js i change
self._ajax({
url: loadUrl,
data: self._lastPostData,
success: function (data) {
self._hideBusy();
//Show the error message if server returns error
if (data.Result != 'OK') {
self._showError(data.Message);
return;
}
//Re-generate table rows
self._removeAllRows('reloading');
self._addRecordsToTable(data.Records);
self._onRecordsLoaded(data);
//Call complete callback
if (completeCallback) {
completeCallback();
}
},
error: function () {
self._hideBusy();
self._showError(self.options.messages.serverCommunicationError);
}
});
}
to:(line 442)
if (typeof loadUrl == "string") {
self._ajax({
url: loadUrl,
data: self._lastPostData,
success: function (data) {
self._hideBusy();
//Show the error message if server returns error
if (data.Result != 'OK') {
self._showError(data.Message);
return;
}
//Re-generate table rows
self._removeAllRows('reloading');
self._addRecordsToTable(data.Records);
self._onRecordsLoaded(data);
//Call complete callback
if (completeCallback) {
completeCallback();
}
},
error: function () {
self._hideBusy();
self._showError(self.options.messages.serverCommunicationError);
}
});
}
else {//no from server method
self._hideBusy();
//Re-generate table rows
self._removeAllRows('reloading');
self._addRecordsToTable(loadUrl.Records);
self._onRecordsLoaded(loadUrl);
//Call complete callback
if (completeCallback) {
completeCallback();
}
}
my complete my jquery.jtable.js

Try do this
function foo(){
return object;// JSON object
}
$('#ExecActDelays').jtable({
actions: {
listAction: foo()
},
///...
OR try this too
var object = null;
function foo(){
object = objectJSON;
}
$('#ExecActDelays').jtable({
actions: {
listAction: object
},
///...

Related

Uncaught SyntaxError: Unexpected number in kendo ui

I have kendo ui popup which sends a request to an action method. The action method returns json and then my code breaks in the kendo.all.min.js file and the error method says Uncaught SyntaxError: Unexpected number
My kendo code below:-
var cloudStore = new kendo.data.DataSource({
//batch: true,
pageSize: 25,
transport: {
create: {
url: "/Admin/AddCloudStore", //(/ControllerName/ActionName)
type: "POST"
},
update: {
url: "/Admin/UpdateCloudStore",
type: "POST"
},
parameterMap: function (data, operation) {
console.table(data);
var result = {};
// For update and create send the entire object
if (operation === "update" || operation === "create") {
return data;
//return JSON.stringify({ service: data });
}
return null;
}
},
schema: {
model: cloudStoreModel,
errors: "error"
},
error: function (e) {
console.log(e);
}
});
Am I suppose to return something else from the action? Any help on the issue would be appreciated
Edit: Okay seems like the problem is with what I am return from my .net action method. Adding my action method below:-
public ActionResult AddCloudStore(DataAccess.Model.domain_config_cloud store)
{
try
{
using (var context = new DataAccess.Model.CondadoMediaVault())
{
if (store.cld_cmp_key <= 0) store.cld_cmp_key = Session["sel_domain_key"].ConvertToLong();
var list = context.domain_config_cloud.Where(x => x.cld_cmp_key == store.cld_cmp_key && x.cld_is_active && x.cld_category == "primary").ToList();
if (list.Count > 0)
return Json("There is already a primary cloud store."); //returning string
long user_key = 0;
long.TryParse(Convert.ToString(Session["user"]), out user_key);
var maxKey = context.domain_config_cloud.OrderByDescending(x => x.cld_key).FirstOrDefault();
if (maxKey == null || maxKey.cld_key == 0)
return Json("Error"); //returning string
else
store.cld_key = maxKey.cld_key + 1;
context.domain_config_cloud.Add(store);
context.SaveChanges();
}
}
catch (Exception ex)
{
MediaVault.BLL.ErrorLoggging.DbExceptionLog.LogError(ex);
}
return Json(store); //returning object
}
So the kendo ui code breaks when a string is returned from the action method. If an object is returned the code does not break. What is the exact return type which is expected by kendo ui?

Nested AJAX call in React redux

So I'm working on some demoware and I have two AJAX calls, the first is just a last modified date, to let me know whether to fetch data from the second. This works, but I feel like there's a smarter way to do this for real applications, and I'm just a UI monkey trying to come up in the world, any advice is much appreciated.
componentDidMount() {
this.getJson();
setInterval(this.getJson.bind(this), 1000);
}
getJson() {
const el = this;
const isModified = (date) => {
let mod = false;
if (this.state.lastModified == date) {
console.log('no change');
} else {
mod = true;
console.log({
'previously modified': this.state.lastModified,
'newly modified': date
});
el.setState({lastModified: date});
}
return mod;
}
this.serverRequest = $.ajax({
url: 'URL_LAST_MODIFIED',
success: function(result) {
const lastModified = $.parseJSON(result).LastModifiedDateTime;
if (isModified(lastModified)) {
$.ajax({
url: 'URL_DATA',
success: function(result2) {
const result2Obj = $.parseJSON(result2);
el.setState({data: result2Obj});
},
error: function(xhr, status, err) {
alert(err.toString());
}
})
}
},
error: function(xhr, status, err) {
}
});
}
I think it is realted to this:
https://github.com/reactjs/redux/issues/1676
The idea is create a action for the first ajax call... and on success dispatch another action to execute the second call.

How to send extjs data via json

i am working extjs. i want to send textfields data via json. So i have written code as-
Ext.define('Balaee.controller.kp.WordController',{
extend: 'Ext.app.Controller',
stores: ['kp.WordStore'],
models: ['kp.WordModel'],
views: ['kp.Word.Word'],
refs:[
{
ref:'wordtext',
selector:'textfield[name=wordtext]'
},
],
init: function() {
console.log('Inside word controller');
this.control(
{
'Word button[action=SearchAction]':
{
click:this.SearchWord
},
});//End of control
},//End of init() function
SearchWord:function(button)
{
var j = Ext.getCmp('wordtext').getValue();
console.log("word is:"+j);
var wordObject = Ext.ModelManager.create(
{
word:Ext.getCmp('wordtext').getValue(),
},'Balaee.model.kp.WordModel');
wordObject.save({
success: function(record, operation)
{
console.log("registration successssssssssss "+record);
},//End of success function
failure: function(record, operation)
{
console.log("Inside failure functionnnnn");
},//End of failure function
callback: function(record, operation)
{
console.log("Inside callback functionnnnnn");
console.log(record);
}//End of callback function
});// End of
},
});//End of Controller
But its always going in failure function. So what additional changes i need to do. please can someone please help me...
Try this to create your instance of WordModel :
var wordObject = Ext.create(
'Balaee.model.kp.WordModel',
{ word : j }
);
Or maybe you need to configure the proxy in the model

jquery validation onSubmit ajax post JSON response

I have a very complicated post using jquery validation and an AJAX post that gets a JSON response back from the server and puts it in a jqGrid... But it seems as though my onsuccess is never being called at any point...
$(document).ready(function () {
$("#formSearchByMRN").validate({
rules: {
MRN: { required: true, minLength: 6 }
},
messages: {
MRN: 'Please Enter a Valid MRN'
},
submmitHandler: function (form) {
e.preventDefault();
animateLoad();
debugger;
var theURL = form.action;
var type = form.methd;
var data = $(this).serialize();
$.ajax({
url: theURL,
type: type,
data: data,
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Empty record") {
$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
return false;
}
});
});
It would seem I never get into the submmitHandler. Event though I manage to get to my server side function and it does return, it prompts my UI to save a file which contains the JSON results...
No good.
Am I going about validating my form before my AJAX post the wrong way? Does anybody have any advice about best practices in validating AJAX posts?
UPDATE... MARK R. This is what I attempted. It seems as though I never get in to the success function... My suspicion is that I am not really posting via ajax, but instead doing a full post. I don't understand why.
$('#submitMRN').click(function () {
$("#formSearchByMRN").validate({
rules: {
MRN: { required: true, minLength: 6 }
},
messages: {
MRN: 'Please Enter a Valid MRN'
}
});
if ($('#submitMRN').valid()) {
$("#list").block({ message: '<img src="../../Images/ajax-loader.gif" />' });
$.ajax({
url: $('#submitMRN').action,
type: $('#submitMRN').method,
data: $('#submitMRN').serialize(),
dataType: "json",
success: function (result) {
debugger;
var data = result;
if (data.split(':')[0] == "Empty record") {
$("#list").unblock();
$('#resultDiv').html('<b><p style="color: #ff00ff">' + data + '</p></b>');
setTimeout(function () {
$('#resultDiv').html("");
}, 10000);
}
else {
binddata(data);
}
}
});
}
});
$('#SubmitButton').click(function (){
//Check that the form is valid
$('#FormName').validate();
//If the Form is valid
if ($('#FormName').valid()) {
$.post(...........
}
else {
//let the user fix their probems
return false;
}
});//$('#SubmitButton').click(function (){

MVC3 return JSON on error instead of HTML [duplicate]

How do I handle exceptions thrown in a controller when jquery ajax calls an action?
For example, I would like a global javascript code that gets executed on any kind of server exception during an ajax call which displays the exception message if in debug mode or just a normal error message.
On the client side, I will call a function on the ajax error.
On the server side, Do I need to write a custom actionfilter?
If the server sends some status code different than 200, the error callback is executed:
$.ajax({
url: '/foo',
success: function(result) {
alert('yeap');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
and to register a global error handler you could use the $.ajaxSetup() method:
$.ajaxSetup({
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('oops, something bad happened');
}
});
Another way is to use JSON. So you could write a custom action filter on the server which catches exception and transforms them into JSON response:
public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new { success = false, error = filterContext.Exception.ToString() },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
and then decorate your controller action with this attribute:
[MyErrorHandler]
public ActionResult Foo(string id)
{
if (string.IsNullOrEmpty(id))
{
throw new Exception("oh no");
}
return Json(new { success = true });
}
and finally invoke it:
$.getJSON('/home/foo', { id: null }, function (result) {
if (!result.success) {
alert(result.error);
} else {
// handle the success
}
});
After googling I write a simple Exception handing based on MVC Action Filter:
public class HandleExceptionAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
{
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.Result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new
{
filterContext.Exception.Message,
filterContext.Exception.StackTrace
}
};
filterContext.ExceptionHandled = true;
}
else
{
base.OnException(filterContext);
}
}
}
and write in global.ascx:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleExceptionAttribute());
}
and then write this script on the layout or Master page:
<script type="text/javascript">
$(document).ajaxError(function (e, jqxhr, settings, exception) {
e.stopPropagation();
if (jqxhr != null)
alert(jqxhr.responseText);
});
</script>
Finally you should turn on custom error.
and then enjoy it :)
Unfortunately, neither of answers are good for me. Surprisingly the solution is much simpler. Return from controller:
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Response.ReasonPhrase);
And handle it as standard HTTP error on client as you like.
I did a quick solution because I was short of time and it worked ok. Although I think the better option is use an Exception Filter, maybe my solution can help in the case that a simple solution is needed.
I did the following. In the controller method I returned a JsonResult with a property "Success" inside the Data:
[HttpPut]
public JsonResult UpdateEmployeeConfig(EmployeConfig employeToSave)
{
if (!ModelState.IsValid)
{
return new JsonResult
{
Data = new { ErrorMessage = "Model is not valid", Success = false },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
try
{
MyDbContext db = new MyDbContext();
db.Entry(employeToSave).State = EntityState.Modified;
db.SaveChanges();
DTO.EmployeConfig user = (DTO.EmployeConfig)Session["EmployeLoggin"];
if (employeToSave.Id == user.Id)
{
user.Company = employeToSave.Company;
user.Language = employeToSave.Language;
user.Money = employeToSave.Money;
user.CostCenter = employeToSave.CostCenter;
Session["EmployeLoggin"] = user;
}
}
catch (Exception ex)
{
return new JsonResult
{
Data = new { ErrorMessage = ex.Message, Success = false },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
return new JsonResult() { Data = new { Success = true }, };
}
Later in the ajax call I just asked for this property to know if I had an exception:
$.ajax({
url: 'UpdateEmployeeConfig',
type: 'PUT',
data: JSON.stringify(EmployeConfig),
contentType: "application/json;charset=utf-8",
success: function (data) {
if (data.Success) {
//This is for the example. Please do something prettier for the user, :)
alert('All was really ok');
}
else {
alert('Oups.. we had errors: ' + data.ErrorMessage);
}
},
error: function (request, status, error) {
alert('oh, errors here. The call to the server is not working.')
}
});
Hope this helps. Happy code! :P
In agreement with aleho's response here's a complete example. It works like a charm and is super simple.
Controller code
[HttpGet]
public async Task<ActionResult> ChildItems()
{
var client = TranslationDataHttpClient.GetClient();
HttpResponseMessage response = await client.GetAsync("childItems);
if (response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
List<WorkflowItem> parameters = JsonConvert.DeserializeObject<List<WorkflowItem>>(content);
return Json(content, JsonRequestBehavior.AllowGet);
}
else
{
return new HttpStatusCodeResult(response.StatusCode, response.ReasonPhrase);
}
}
}
Javascript code in the view
var url = '#Html.Raw(#Url.Action("ChildItems", "WorkflowItemModal")';
$.ajax({
type: "GET",
dataType: "json",
url: url,
contentType: "application/json; charset=utf-8",
success: function (data) {
// Do something with the returned data
},
error: function (xhr, status, error) {
// Handle the error.
}
});
Hope this helps someone else!
For handling errors from ajax calls on the client side, you assign a function to the error option of the ajax call.
To set a default globally, you can use the function described here:
http://api.jquery.com/jQuery.ajaxSetup.