var DataSourceTree = function (options) {
this.url = options.url;
}
DataSourceTree.prototype = {
data: function (options, callback) {
var self = this;
var $data = null;
var param = null
if (!("name" in options) && !("type" in options)) {
param = 0; //load the first level
} else if ("type" in options && options.type == "folder") {
if ("additionalParameters" in options && "children" in options.additionalParameters) {
param = options.additionalParameters["id"];
}
}
if (param != null) {
$.ajax({
url: this.url,
data: 'id=' + param,
type: 'POST',
dataType: 'json',
success: function (response) {
callback(response)
},
error: function (response) {
console.log(response);
}
})
}
}
};
$('#tree2').admin_tree({
dataSource: new DataSourceTree({ url: 'AccountTree.ashx' }),
loadingHTML: '<div class="tree-loading"><i class="fa fa-spinner fa-2x fa-spin"></i></div>',
'open-icon': 'fa-folder-open',
'close-icon': 'fa-folder',
'selectable': false,
'multiSelect': false,
'selected-icon': null,
'unselected-icon': null
});
this JSON data i revived from AccountTree.ashx
{\"data\":[{\"id\":1,\"name\":\"label 1\",\"type\":\"folder\",\"additionalParameters\":{\"id\":1,\"children\":true,\"itemSelected\":false,\"name\":\"test\",\"type\":\"item\"}}]}
i know there is something wrong in callback(response)
http://i.stack.imgur.com/6DEtr.png
must be label1 --> item
It seems that your data source function is not changing the URL you are getting JSON from.
When a folder node is opened it uses whatever JSON the datasource gives it. Use the attr key and the event opened.fu.tree to give your nodes data attributes that will then inform/manipulate your datasource and tell it what URL and thus JSON to load.
Related
Hi ihave this input with type file with multiple select enabled.
i need to get the files from the file input and pass it to my webmethod but i'm getting none in my webmethod, i've read that prop return a list, i have this code in jquery
function post_RepAttach(){
var params = {
Ocap_no:$('#txtOcapNo').val(),
file_Name:$('#FileUpload1').prop("files")[0]
}
var files = $('#FileUpload1').prop("files")[0];
alert(files);
$.ajax({
type: 'POST',
contentType: 'application/json',
url: baseUrl + 'Create-OCAP.aspx/post_attachment_rep',
data: JSON.stringify(params),
dataType: 'json',
success: function (data) {
var response = data;
if (typeof callback != 'undefined') {
//hideLoadingGif();
//callback(response);
}
},
error: function (xhr, status, error) {
//hideLoadingGif();
console.log(xhr, status, error);
}
});
}
i have try this $('#FileUpload1').prop("files") remove the [0] but still no luck
and here's my webMethod
[WebMethod]
public static string post_attachment_rep(string Ocap_no, List<string> file_Name)
{
OcapDataAccess ODA = new OcapDataAccess();
bool result;
result = ODA.insert_reports(HttpContext.Current.Request.MapPath("~/OCAP/files/Reports/" + file_Name.ToString()), Ocap_no);
if (result == true)
{
return "1";
}
else
{
return "0";
}
}
but the file_Name count is zero even if i selected files
how can i achive it.
Hope you understand what i mean
var fileNames = $.map( $('#FileUpload1').prop("files"), function(val) { return val.name; });
and params is :
var params = {
Ocap_no:$('#txtOcapNo').val(),
file_Name:fileNames }
}
I'm trying to post a single object data to an MVC Controler using JQuery, Below are my codes.
//declare of type Object of GroupData
var GroupData = {};
//pass each data into the object
GroupData.groupName = $('#groupName').val();
GroupData.narration = $('#narration').val();
GroupData.investmentCode = $('#investmentCode').val();
GroupData.isNew = isNewItem;
//send to server
$.ajax({
url: "/Admin/SaveContributionInvestGroup",
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify({ GroupData: JSON.stringify(GroupData) }),
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
Below is my controller.
[HttpPost]
public JsonResult SaveContributionInvestGroup(ContributionInvestmentGroup GroupData)
{
ClsResponse response = new ClsResponse();
ClsContributionInvestmentGroup clsClsContributionInvestmentGroup = new ClsContributionInvestmentGroup();
var userID = (int)Session["userID"];
var sessionID = (Session["sessionID"]).ToString();
if (contributionGroupData != null)
{
//get the data from the cient that was passed
ContributionInvestmentGroup objData = new ContributionInvestmentGroup()
{
contributionInvestmentGroupID = 0,
groupName = GroupData.groupName,
narration = GroupData.narration,
investmentCode = GroupData.investmentCode,
isNew = GroupData.isNew
};
response = clsClsContributionInvestmentGroup.initiateNewContributionInvestmentGroup(sessionID, objData);
}
else
{
response.IsException = true;
response.IsSucess = false;
response.Message = "A system exception occurred kindly contact your Administrator.";
}
return Json(new
{
response.IsSucess,
response.Message
});
}
The issue is, the data is not been posted to the controller, the controller receives a null object.
Kindly assist, would really appreciate your effort, thanks.
Try Like this:
//send to server
$.ajax({
type: "POST",
url: "/Admin/SaveContributionInvestGroup",
dataType: "json",
data: GroupData,
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
in your controller your dont have custom binding to bind JSON to your model thats why you get null in you parameter.
instead just post it as query, try simply changes your ajax option like so:
{
...
contentType: "application/x-www-form-urlencoded", //default:
...,
data: $.param(GroupData),
...
}
and perhaps property names are case sensitive so you will need to change your javascript model's name
This is my view model:
function viewModel() {
var self = this;
self.posts = ko.observableArray();
self.newMessage = ko.observable();
self.error = ko.observable();
and these are my two loads functions:
self.reloadPosts = function () {
$.ajax({
type: "Get",
url: postApiUrl2,
data: { id: $("#Locations").val() },
datatype: "json",
contentType: "application/json"
})
}
self.loadPosts = function () {
// to load existing posts
$.ajax({
url: postApiUrl1,
// data: { id: $("#Locations").val() },
datatype: "json",
contentType: "application/json",
cache: false,
type: 'Get'
})
}
self.loadPosts();
self.reloadPosts();
return self;
here, self.loadPosts is the function with no parameter in it and self.reloadPosts passes selected dropdown id to controller.
My question is-- is it possible to put condition here so that self.reloadPosts should only load data on the view page when it has some data.
Right now, both of these are loading one by one. i want to control it by some condition.this code is in .js file not on .cshtml page.
I am trying something like this but getting uncaught reference errror at first line:
if (id != null) {
self.reloadPosts();
}
else {
self.loadPosts();
}
Can anyone suggest me something how to do it.
I don't know what #locations refers to, but if it's a select list or something try this in the HTML (for example):
<select data-bind="value: locations">
<option>location 1</option>
<option>location 2</option>
<select>
And change the script:
function viewModel() {
var self = this;
// location will be stored here
self.locations = ko.observable();
self.posts = ko.observableArray();
self.newMessage = ko.observable();
self.error = ko.observable();
// we can avoid some repeat code:
self.loadPosts = function () {
// read value
var id = self.locations();
// set url and data
var url = (id) ? postApiUrl2 : postApiUrl1;
var data = (id) ? { id: id } : null;
$.ajax({
type: "Get",
url: url,
data: data,
datatype: "json",
contentType: "application/json"
})
}
self.loadPosts();
return self;
Hope this helps.
I have an MVC application where I am uploading picture files in an application.
The code for this:
var files = $(".uploadFile").data("files");
$.each(files, function (key, value) {
data.append('file', value);
})
$('.userForm *').filter(':input').each(function (index, value) {
data.append(value.id, $("#" + value.id).val());
});
$.ajax({
url: "/Customer/AddCustomer",
type: 'POST',
data: data,
cache: false,
processData: false,
contentType: false,
success: function (data) {
// logic
$.LoadingOverlay("hide");
},
error: function (event, jqxhr, settings, thrownError) {
// logic
$.LoadingOverlay("hide");
}
});
Server code:
public string AddCustomer(HttpPostedFileBase file, Customer customer)
{
// add customer and return to edit view
return partialView("customerEdit");
}
I am trying to figure out how i can add a property to each file that I send?
for example for every file that i add I create a list which I append to the DOM.
In this list there is a checkbox next to each file which indicates if this file(picture) should be the profile picture or not.
How do I append a boelan property to each file?
Thanks to #adeneo my brain got a jump start.
I had to retrhink my strategy here since I did not want to send the extra paramaters as a concatinated string.
I did the following:
In my first post I sent the file and the customer data. I saved the customer in the DB and for the file i stored it in tempdata in order to be able to access it in my second post where i would be savinng the file to the db with desiered extra paramaters.
script:
$.ajax({
url: "/Customer/AddCustomer",
type: 'POST',
data: data,
cache: false,
processData: false,
contentType: false,
success: function (data) {
// "Pictures" is an array that contains objects with all the file names and other properties.
$.ajax({
url: "/Customer/AddCustomerPictures",
type: 'POST',
data: JSON.stringify({ pictureFiles: Pictures}),
contentType: 'application/json; charset=utf-8',
success: function(data) {
//logic
}
});
//logic
},
error: function (event, jqxhr, settings, thrownError) {
//logic
}
});
server code, NOTE entire soloution not included:
public ActionResult AddCustomer(CustomerM customer)
{
var Id = _iScissorFingersManager.AddCustomer(customer.FirstName, customer.LastName, customer.Email,customer.PhoenNumber);
if (Request.Files.Count != 0)
{
TempData["files"] = Request.Files;
TempData["Id"] = Id;
}
// add customer and return to edit view
return PartialView("CustomerEdit", customer);
}
public ActionResult AddCustomerPictures(List<PictureFiles> pictureFiles)
{
var files = (HttpFileCollectionBase)TempData["files"];
var id = (long) TempData["Id"];
if (files != null)
{
foreach (var p in pictureFiles)
{
for (int i = 0; i < files.Count; i++)
{
HttpPostedFileBase hpf = files[i];
p.Name == files[i].FileName && p.IsProfile ? _iScissorFingersManager.UploadCustomerPictures(hpf.InputStream, hpf.ContentType, id, true), _iScissorFingersManager.UploadCustomerPictures(hpf.InputStream, hpf.ContentType, id);
}
}
}
return PartialView("CustomerProfileImage");
}
I am trying to use JQPlot within a VB.NET application under .NET 3.5. On a button click, using jquery, I am trying to populate the JQPlot Chart with JSON derived data using a ASP.NET Webservices Source file (which is part of the solution).
The JSON data is sent by the web service but when it is presented to JQPlot I get the javascript error 'No Data Specified' which is generated by JQPlot code.
My code listing is as follows:
Code to listen for the button to be clicked:
$(document).ready(function () {
$('#<%=btnASMX1.ClientID%>').click(function () {
getElectricDataJSON();
return false;
});
});
Javascript code outside the 'document.ready' function:
function ajaxDataRenderer() {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
//url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "AccountsService.asmx/GetJSONData",
data: "{AccountID: " + $('#<%= hiddenAccountID.ClientID%>').val() + " }",
dataType: "json",
success: function (response) {
var ret = response.d;
// The following two lines just display the JSON data for testing purposes
$('#<%=outputASMX.ClientID%>').empty();
$('#<%=outputASMX.ClientID%>').html("<div>" + ret + "</div>");
return ret;
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
var jsonurl = "./jsondata.txt";
function getElectricDataJSON() {
var ret = ajaxDataRenderer();
var plot1 = $.jqplot('chart2', jsonurl, {
title: "AJAX JSON Data Renderer",
dataRenderer: ret, //$.jqplot.ciParser
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
});
}
The JSON data format is as follows:
[ { "todate": "2013-09-23T00:00:00", "Bill": 7095.65 }, { "todate": "2013-08-22T00:00:00", "Bill": 1137.96 }, { "todate": "2013-07-24T00:00:00", "Bill": 220429.41 }, ... ]
Any help or advice will be appreciated.
Thanks to #Fresh for their quick response. Here is the complete solution to my problem:
Code to listen for the button to be clicked:
$(document).ready(function () {
$('#<%=btnASMX1.ClientID%>').click(function () {
getElectricDataJSON();
return false;
});
});
JS function to get the data from a web service:
function ajaxDataRenderer() {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: "AccountsService.asmx/GetJSONData",
data: "{AccountID: " + $('#<%= hiddenAccountID.ClientID%>').val() + " }",
dataType: "json",
success: function (response) {
ret = response.d; // return response string object
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
Data structure outputted by the web service is:
[ { "todate": "2013-09-23T00:00:00", "Bill": 7,095.65 }, { "todate": "2013-08-22T00:00:00", "Bill": 1,137.96 }, { "todate": "2013-07-24T00:00:00", "Bill": 220,429.41 }, ... ]
Data structure that is expected by JQPlot:
[ [ "2013-09-23T00:00:00", 7095.65 ] , [ "2013-08-22T00:00:00", 1137.96 ], [ "2013-07-24T00:00:00", 220429.41 ], ... ]
Note the removal of the comma's in the 'expected data' Bill field.
And finally, the function getElectricDataJSON() that is being called by btnASMX1 where 'chart2' is the ID of the div tags where the chart will be drawn.
function getElectricDataJSON() {
// Get JSON 'string' object
var ret = ajaxDataRenderer();
// If JSON string object is null, stop processing with friendly message
if (ret == null) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>CHARTS ARE NOT AVAILABLE AT THIS TIME</div>");
return false;
}
// Now push required data into a JSON array object
var sampleData = [], item;
$.each(ret, function (key, value) {
sampleData.push([value.todate, parseFloat(value.Bill.replace(/,/g, ""))]);
});
var plot = $.jqplot('chart2', [sampleData], {
title: 'AJAX JSON Data Renderer',
dataRenderer: sampleData,
...
});
}
The method signature for your datarender (i.e. ajaxDataRender) is wrong. The signature should look like this:
function(userData, plotObject, options) { ... return data; }
(See the documentation here)
In your example you are passing the datarenderer "ret" which is not a function with the correct datarender signature. Also the jsonurl you are passing to getElectricDataJSON() is redundant as at no point in your code is the data from "AccountsService.asmx/GetJSONData" persisted to "./jsondata.txt".
Hence you should change your code to this:
$(document).ready(function(){
function ajaxDataRenderer(url, plot, options) {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
url: url,
dataType: "json",
success: function (response) {
var ret = response;
// The following two lines just display the JSON data for testing purposes
$('#<%=outputASMX.ClientID%>').empty();
$('#<%=outputASMX.ClientID%>').html("<div>" + ret + "</div>");
},
error: function (request) {
$('#<%=outputASMX.ClientID%>').html("<div style='color:red;'>WEBSERVICE UNREACHABLE</div>");
}
});
return ret;
};
var url = "AccountsService.asmx/GetJSONData";
function getElectricDataJSON() {
var plot1 = $.jqplot('chart2', url, {
title: "AJAX JSON Data Renderer",
dataRenderer: ajaxDataRenderer,
});
}