Database Not Showing Data in Json Ajax - json

This is my view file Book.cshtml script section. The problem coming is that it not fetching my data from my database.
Instead it is giving a error:
alert("Failed! Please try again.")
If I truncate the data from the database it shows ONLY the heading "BOOK ID" "BOOK NAME" "BOOK SERIAL NUMBER" "BOOK AUTHER" "BOOK PUBLISHER NAME"
$(document).ready(function () {
// This is for Get All Data
$("#btnAllBook").click(function () {
$.ajax({
url: "#Url.Action("GetAllBook","Books")",
data: "",
type: "GET",
dataType: "json",
success: function (data)
{
loadData(data);
},
error: function () {
alert("Failed! Please try again.");
}
});
});
// this will use for Get Data based on parameter
$("#btnSearch").click(function () {
$.ajax({
url: "#Url.Action("GetBookWithParameter", "Books")",
data: { prefix: $('#txtSearch').val() },
type: "GET",
dataType: "json",
success: function (data) {
loadData(data);
},
error: function () {
alert("Failed! Please try again.");
}
});
});
function loadData(data) {
// Here we will format & load/show data
var tab = $('<table class="myTable"></table>');
var thead = $('<thead></thead>');
thead.append('<th>Book ID</th>');
thead.append('<th>Book Name</th>');
thead.append('<th>Book Serial Number</th>');
thead.append('<th>Book Auther</th>');
thead.append('<th>Book Publisher</th>');
tab.append(thead);
$.each(data, function (i, val) {
// Append database data here
var trow = $('<tr></tr>');
trow.append('<td>' + val.BookID + '</td>');
trow.append('<td>' + val.BookName + '</td>');
trow.append('<td>' + val.BookSerialNumber + '</td>');
trow.append('<td>' + val.BookAuther + '</td>');
trow.append('<td>' + val.BookPublisher + '</td>');
tab.append(trow);
});
$("tr:odd", tab).css('background-color', '#C4C4C4');
$("#UpdatePanel").html(tab);
};
});

Looking into the documentation on http://api.jquery.com/jquery.ajax/, the callback error is called because the request failed. Then, I suggest you to check if the url #Url.Action("GetAllBook","Books") is returning the right string of the url, maybe you are trying to request in a url that doesn't exists.
Another point, being about a GET request, I suggest you to check opening in a browser if this URL that you are trying to return data, is returning the JSON data expected as you need to append to the HTML.

Related

In forge viewer onSelectionEvent this.viewer.getProperties() method does not returns property information when site is opened on mobile

"In forge viewer version 6.* onSelectionEvent this.viewer.getProperties() method does not returns property information when site is opened on mobile but it works fine on desktop. “On mobile a property called propDbLoader is not generated which is responsible to pass the data to the viewer. The same method works fine in version 2.7.* for desktop and mobile both but does not work version 6.*, viewer.getProperties() returns undefined ,while debugging found that when site is opened in mobile its does not find the property propDbLoader under Model.prototype.getPropertyDb = function() {
var data = this.genter code hereetData();
return data && data.propDbLoader;
}; says data.propDbLoader undefined.
PanelObjectExtension.prototype.onSelectionEvent = function (event) {
var viewer = this.viewerApp;
var currSelection = this.viewer.getSelection();
this.viewer.getProperties(currSelection[0], function (objProp) {
if (objProp) {
var Prop = objProp.properties[2];
if (Prop.displayName == 'Test' && Prop.displayValue == 'Test') {
$.ajax({
type: "POST",
url:document.location.origin+'#Url.Action("TestAction", "Test")',
contentType: "application/json; charset=utf-8",
data: '{Test: "' + objProp["Test"] + '" }',
dataType: "json",
cache: false,
headers: { "cache-control": "no-cache" },
success: function (data) {
$('#Test).val(data.Test);
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText
Console.log(errorMessage);
}
});
}
};
}, function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText
Console.log(errorMessage);
alert(errorMessage);
});
};
viewer.getProperties() should return the property information in forge viewer version 6.* .
Unfortunately I was unable to reproduce the issue with Viewer v6.6 on iOS Safari - see live sample here:
viewer.getProperties(4, sb=>alert(JSON.stringify(sb))

Tableau: import JSON data from simple REST call

I have a REST API (served by an external server) replying JSON formatted data.
From what I read from Tableau doc, there's available:
- WebDataConnector but you have to add a JS overload on your webpages, not very suitable for REST APIs
- importing JSON data from file, but doesn't answer my issue
Isn't there a simple way to integrate JSON data requested via REST call ?
You can use WDC, you are wrong that its not suitable for REST API. So you basically need to create 2 functions for getting fields and data for your datasets from API:
myConnector.getSchema = function (schemaCallback) {
$.ajax({
url: apiurl + JSON.parse(tableau.connectionData)['diggerID'] + "/sessions/last/data/one",
type: "GET",
headers: {
'Authorization': 'Token ' + JSON.parse(tableau.connectionData)['apiKey']
},
success: function(response){
var flatten = objectFlatten(response)
var columns = []
for (var key in flatten) {
var id = key.replace(/[^A-Za-z0-9_]+/g, '')
columns.push({
id: id,
alias: key,
dataType: tableauType(flatten[key])
})
}
var table = {
id: "digger_" + JSON.parse(tableau.connectionData)['diggerID'],
alias: tableau.connectionName,
columns: columns
}
schemaCallback([table]);
},
error: function (xhr, ajaxOptions, thrownError) {
tableau.abortWithError("Unable to get data. Make sure you used proper API key and you have at least one session for selected digger with dataset.");
}
});
};
myConnector.getData = function (table, doneCallback) {
$.ajax({
url: apiurl + JSON.parse(tableau.connectionData)['diggerID'] + "/sessions/last/data",
type: "GET",
headers: {
'Authorization': 'Token ' + JSON.parse(tableau.connectionData)['apiKey']
},
success: function(response){
var data = []
for (var i=0; i < response.length; i++) {
var flatten = objectFlatten(response[i])
var rec = {}
for (var key in flatten) {
var id = key.replace(/[^A-Za-z0-9_]+/g, '')
rec[id] = flatten[key]
}
data.push(rec)
}
table.appendRows(data);
doneCallback();
},
error: function (xhr, ajaxOptions, thrownError) {
tableau.abortWithError("Unable to get data. Make sure you used proper API key and you have at least one session for selected digger with dataset.");
}
});
};
For complete code you can check out for source code on github: https://github.com/Diggernaut/diggernaut-wdc

Call JSON method in asp.net mvc without page refresh?

Here is my JSON method in controller
public JsonResult GetNotificationForAll()
{
Int64 userid = Convert.ToInt64(Session["UserID"]);
string searchcriteria = string.Format("N.notificationfor ={0}", 1);
PODService.Notification[] notification = service.GetNotificationBySearchCriteria(searchcriteria);
return Json(notification, JsonRequestBehavior.AllowGet);
}
Here is my script code for JSON method:
var URL6 = "/Home/GetNotificationForAll";
$.getJSON(URL6, "", function (data) {
var x = { "padding-left": "10px" };
$.each(data, function (index, value) {
$("<td>"
+ value["Notification_Name"]
+ "</td>")
.appendTo("#Allnotification").css(x);
});
});
Here is my view:
<div id="Allnotification" style="color:White;float:left;margin-left:10px"> </div>
I want to show data without page refresh.
i have found the solution.
function NotificationForALL() {
$("#Allnotification").empty();
$.ajax({
type: "GET",
url: "#Url.Action("GetNotificationForAll", "Home")",
dataType: "json",
cache: false,
success: function (data) {
$.each(data, function(index, element) {
var x = { "padding-left": "10px" };
$("<td>"
+ element["Notification_Name"]
+ "</td>") .appendTo("#Allnotification").css(x);
});
setTimeout(function(){NotificationForALL();}, 900000);
}
});
}
NotificationForALL();
Hope it will help to someone

How To Reduce Multiple Ajax Calls

I'm Developing A windows Phone 7 Application Using Phone Gap.Language Used[HTML,css,JavaScript]
I'm using A web Service For Get Json Data Web service And Bind In Drop Down List.
In Single Page I'M Using 5 AJAX Calls Ex[Age,Height,Religion,Cast,Country,Language,Status,Education]
My Sample Ajax Call For Age given Below.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "https://www.xxxxxxxx.com/yyyyyyyy/zzzzzzzzzz.svc/GetMasterDataoverHTTPS?AuthToken=" + encodeAuthtoken + "&ListKey=" + encodeListkey + "&ListValue=" + encodeMinAge,
crossDomain: true,
dataType: "jsonp",
success: function (data) {
var result = data;
$.each(result, function (key, value) {
var appenddata = "<option value = '" + value.ListKey + "'>" + value.ListValue + " </option>";
$('#ddlSFromAge').html($('#ddlSFromAge').html() + appenddata);
});
//alert(result);
},
error: errorResponse
});
function errorResponse(xhr, ajaxOptions, thrownError) {
alert('Error on Ajax Call' + '\n Status: ' + xhr.status + '\n Response Text: ' + xhr.responseText + '\n Error: ' + thrownError);
}enter code here
For Each And Ever Drop Down I call Like This . I know This Is Not Good.
Any One Tell Me How To Reduce This AJAX call's [For Each Drop down Separate URL Used]
I am guessing you are using so many ajax calls because the data types are dynamic? If they are not dynamic, then you should really consider using the device sqlite database to store your values and just query that. Documentation can be found here.
If you really really need to make that many calls because the data is dynamic then so be it. But instead of having 5 seperate AJAX functions you can just use 1 function and either pass the function your url you want it to use function ajaxCall('http://www.myserviceurl') or pass it a value to run agains a switch to determine what url to use.
I Changed My Code Like This Credits Go To #Dom
<script type="text/javascript">
doAjaxCall("Country");
doAjaxCall("Language");
doAjaxCall("religion");
doAjaxCall("Caste");
function doAjaxCall(type) {
var url;
switch (type) {
case "Country":
url = "https://www.xxxxxx.com/yyyyyyy/GetCountryoverHTTPS?AuthToken=Z0lFITFVMw==&FormCode=U1A=";
ajaxCall(url, '#ddlCountry');
break;
case "Language":
url = "https://www.xxxxxx.com/yyyyyyy/GetLanguageoverHTTPS?AuthToken=Z0lFITFVMw==&FormCode=U1A=";
ajaxCall(url, '#ddlLanguage');
break;
case "religion":
url = "https://www.xxxxxx.com/yyyyyyy/GetReligionoverHTTPS?AuthToken=Z0lFITFVMw==&FormCode=U1A=";
ajaxCall(url, '#ddlReligion');
break;
case "Caste":
url = "https://www.xxxxxx.com/yyyyyyy/GetMotherTongueoverHTTPS?AuthToken=Z0lFITFVMw==&FormCode=U1A=";
ajaxCall(url, '#ddlMother');
break;
default:
url = ""; //or some other code to execute if type doesnt match anything
}
function ajaxCall(paramurl,paramControlId) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: url,
crossDomain: true,
dataType: "jsonp",
success: function (data) {
var result = data;
$.each(result, function (key, value) {
var appenddata = "<option value = '" + value.ListKey + "'>" + value.ListValue + " </option>";
$(paramControlId).html($(paramControlId).html() + appenddata);
});
//alert(result);
},
error: errorResponse
});
function errorResponse(xhr, ajaxOptions, thrownError) {
alert('Error on Ajax Call' + '\n Status: ' + xhr.status + '\n Response Text: ' + xhr.responseText + '\n Error: ' + thrownError);
}
}
}
</script>`

Unable to recieve JSON from Webmethod using $.getJSON or Ajax call

I have some JSON objects that I want to process on Client Side, but My WebMethod that I specified does not want to fire.
Here is the Ajax and GetJson methods i used in my Client Side Script:
GetSJON
$(document).ready(function() {
$(document).ready(function() {
//attach a jQuery live event to the button
$('#getdata').live('click', function() {
$.getJSON('/Members_Only/StockMovement/WebForm1.aspx/StockPlacementOptions', function(data) {
//alert(data); //uncomment this for debug
// alert(data.item1 + " " + data.item2 + " " + data.item3); //further debug
$('#showdata').html("<p>item1=" + data.item1 + " item2=" + data.item2 + " item3=" + data.item3 + "</p>");
});
});
});
Here is the Ajax
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/Members_Only/StockMovement/WebForm1.aspx/StockPlacementOptions",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
success: function (res) {
$('#Results').append(CreateTableView(res)).fadeIn();
}
});
});
Both of these Methods Call StockPlacementOptions which is my WebMethod that look like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json,
UseHttpGet = true, XmlSerializeString = false)]
public static List<StockReturnMethod> StockPlacementOptions()
{
scmEntitiesPrimaryCon entities = new scmEntitiesPrimaryCon();
var binOptions = (from avail in entities.ProductAvailibleBins(1, 2)
select new StockReturnMethod() { LotID = (int)avail.LotID, LotName = avail.LotName, AreaID = (int)avail.AreaID, AreaName = avail.AreaName, BinID = (int)avail.BinID, BinName = avail.BinName }).ToList();
return binOptions;
}
If I can just get the JSON web Method to fire on $(document).ready event, I will be able to process and work with the data from there. I have also tried looking at a diffrent jQuery library like KnockoutJS with it's data processing capability, also no luck.
I am using ASP Webforms on Framework 4 with Html5 Markup.
Any advice will be greatly appreciated.
Why are you using two document.ready() handlers at your client side getJson and ajax
$(document).ready(function() { // <-------you can remove this handler
$(document).ready(function() {
$('#getdata').live('click', function() {
$.getJSON('/Members_Only/StockMovement/WebForm1.aspx/StockPlacementOptions', function(data) {
//alert(data); //uncomment this for debug
// alert(data.item1 + " " + data.item2 + " " + data.item3); //further debug
$('#showdata').html("<p>item1=" + data.item1 + " item2=" + data.item2 + " item3=" + data.item3 + "</p>");
});
});
}); // <-------you can remove this handler
although i am not sure this could be the issue but try this one if this helps.
I got it fixed by using a combination of KnockoutJS and ajax.
By utilizing the knockoutJS mapping model, I am able to manipulate the returned JSON anyway i want :)
Here is my Jquery that does the Mapping and obtains JSON from server.
<script type="text/javascript">
//Declareing Viewmodel For KnockoutJS
var viewModel;
//Using Mapping Plugin for Knockout JS
function bindModel(data) {
viewModel = ko.mapping.fromJS(data);
console.log(viewModel);
ko.applyBindings(viewModel);
}
//Onload ObtainJSON
$(document).ready(function () {
$.ajax({
url: "WebForm1.aspx/StockPlacementOptions",
// Current Page, Method
data: {},
// parameter map as JSON
type: "POST",
// data has to be POSTed
contentType: "application/json",
// posting JSON content
dataType: "JSON",
// type of data is JSON (must be upper case!)
timeout: 10000,
// AJAX timeout
success: function (result) {
bindModel(result);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
});
</script>
I also changed the Webmethod slightly to obtain the result i wanted:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<StockReturnMethod> StockPlacementOptions()
{
scmEntitiesPrimaryCon entities = new scmEntitiesPrimaryCon();
var binOptions = (from avail in entities.ProductAvailibleBins(1, 2)
select new StockReturnMethod() { LotID = (int)avail.LotID, LotName = avail.LotName, AreaID = (int)avail.AreaID, AreaName = avail.AreaName, BinID = (int)avail.BinID, BinName = avail.BinName }).ToList();
return binOptions;
}
And That's it :D
Thanks for all the help