I am using PivotTable.js
Run-time error and I do not know what is
[HttpGet]
public JsonResult DataResult ()
{
List<jsonList> list = new List<jsonList>();
for (int i = 0; i < 100; i++)
{
jsonList New = new jsonList();
New.Age = i;
if (i % 2 == 0)
{
New.Gender = "Female";
}
else
{
New.Gender= "Male";
}
New.Name= i.ToString();
New.Party = "NDP";
New.Province= "Quebec";
list.Add(New);
}
return Json(list, JsonRequestBehavior.AllowGet);
}
and View
JavaScript code snippet at the bottom
<link href="../../assets/PivotCss/pivot.css" rel="stylesheet" />
<div id="output"></div>
<script src="~/scripts/Pivote/jquery-1.8.3.min.js"></script>
<script src="~/scripts/Pivote/jquery-ui-1.9.2.custom.min.js"></script>
<script src="~/scripts/Pivote/**pivot.js**"></script>
<div id="output"></div>
<script>
$(document).ready(function () {
jQuery.ajax({
type: "Get",
url: "/ReportBuilder/DataResult",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: [],
success: function (data) {
alert(JSON.stringify(data));
$("#output").pivot(
JSON.stringify(data),
{
rows: ["Age"],
cols: ["Province", "Party"]
}
);
}
});
});
</script>
And Alert Result Json
And Firebug Error page
This error is that when run
Thanks for your kindness
Related
I got error like "Failed to load resource: the server responded with a status of 400 ()" when i'm trying to run function ajax in javascript. What to do? Please, help me!
#page
#model IndexModel
#{
ViewData["Title"] = "Home page";
}
<div class="container">
<p id="scanned"></p>
</div>
<script type="text/javascript">
function Q(el) {
if (typeof el === "string") {
var els = document.querySelectorAll(el);
return typeof els === "undefined" ? undefined : els.length > 1 ? els : els[0];
}
return el;
}
var txt = "innerText" in HTMLElement.prototype ? "innerText" : "textContent";
var scannedQR = Q("#scanned");
var args = {
autoBrightnessValue: 100,
resultFunction: function (res) {
[].forEach.call(scannerLaser, function (el) {
fadeOut(el, 0.5);
setTimeout(function () {
fadeIn(el, 0.5);
}, 300);
});
scannedImg.src = res.imgData;
scannedQR[txt] = res.code;
UserCheckId();
}
};
function UserCheckId() {
$.ajax({
contentType: 'application/json; charset=utf-8',
crossDomain: true,
type: "POST",
dataType: "json",
url: '#Url.Action("UserCheckId", "Home")',
data: { qrcode: JSON.stringify(scannedQR[txt]) },
success: function (data) {
alert(data);
}
});
}
</script>
[HttpPost]
[AutoValidateAntiforgeryToken]
public ActionResult UserCheckId(string qrcode)
{
string result = qrcode;
return Json(result, System.Web.Mvc.JsonRequestBehavior.AllowGet);
}
i updated the code and showed where i am calling function "UserCheckId".
i found a solution.
I added below line in Startup.cs in Configure and it worked.
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
I have following the Ajax call method and The asp.net web method.
My asp.net function is returning some values I need those back in Ajax call.
I have tried a lot of things but not succeeded yet.
here is my function, I need to convert my list to JSON:
public List < Node > ReadData() {
SqlConnection conn = new SqlConnection("Data Source=OUMAIMA-PC\\SQLEXPRESS;Initial Catalog=AGIRH;Integrated Security=True");
string query = "SELECT uo,uo_rattachement,lib_reduit FROM UNITE_ORG ";
List < Node > list = new List < Node > ();
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read()) {
list.Add(new Node {
uo = dataReader.GetString(0),
uo_rattachement = dataReader.GetString(1),
lib_reduit = dataReader.GetString(2)
});
}
dataReader.Close();
conn.Close();
return list;
}
**Jquery:**
$(function() {
$.ajax({
type: "POST",
url: 'WebForm1.aspx.cs/ReadData',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(response) {
if (response != null && response.d != null) {
var data = response.d;
alert(typeof(data));
data = $.parseJSON(data);
alert(data.subject);
alert(data.description);
}
}
}; $.ajax(options);
});
});
here is my source code, i us webforms Application and orgchart.js liberary
this aspx.cs source code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace testProjet
{
public partial class WebForm1 : System.Web.UI.Page
{
private object JsonConvert;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["Nodes"] == null)
{
var jsonSerialization = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Node> list = new List<Node>();
list.Add(new Node
{
uo = "1",
lib_reduit = "Name 1"
});
Session["Nodes"] = jsonSerialization.Serialize(list);
}
}
}
public static List<Node> ReadData()
{
SqlConnection conn = new SqlConnection("Data Source=OUMAIMA-PC\\SQLEXPRESS;Initial Catalog=AGIRH;Integrated Security=True");
string query = "SELECT uo,uo_rattachement,lib_reduit FROM UNITE_ORG ";
List<Node> list = new List<Node>();
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
list.Add(new Node
{
uo = dataReader.GetString(0),
uo_rattachement = dataReader.GetString(1),
lib_reduit = dataReader.GetString(2)
});
}
dataReader.Close();
conn.Close();
return list;
}
public static void Add(string uo, string uo_rattachement, string lib_reduit)
{
var jsonSerialization = new System.Web.Script.Serialization.JavaScriptSerializer();
var list = jsonSerialization.Deserialize<List<Node>>((string)HttpContext.Current.Session["Nodes"]);
list.Add(new Node
{
uo = uo,
uo_rattachement = uo_rattachement,
lib_reduit = lib_reduit
});
HttpContext.Current.Session["Nodes"] = jsonSerialization.Serialize(list);
}
public static void Remove(string uo)
{
var jsonSerialization = new System.Web.Script.Serialization.JavaScriptSerializer();
var list = jsonSerialization.Deserialize<List<Node>>((string)HttpContext.Current.Session["Nodes"]);
Node removeItem = null;
foreach (var item in list)
{
if (item.uo == uo)
{
removeItem = item;
break;
}
}
list.Remove(removeItem);
HttpContext.Current.Session["Nodes"] = jsonSerialization.Serialize(list);
}
public static void Update(Node oldNode, Node newNode)
{
var jsonSerialization = new System.Web.Script.Serialization.JavaScriptSerializer();
var list = jsonSerialization.Deserialize<List<Node>>((string)HttpContext.Current.Session["Nodes"]);
foreach (var item in list)
{
if (item.uo == newNode.uo)
{
item.uo_rattachement = newNode.uo_rattachement;
item.lib_reduit = newNode.lib_reduit;
break;
}
}
HttpContext.Current.Session["Nodes"] = jsonSerialization.Serialize(list);
}
}
}
and this is my aspc code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="testProjet.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title> OrgChart</title>
<script src="OrgChart.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<style>
html, body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
overflow: hidden;
}
#tree {
width: 100%;
height: 100%;
}
.field_0 {
font-family: Impact;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="scm" runat="server" EnablePageMethods="true" />
<div id="tree">
</div>
</form>
<script >
var chart = new OrgChart(document.getElementById("tree"), {
nodeBinding: {
field_0: "UO",
field_1:"Uo_Rattachement"
},
menu: {
pdf: { text: "Export PDF" },
png: { text: "Export PNG" },
svg: { text: "Export SVG" },
csv: { text: "Export CSV" }
},
nodeContextMenu: {
edit: { text: "Edit", icon: OrgChart.icon.edit(18, 18, '#039BE5') },
add: { text: "Add", icon: OrgChart.icon.add(18, 18, '#FF8304') }
},
nodeMenu: {
details: { text: "Details" },
edit: { text: "Edit" },
add: { text: "Add" },
remove: { text: "Remove" }
}
});
$.ajax({
type: "POST",
url: 'WebForm1.aspx.cs/ReadData',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response != null && response.d != null) {
var data = response.d;//this data already json you can iterate with each
$.each(data, function (index, node) {
console.log(node);
});
};
chart.on('add', function (sender, n) {
$.ajax({
type: 'POST',
url: '<%= ResolveUrl("WebForm1.aspx.cs/Add") %>',
data: JSON.stringify(n),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
});
chart.on('remove', function (sender, uo) {
$.ajax({
type: 'POST',
url: '<%= ResolveUrl("WebForm1.aspx.cs/Remove") %>',
data: JSON.stringify({ uo: uo }),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
});
chart.on('update', function (sender, oldNode, newNode) {
$.ajax({
type: 'POST',
url: '<%= ResolveUrl("WebForm1.aspx.cs/Update") %>',
data: JSON.stringify({ oldNode: oldNode, newNode: newNode }),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
});
chart.load(<%= Session["Nodes"] %>);
});
</script>
<select style="position: absolute;right: 90px;top: 30px;color: #7a7a7a;font-size: 14px;padding: 10px;background-color: #F57C00;color: #ffffff;width: 100px;z-index:2;" id="selectTemplate">
<option>luba</option>
<option>olivia</option>
<option>derek</option>
<option>diva</option>
<option>mila</option>
<option>polina</option>
<option>mery</option>
<option>rony</option>
<option>belinda</option>
<option>ula</option>
<option>ana</option>
<option>isla</option>
<option>deborah</option>
</select>
</body>
</html>
First you should make function static and add WebMethod attribute:
[WebMethod()]
public static List<Node> ReadData()
{
//..
}
Then you don't need to convert response to JSON beacuse data is already JSON. You can directly use it as following:
$.ajax({
type: "POST",
url: 'WebForm1.aspx/ReadData',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(response) {
if (response != null && response.d != null) {
var data = response.d;//this data already is json which represent list of Node so that you can iterate with each
$.each(data, function (index, node) {
console.log(node);
});
}
}
};
In addition url must be WebForm1.aspx/ReadData instead of WebForm1.aspx.cs/ReadData
Change the method's return type to JsonResult and return new Json object with subject and desription.
public JsonResult ReadData() {
// Rest of your code
return Json(new { data = list, subject = "My subject", description = "My Description" });
}
Jquery:
$(function () {
$.ajax({
type: "POST",
url: 'Home/ReadData',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
if (response != null && response.data != null) {
var data = response.data;
alert(typeof (data));
alert('subject: ' + response.subject);
alert('description: ' + response.description);
}
}
})
});
Facing error on JSON.stringify(ApplObj) :
How to post this object to controller
JQuery Code -
var ApplName = $("#ApplicantName").val();
var ApplMobile = $("#ApplicantMobile").val();
var ApplEmail = $("#ApplicantEmailId").val();
var ApplFHName = $("#ApplicantFHName").val();
var ApplObj = {
ApplicantName: ApplName, ApplicantMobile: ApplMobile, ApplicantEmailId: ApplEmail, ApplFHName: ApplicantFHName
}
$.ajax({
url: '#Url.Action("SaveApplicatDetail", "Dashboard")',
data: JSON.stringify(ApplObj),
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
}
});
Controller Code...
this jsonresult used for save records and return value...
this code is working in other project....
public JsonResult SaveApplicatDetail()
{
try
{
var resolveRequest = HttpContext.Request;
TicketMasterModel TMM = new TicketMasterModel();
resolveRequest.InputStream.Seek(0, SeekOrigin.Begin);
string jsonString = new StreamReader(resolveRequest.InputStream).ReadToEnd();
if (jsonString != null)
{
TMM = (TicketMasterModel)js.Deserialize(jsonString, typeof(TicketMasterModel));
}
int TicketId = 0;
using (var db = new UnitOfWork())
{
DAL.tbl_TrnTicketMaster TM = new DAL.tbl_TrnTicketMaster();
TM.ApplicantName = TMM.ApplicantName;
TM.ApplicantMobile = TMM.ApplicantMobile;
TM.ApplicantEmailId = TMM.ApplicantEmailId;
TM.ApplicantFHName = TMM.ApplicantFHName;
TM.FK_CompanyId = 1;
TM.CustomerId = UserSession.UserId;
TM.IsSubmissionLocked = false;
TM.CreatedBy = UserSession.UserId;
db.tbl_TrnTicketMaster.Insert(TM);
TicketId = TM.PK_TicketId;
}
return Json(TicketId, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
throw;
}
}
basically JSON.stringify turns a Javascript object into JSON text and stores that JSON text in a string.
try this,
var ApplName = $("#ApplicantName").val();
var ApplMobile = $("#ApplicantMobile").val();
var ApplEmail = $("#ApplicantEmailId").val();
var ApplFHName = $("#ApplicantFHName").val();
var ApplObj = {
'ApplicantName': ApplName, 'ApplicantMobile': ApplMobile, 'ApplicantEmailId': ApplEmail, 'ApplFHName': ApplicantFHName
}
$.ajax({
url: '#Url.Action("SaveApplicatDetail", "Dashboard")',
data: JSON.stringify(ApplObj),
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
}
});
Problem Resolved -
"JSON.stringify" is used array to convert it.
var ApplName = $("#ApplicantName").val();
var ApplMobile = $("#ApplicantMobile").val();
var ApplEmail = $("#ApplicantEmailId").val();
var ApplFHName = $("#ApplicantFHName").val();
var ApplDetails = {
ApplicantName: ApplName,
ApplicantMobile: ApplMobile,
ApplicantEmailId: ApplEmail,
ApplicantFHName: ApplFHName
}
var ApplObj = { ApplicantDetail: ApplDetails };
$.ajax({
url: '#Url.Action("SaveApplicatDetail", "Dashboard")',
data: JSON.stringify(ApplDetails),
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
}
});
I have been trying for 4 days to solve this problem. But I cannot return json data into a new tab page.
My code:
<script type="text/javascript">
function CustomerId() {
var url = "Home/PanelGoster"; // My URL
var veri = {
Id: Id.GetValue(),
};
$.ajax({
url: "/Home/PanelGoster",
type: "POST",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(veri),
success: function (mydata) {
if (mydata.error6 == true) {
}
else { // Success
var something = window.open(url, '_blank'); // Problem Here , it does not work
something.focus(); // Problem Here
("#MusterilerGetir").html(mydata); // Problem Here, should be displayed in a new tab
}
},
error: function () {
}
});
return false;
}
</script>
Controller:
public ActionResult PanelGoster(MyModel model)
{
var stringView = RenderRazorViewToString("PartialView", MyModel());
return Json(stringView, JsonRequestBehavior.AllowGet);
}
}
try
something = window.open("data:text/json," + encodeURIComponent(mysdata),
"_blank");
something.focus();
from Open a new tab/window and write something to it?
I'm trying to create a page with fields, that use autocomplete function.
The first field - "ana" works fine. The second fails. I don't see any errors in the console. The prompt doesn't appear.
Here the snippet:
<script src="/inc/jquery-1.8.3.js"></script>
<script src="/inc/jquery-ui.js"></script>
<link href="/inc/jquery-ui.css" rel="stylesheet" type="text/css"/>
<table>
<tr>
<td>Ticker:</td><td><input type="text" name="ana" /></td>
</tr>
<tr>
<td>Cmp: </td><td><input type="text" name="sou" /></td>
</tr>
</table>
<div id="result" style="margin-top:25px;"></div>
<script language="javascript">
$(document).ready(function() {
ana = [ <% getAna %>];
$("input[name='ana']").autocomplete({ source: ana });
sou = [ <% getSou %>];
$("input[name='sou']").autocomplete({ source: sou});
});
</script>
I' cutting getAna and getSou. These works. Here the js/html source code:
<script language="javascript">
$(document).ready(function() {
ana = [ "Aar Edw"];
$("input[name='ana']").autocomplete({ source: ana });
sou = [ "A&A Equity Research"];
$("input[name='sou']").autocomplete({ source: sou});
});
</script>
try this
$(document).ready(function () {
var ana = Array();
$.ajax({
type: "POST",
url: "pagename.aspx/GetAna", //GetAna must be public static web method
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
$.map(data.d, function (item) {
ana.push(item.name);
})
}
});
$("input[name='ana']").autocomplete({ source: ana });
var sou = Array();
$.ajax({
type: "POST",
url: "pagename.aspx/GetSou", //GetSou must be public static web method
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
$.map(data.d, function (item) {
ana.push(item.name);
})
}
});
$("input[name='sou']").autocomplete({ source: sou });
});
in code behind
[WebMethod]
public static List<valuepair> GetAna()//example method same method for GetSou
{
List<valuepair> lstvaluepair = new List<valuepair>();
// ResumeFromBAL objResumeFromBAL = new ResumeFromBAL();
// ResumeFrom objResumeFrom = new ResumeFrom();
DataSet ds = new DataSet();//use your code to get dynamic data
// ds = objResumeFromBAL.GetANA();
if (ds.Tables.Count > 0)
{
foreach (DataRow item in ds.Tables[0].Rows)
{
lstvaluepair.Add(new valuepair() { name = item["ResumeFromName"].ToString(), value = item["ResumeFromId"].ToString() });
}
}
return lstvaluepair;
}
public class valuepair
{
public string name { get; set; }
public string value { get; set; }
}