I would really appreciate guidance.
My script will make a call to my server, grab some data and bring it back as JSON. Then I call ServiceSucceeded(msg); I pass in the JSON results in msg. Now in ServiceSucceeded I want to display my results on kendoui grid. That is the part that I can't get to work. It gives no browser errors.
This code might be awful, so please school me on this , thanks!
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" href="../../assets/telerik/styles/kendo.common.min.css" />
<link rel="stylesheet" href="../../assets/telerik/styles/kendo.default.min.css" />
<script src="../../assets/telerik/js/jquery.min.js"></script>
<script src="../../assets/telerik/js/kendo.all.min.js"></script>
</head>
<body>
<div id="grid">
</div>
<div>
<script>
var Type;
var Url;
var Data;
var ContentType;
var DataType;
var ProcessData;
var Username;
var Password;
var qryVar;
var locationName;
function GetAllReportDB() {
var dataId = "1";
Type = "GET";
qryVar = "userName=Simon"
Url = "http://localhost/UserReportMap.svc/GetAllReportDB?" + qryVar;
Data = '{"Contains": "Kir","DBName":"Bony","Operator":"BON0D"}';
ContentType = "application/json; charset=utf-8";
DataType = "json"; ProcessData = true;
Username = "test";
Password = "test";
CallService();
}
function CallService() {
$.support.cors = true;
$.ajax({
cache: false,
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
data: Data, //Data sent to server
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
beforeSend: function (xhr2) {
xhr2.setRequestHeader("Authorization", "Basic " + window.btoa(Username + ':' + Password));
},
success: function (msg) {
ServiceSucceeded(msg);
alert("Succeeded");
},
error: function (errMsg) {
alert("Fail!");
}
});
}
function ServiceSucceeded(msg) {
var myResults = { "d": [{msg}] };
alert(JSON.stringify(msg));
$(function () {
$("#grid").kendoGrid({
dataType: "json",
schem: {
data: "d"
}
//columns: [{ title: "First Name" },
// { title: "Last Name" }]
});
});
}
$(document).ready(
function () {
GetAllReportDB();
}
);
</script>
</div>
</body>
</html>
Well, you have one typo at schem. It should be schema and not schem.
Anyway, I recommend check API docs, there is written what you need.
And to your question:
You are missing dataSource in your grid so it doesn't know from what data grid should be rendered.
$("#grid").kendoGrid({
dataSource: {
type: "json",
data: jsonData,
pageSize: 20
},
...
});
So line var myResults = { "d": [{msg}] }; can be removed and msg data can be assigned into dataSource. Then you will be able to set columns - here demo
And also consider, if you need load your json data in function and result assign into variable. Grid is able to load data from server without that - server just has to return json data, like in this example
Related
I am trying to only parse the information related to a certain "market_name" however I cannot seem to figure out how. The api is located at https://stocks.exchange/api2/ticker which displays information related to the entire exchange. I simply need all of the information returned relating to the "market_name" I am searching for such as ETH_BTC
Ajax:
$.ajax({
url: "https://stocks.exchange/api2/ticker",
dataType: 'json',
success: function(data) {
last = data.last;
console.log(last);
$("#btcprice").text(last);
},
error: function() {
//alert("Was unable to get info!");
}
});
That's because data is an array of objects, not a single object.
Try:
$.ajax({
url: "https://stocks.exchange/api2/ticker",
dataType: 'json',
success: function (data) {
// find object
var market = data.find(function (obj) {
return obj.market_name == 'ETH_BTC';
});
$("#btcprice").text(market.last);
},
error: function() {
//alert("Was unable to get info!");
}
});
Use array filter() method to filter out the record having market_name as ETH_BTC.
array.filter(obj => {
return obj.market_name == 'ETH_BTC'
});
DEMO
var jsonObj = [{"min_order_amount":"0.00000010","ask":"0.00000017","bid":"0.0000001","last":"0.00000010","lastDayAgo":"0.00000009","vol":"154955.9586604","spread":"0","buy_fee_percent":"0","sell_fee_percent":"0","market_name":"ATR_BTC","market_id":338,"updated_time":1527789301,"server_time":1527789301},{"min_order_amount":"0.00000010","ask":"0.000032","bid":"0.000012","last":"0.00003200","lastDayAgo":"0.000065","vol":"372.5011152","spread":"0","buy_fee_percent":"0","sell_fee_percent":"0","market_name":"ETH_BTC","market_id":35,"updated_time":1527789301,"server_time":1527789301},{"min_order_amount":"0.00000010","ask":"0.00003595","bid":"0.00003","last":"0.00003000","lastDayAgo":"0.00003001","vol":"26.44435669","spread":"0","buy_fee_percent":"0","sell_fee_percent":"0","market_name":"ARDOR_BTC","market_id":262,"updated_time":1527789301,"server_time":1527789301}];
var res = jsonObj.filter(obj => {
return obj.market_name == 'ETH_BTC'
});
console.log(res);
$.ajax({
url: "https://stocks.exchange/api2/ticker",
dataType: 'json',
success: function(data) {
var results = [];
var searchField = "market_name";
var searchVal = "ETH_BTC";
for (var i=0 ; i < data.length ; i++)
{
if (data[i][searchField] == searchVal) {
results.push(data[i]);
}
}
$("#btcprice").text(results[0].last);
},
error: function() {
//alert("Was unable to get info!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is a simple code in which you find what you want simply just change searchVal statically or dynamically according to your need......
My project have following structure.
The pages is in the html file. and server request is processed on Page_load in the other aspx page.
I created a sample application to show the error.
Here is the HTML file HTMLPage1.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
var params = 'pak=' + encodeURIComponent('</br>');
debugger;
var url = 'http://localhost:49735/WebForm1.aspx?' + params;
$.ajax({
type: 'POST',
async: false,
url: url,
success: function (data) {
alert('Hi');
}
});
});
</script>
<meta charset="utf-8" />
Here is the PageLoad function in WebForm1.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
var authorize = Request["pak"];
int i = 0;
}
But Request["pak"] is not accessible. I should need to pass pak as </br>
If you want to call web by POST
You should set the data field
like this
$(document).ready(function () {
//var params = 'pak=' + encodeURIComponent('</br>');
debugger;
var url = 'http://localhost:49735/WebForm1.aspx';
$.ajax({
type: 'POST',
async: false,
data:{
pak : encodeURIComponent('</br>')
},
url: url,
success: function (data) {
alert('Hi');
}
});
});
encodeURIComponent('</br>') will encodeURL like "%3C%2Fbr%3E"
You can try to use HttpUtility.UrlDecode() to Decode
var authorize = HttpUtility.UrlDecode(Request["pak"].toString());
You will get </br>
I have a controller which return a model as json object:
[HttpGet("{id}")]
[Route("GetById")]
public async Task <JsonResult> GetById([FromQuery]string id)
{
var myfoo = new {foo="bar", baz="Blech"};
return Json(myfoo);
}
How can handle the returned json object in jQuery?
<script type="text/javascript">
$('#id').change(function () {
var id = $('#id').val();
if (id.length = 17) {
$.ajax(
{
url: '/Home/GetById?id=' + id,
type: 'GET',
jsondata: "",
contentType: 'application/json; charset=utf-8',
success: function (jsondata) {
alert("foo is: " + jsondata ); <---?
},
error: function () {
//alert("error");
}
});
}
});
</script>
I need to get foo value and assigned to an html control
Thanks in advance
all the time I was using capital letter
jsondata.foo // not .Foo
I have a very specific need to serialize a model in the view and then pass it to a controller action at some point. I can get it to work by doing several hacks but its not pretty.
My test controller action
public ActionResult Index()
{
DefaultOptionValueRound defaultOptionValueRound = new DefaultOptionValueRound()
{
OptionId = 1835,
OptionValueId = 40343
};
TestModel testModel = new TestModel()
{
DefaultOptionValueRound = defaultOptionValueRound
};
return View(testModel);
}
The View
#using Common.Repository.Extensions
#model EngA.SandboxApplication.Controllers.TestModel
#Html.Hidden("DefaultOptionValueRound", Html.Raw(Json.Encode(Model.DefaultOptionValueRound)))
<input type="button" value="submit" onclick="SerializeModelTest.processOptionMag()"/>
<script language="javascript">
SerializeModelTest = {
processOptionMag: function () {
//Testing: This Works
//var defaultOptionValueRound = { OptionId: 1834, OptionValueId: 4034377 }
//var data = JSON.stringify({ defaultOptionValueRound: defaultOptionValueRound });
//This Does Not Work
var defaultOptionValueRound = $("#DefaultOptionValueRound").val();
var data = { defaultOptionValueRound: defaultOptionValueRound }; //Stringify Does not work either
$.ajax({
contentType: 'application/json; charset=utf-8',
type: "Post",
cache: false,
url: '#Url.Action("ProcessOptionMag", "SerializeModelTest")',
data: data,
dataType: "json",
traditional: true,
success: function(data) {
alert(data);
}
});
}
}
</script>
The problem is that the serialized model is returned in a stringify form already.
There must be an elegant way of doing this without me have to do JS string manipulation to make it work.
Thank you for your help
I found out that I can un-stringify my result using JSON.Parse and then repackage it with other parameters for sending to the controller.
var defaultOptionValueRound = $("#DefaultOptionValueRound").val();
var data = JSON.stringify({ defaultOptionValueRound: JSON.parse(defaultOptionValueRound) });
Now everything works.
Could not find exact matches for the question (some similar posts found) ..
How can multiple models be send via JSON to MVC3 controller e.g having the following parameters:
public JsonResult Add(Project pr, List<Modules> mod)
{
}
following technique was tried but did not work
function AddModules() {
var pname = $("#ProjectName").val();
var data = new Array();
var modules = new Array();
$("#ModuleTable tr").each(function () {
var row =
{
"ModuleName": $(this).find(".moduleName").val(),
"ModuleDesc": $(this).find(".moduleDesc").val(),
"ModuleSize": $(this).find(".moduleSize").val(),
"StartDate": $(this).find(".startDate").val(),
"ModuleId": "",
"ProjectName": pname
}
modules.push(row);
});
var project =
{
"ProjectName": $("#ProjectName").val(),
"ProjectDescription" : $("#ProjectDescription").val(),
"StartDate" : $("#ProjectStartDate").val(),
"ModuleName" : modules
}
data.push(project);
$.ajax({
url: "AddProject",
data: JSON.stringify(data),
type: "post",
contentType: "application/json; charset = utf-8",
dataType: "json",
success: function (status) {
alert(status);
}
});
}
The project class also contains a List type of Module class.
You are sending a string of JSON back to the server, so you have a type difference. Try something like this instead:
Client Side
var myFunction = function(){
var projectName = $("#ProjectName").val();
var projectDescription = $("#ProjectDescription").val();
$.post("[URL TO YOUR CONTROLLER]",{pName : projectName, pDescription: projectDescription},function(response){
alert(response);
});
};
Server Side
public ActionResult MyActionResult(FormCollection fc)
{
var projectName = fc["pName"];
var projectDescription = fc["pDescription"];
var result = projectName + " hase been posted!";
return Content(result);
}
Good luck!