Json result to table - html

I Would like when doing the search the results to be inputed to a table my results are being taken from my web service table
function DoSearch() {
$("#resultsDiv").html("");
var key = { "key": $("#SearchString").val() };
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Stadium.asmx/GetStadiumByName",
data: JSON.stringify(key),
dataType: "json",
async: true,
success: function (result, textStatus) {
if (textStatus == "success") {
for (var i = 0; i < result.d.length; i++) {
$("#resultsDiv").html($("#resultsDiv").html() + result.d[i] + "<br/>");
}
}
},
error: function (result, status, error) {
$("#resultsDiv").html("Error: " + error + " <br/>")
}
});
}
Below is my webservice file this gets all the information im looking for in my search.
[WebMethod]
public object[] GetStadiumByName(string key)
{
List<object> stadiums = new List<object>();
if (key != "")
{
foreach(var Name in db.Stadiums
.Where(a => a.Name.Contains(key))
.ToList())
{
stadiums.Add(Name.Name);
stadiums.Add(Name.Location);
stadiums.Add(Name.Team);
stadiums.Add(Name.Capacity);
}
}
return stadiums.ToArray();
}
}
The search returns the following I want to put that information in a table

Related

How to fix '415 unsupported media error' on ajax post to controller

The instant the post to the controller happens, the screen show the 415 error...so I am thinking that even though the data goes through somehow my json structure must not be correct.
View Ajax:
function SubAll() {
var selectedValues =
$('#timesheet').DataTable().column(0).checkboxes.selected().toArray();
var instructions = []; //create array of objects
for (var i = 0; i < selectedValues.length; i++) {
instructions.push({ TimeId: selectedValues[i] });
}
var jsonObject = { MasterIds: instructions };
$.ajax({
url: "/Admin/ApproveAllTimesheets",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(jsonObject),
success: function (result) {
console.log(result);
},
error: function (xhr, textStatus) {
if (xhr.status == 401) { alert("Session Expired!"); window.location =
"/Account"; }
else {
alert('Content load failed!', "info");
}
}
});
};
Controller:
public IActionResult ApproveAllTimesheets([FromBody]ValueContainer information)
Class Objects:
public class ValueContainer
{
public List<Value> MasterIds { get; set; }
}
public class Value
{
public Guid TimeId { get; set; }
}
Payload:
{"MasterIds":[{"TimeId":"ad98749f-9083-464b-aac2-0d685a7de809"}]}
UPDATE #1
As it turns out the fix is the way I was calling the function. Instead of the button onclick="SubAll()" I replaced that with a simple and used jQuery to intercept the click event, prevent it, and then call into the function...and now no 415 error.
View Button
<button id="ApproveAll" class="btn btn-success">Approve All</button>
View jQuery
$(document).ready(function () {
timesheet = $('#timesheet').DataTable({
responsive: {
details: {
renderer: function (api, rowIdx, columns) {
var data = $.map(columns, function (col, i) {
return col.hidden ?
'<tr data-dt-row="' + col.rowIndex + '"
data-dt-column="' + col.columnIndex + '">' +
'<td>' + col.title + ':' + '</td> ' +
'<td>' + col.data + '</td>' +
'</tr>' :
'';
}).join('');
return data ?
$('<table/>').append(data) :
false;
}
}
},
columnDefs: [
{
targets: 0,
orderable: false,
searchable: false,
checkboxes: true
},
{
targets: 5,
visible: false
},
{
targets: 6,
visible: false
}
],
order: [
[1, 'asc']
]
});
$('#ApproveAll').on('click',
function (e) {
var selectedValues =
$('#timesheet').DataTable().column(0).checkboxes.selected().toArray();
var instructions = []; //create array of objects
for (var i = 0; i < selectedValues.length; i++) {
instructions.push(selectedValues[i]);
}
var jsonObject = { MasterIds: instructions };
$.ajax({
url: "/Admin/ApproveAllTimesheets",
type: "POST",
contentType: "application/json;charset=utf-8",
data: JSON.stringify(jsonObject),
traditional: true,
statusCode: {
415: function () {
Response.redirect("/Admin/Index");
}
},
success: function (result) {
console.log(result);
},
error: function (xhr, textStatus, errorThrown) {
if (xhr.status == 401) { alert("Session
Expired!"); window.location = "/Account"; }
else {
alert('Content load failed!', "info");
}
}
});
e.preventDefault();
});
});

Invalid JSON primitive when sending POST request of stringify objects

I have ajax function where i am sending two stringify objects like this:
function SaveOffsetOrder() {
var temp = sessionStorage.getItem('book');
var viewName = $.parseJSON(temp);
var BookObj = JSON.stringify({ obj: viewName })
var OffsetCommonModel = {
ProductId: $('#OffProductId').val(),
CustomerId: $("#OffCustomerId").val(),
}
var OffsetCommonObj = JSON.stringify({ 'OffsetCommonObj':
OffsetCommonModel });
$.ajax({
contentType: "application/json; charset=utf-8",
type: "Post",
url: "#Url.Content("~/Estimate/CreateOffset")",
data: OffsetCommonObj + '&' + $.param(BookObj),
dataType: 'json',
success: function (data) {
}
});
this is my action method :-
public ActionResult CreateOffset(OffsetCommonModel OffsetCommonObj, CalculationModel obj)
{
// do something with objects
}
but when i check in the console its giving error "Invalid JSON primitive"
where i am doing wrong please help..Thanks
Your data part in ajax should be something like this and no need to stringify objects individually, do that once
function SaveOffsetOrder() {
var temp = sessionStorage.getItem('book');
var viewName = $.parseJSON(temp);
// var BookObj = { obj: viewName }
var OffsetCommonModel = {
ProductId: $('#OffProductId').val(),
CustomerId: $("#OffCustomerId").val(),
}
// var OffsetCommonObj = { 'OffsetCommonObj': OffsetCommonModel };
$.ajax({
contentType: "application/json; charset=utf-8",
type: "Post",
url: "#Url.Content("~/Estimate/CreateOffset")",
data: JSON.stringify({ 'OffsetCommonObj': OffsetCommonModel, 'obj': viewName }),
dataType: 'json',
success: function (data) {
}
});
}

“Invalid JSON primitive” in Ajax processing MVC

I have some problems with an ajax call.
Here is the function:
function jsFunction(value) {
var selectedCompany = document.getElementById("CompanyId");
var selectedCompanyId = selectedCompany.options[selectedCompany.selectedIndex].value;
$.ajax({
type: "POST",
data: { companyId: selectedCompanyId, supplierId: value },
url: "#Url.Action("CheckContract", "PaidWork")",
dataType: 'json',
traditional: true,
contentType: 'application/json; charset=utf-8',
processData: false,
success: function (response) {
if (response != null && response.success) {
document.getElementById("errorMessage").style.display = 'hidden';
alert(response.responseText);
} else {
// DoSomethingElse()
document.getElementById("errorMessage").style.display = 'visible';
alert(response.responseText);
}
},
error: function (response) {
alert("error!"); //
}
});
}
This is the div for the message
<div id="errorMessage" style="display:none"><strong class="alert-danger">#ViewBag.MessageContractNotExist</strong></div>
In my view I have a message which I want to display or not, depends on what response Json send me from controller.
This is the method in controller:
public ActionResult CheckContract(int companyId, int supplierId)
{
bool result = true;
if (!spService.ContractExists(companyId, supplierId, ContractType.SupplierSilviPrio))
{
result = false;
}
if(!result)
{
ViewBag.MessageContractNotExist = "Not exist!!!";
return Json(new { success = false, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
}
return Json(new { success = true, responseText = "Your message successfuly sent!" }, JsonRequestBehavior.AllowGet);
}
The problem is that I keep getting this error: invalid json primitive object
Can you please help me what I miss here? Thanks

How to fetch particular data in column from JSON with keys

I am not sure how to fetch particular data in column from JSON with the help of keys. From ajax request i am getting data from the server but i want to store it in sqlite as the columns in server
$("#xxx").click(function()
{
var e = $("#mob").val();
var p = $("#key").val();
myDB.transaction(function(transaction)
{
transaction.executeSql('CREATE TABLE IF NOT EXISTS User_data (data)', [],
function(tx, result)
{
navigator.notification.alert("table created");
},
function(error)
{
navigator.notification.alert("error, table exists");
});
});
$.ajax
({
url: "http://192.168.1.4/sms/android.php",
type: "GET",
datatype: "json",
data: { type:'login', phone: e, name: p },
ContentType: "application/json",
success: function(response)
{
var valuesInArray = JSON.stringify(response);
var user_data = JSON.parse(valuesInArray);
for(var item in user_data.Users)
{
myDB.transaction(function(transaction)
{
transaction.executeSql('INSERT INTO User_data (id,date_closed) VALUES (item.id,item.date_closed)', [],
function(tx, result)
{
navigator.notification.alert("data inserted");
},
function(error)
{
navigator.notification.alert("error, table exists");
});
});
}
},
error: function(e)
{
alert('Got ERROR: ' + JSON.stringify(e));
}
});
});
here is the image of the data i am getting from the server
DATA IN ALERT BOX
here, i want to fetch each column in the database.
Thankx in advance.
<?php
header('Access-Control-Allow-Origin:*');
pg_connect("host=localhost port=5432 dbname=** user=** password=***");
if(isset($_GET['type']))
{
if($_GET['type'] == "login")
{
$mobile = $_GET['phone'];
$key = $_GET['name'];
$query = "select * from crm_lead where phone='$mobile' and id='$key'";
$result = pg_query($query);
while($myrow = pg_fetch_assoc($result))
{
$recipes[]=$myrow;
}
$output = json_encode(array('Users' => $recipes));
echo "'".$output."';";
}
}
else
{
echo "invalid";
}
pg_close();
?>
Why can't you use the response object directly since it's already a Json object?
var users = response.Users;
for(var i=0; i < users.length;i++)
{
var id = users[i].id;
//do something with id
}
$.ajax
({
url: "http://182.70.240.81:82/sms/android.php",
type: "GET",
datatype: "json",
data: { type: 'login', phone: 9770869868, name: 14 },
ContentType: "application/json",
success: function (response) {
var simpleJson = JSON.parse(response);
var shortName = 'db_test';
var version = '1.0';
var displayName = 'Test Information';
var maxSize = 65536; // in bytes
var db = openDatabase(shortName, version, displayName, maxSize);
db.transaction(function (txe) {
txe.executeSql('DROP TABLE User_data');
txe.executeSql('CREATE TABLE User_data(id INTEGER,date_closed TEXT)');
db.transaction(function (txe1) {
for (var i = 0; i < simpleJson.Users.length; i++) {
txe1.executeSql('INSERT INTO User_data (id,date_closed) VALUES (' + simpleJson.Users[i].id + ',"' + simpleJson.Users[i].date_closed + '")', [],
function (tx, result) {
alert("data inserted");
},
function (error) {
alert("error, table exists");
});
}
});
});
}
});
Remove Single Qoutaion from your json:

Json responseText empty and statusText as error

From mvc 4 action:
[HttpPost]
public ActionResult DoStuff(string str)
{
// Do some things
Response.ContentType = "application/json;charset=utf-8";
Response.StatusCode = someCondition == true ? HttpStatusCode.OK : HttpStatusCode.NotFound);
Response.TrySkipIisCustomErrors = true;
return Json(
new {
object1 = 1,
object2 = someArray[0],
object3 = someArray[1],
object4 = someValue == 4 ? 1 : 0
}
);
}
In jquery ajax:
ajax({
url: '/Ctrler/DoStuff/',
data: { str: someString },
type: 'POST',
dataType: 'json'
}).then(function (data) {
var _response = $.parseJSON(data);
}, function (data) {
var _response = $.parseJSON(data.responseText);
});
data.responseText is empty ("") and statusText is "error". It is not always happening. I have observed that it is happening randomly. Why?
Your data is already being converted to an object from JSON, so you do not need to parse it again. Try this:
ajax({
url: '/Ctrler/DoStuff/',
data: { str: someString },
type: 'POST',
dataType: 'json'
}).then(function (data) {
// use data here...
alert(data.object1);
}, function () {
alert('request failed');
});