How to fetch particular data in column from JSON with keys - json

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:

Related

Database not updating based on the values from API

I'm trying to update the status for every ticket in the database by fetching all the tickets from database and then passing it to the API.
The API returns me a status which I want to update against every ticket in the database.
My code looks fine to me, but the table is not being updated.
I tried console.log() for both ticketNumber as well as info.status.name, they both are printing correct values as well.
NOTE: URL is a combination of urlcomeshere/ticketNumber
something like https://api-example.com/BCA-123
connection.query(`SELECT ticket_Number FROM tickets`, function(
err,
result,
fields
) {
var totalTickets = result.length;
for (var i = 0; i < totalTickets; i++) {
ticketNumber = result[i].ticket_Number;
var infix = "urlcomeshere/";
infix += ticketNumber;
var options = {
method: "GET",
url: infix,
auth: {
username: "username comes here",
password: "password comes here"
},
headers: {
Accept: "application/json"
}
};
request(options, function(error, response, body) {
info = JSON.parse(body)["fields"];
var updateTickets = `UPDATE tickets SET status = "${info.status.name}" WHERE ticket_Number = "${ticketNumber}"`;
connection.query(updateTickets, function(err, result) {
console.log("Updated ticket Status");
});
});
}
});
Since it is you are calling an async function your application won't know when will it end or execute, and the thread might be ended before your query is executed.
Below the example i tried to separate the query function and promisify it.
Read:
Promisification
const somefunction = () => {
connection.query(`SELECT ticket_Number FROM tickets`, function(
err,
result,
fields
) {
var totalTickets = result.length;
const promises = []
for (var i = 0; i < totalTickets; i++) {
ticketNumber = result[i].ticket_Number;
var infix = "urlcomeshere/";
infix += ticketNumber;
var options = {
method: "GET",
url: infix,
auth: {
username: "username comes here",
password: "password comes here"
},
headers: {
Accept: "application/json"
}
};
promises.push(updateTicketQuery(options, body, ticketNumber))
}
await Promise.all(promises)
});
}
const updateTicketQuery = (options, body, ticketNumber) => {
return new Promise((resolve, reject) => {
request(options, function(error, response, body) {
coonst info = JSON.parse(body)["fields"];
var updateTickets = `UPDATE tickets SET status = "${info.status.name}" WHERE ticket_Number = "${ticketNumber}"`;
connection.query(updateTickets, function(err, result) {
if(err) {
reject(err)
} else {
console.log("Updated ticket Status");
resolve(result)
}
});
});
})
}

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();
});
});

Upload Excel file and download from mysql using Node js

I want to upload Excel sheet and after submit that excel sheet need to insert data into mysql database and same sheet which we upload need to download.
I have tried below code:
Node Service-
function getDetails(req, res) {
var sampleFile, fileInfo = {};
var post = req.body;
var ID= post.id;
var name=post.name
if (!req.files) {
res.send('No files were uploaded.');
return;
}
sampleFile = req.files.fileInputXLSX;
console.log("req.body -- ",req.body);
console.log("Uploaded -- ",sampleFile);
// Get file attributes
var fileId = req.body.fileId;
var fileExtn = sampleFile.name.split(".").pop();
var extractedFilename = sampleFile.name.slice(0, sampleFile.name.lastIndexOf('.'));
var uploadFileName = extractedFilename+'_'+fileId+'.'+fileExtn;
console.log("uploadFileName -- ",uploadFileName);
fileInfo = {
"name": uploadFileName,
"mimetype": sampleFile.mimetype
}
sampleFile.mv(__dirname+'/Myuploads/Details/'+uploadFileName, function(err) {
if (err) {
res.status(500).send(err);
}
else {
// Update file info
var queryString = "INSERT INTO 'details'('id','name') VALUES ('" + ID + "','" + name + "')";
connection.query(queryString, function(err, result) {
if (!err){
var response = [];
response.push({'result' : 'success'});
if (result.length != 0) {
response.push({'data' : result});
} else {
response.push({'msg' : 'No Result Found'});
}
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
} else {
res.status(400).send(err);
}
});
}
});
}
Controller.js
$scope.MyFunction=function(){
var excelForm = new FormData();
excelForm.append('fileInputXLSX', document.getElementById("fileInputXLSX").files[0]);
console.log("---- excelFile : ", document.getElementById("fileInputXLSX").files[0]);
// End : Get File
$http.post(Data.baseNodeService + "getDetails", {
"newProtocolObj": $scope.newProtocolObj
},headconfig).success(function(data, status, headers, config) {
console.log('Details: success');
excelForm.append('fileId', data);
jQuery.ajax({
url: data.baseNodeService + "getDetails",
type: "POST",
cache: false,
contentType: false,
processData: false,
data: excelForm,
success: function(data) {
console.log("---- upload response : ", data);
$scope.goToTfilePage();
}
});
// End : Upload File
}).error(function(map_data, status, headers, config) {
console.log('Details: error');
console.log('status: ', status, '\nmap_data: ', map_data, '\nconfig: ', config);
});
}
Message is coming in console: No file is uploaded.
Please help with the same.It is not upload the file.It is not able to read the response from node service.
I am new in this help in which manner i need to write.
Edit:I am able to upload the file but how to insert into mysql database??

Json result to table

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

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');
});