JQuery does not fetch and parse json from url - javascript

I have been developing an app to connect with an API I recently built for testing (It is working fine) but I deem to be getting an unknown error with my code. I am a newbie trying out jQuery. This is my code:
$(document).ready(function(){
$.ajax({
url: 'api.lynmerc-enterprise.com/requests',
async: false,
type: 'GET',
//dataType: 'json',
success: function(data){
console.log(data);
var data2 = jQuery.parseJSON(data);
console.log(data2);
//assign parsed JSON to variables
var apiStatus = data2.status;
var apiMessage= data2.message;
var apiData = data2.data;
var data3 = $.parseJSON(apiData);
//Here we get Requester info and material JSON
console.log(data3);
var materials = data3.material;
var data4 = $.parseJSON(materials);
console.log(data4);
//loop through the data and assign needed info to table
$.each(data3, function(i,row){
var dateRequested = data3.date;
var projectCode = data3.p_code;
var requestNumber = data3.rq_no;
var materialName = data4.name;
var purpose = data4.purpose;
var quantity = data4.quantity;
var cost = data4.cost;
var total = data4.total;
$("table.table").append("<tr><td>"+dateRequested+"</td><td>"+projectCode+"</td><td>"+requestNumber+"</td><td>"+materialName+"</td><td>"+purpose+"</td><td>"+quantity+"</td><td>"+cost+"</td><td>"+total+"</td></tr>");
});
},
//error: function(){console.log('Error Encountered')},
beforeSend: setHeader()
});
});
//set required headers
function setHeader(xhr){
xhr.setRequestHeader('Api-Key','ZHhjZmIyMHdnazVtdWw=');
xhr.setRequestHeader('Content-Type','application/json')
}
The code is supposed to connect to the API with the Api-Key as a header then fetch Json of format
{
'status':success,
'data':'[{
"p_code":,"requester_id":,
"date":,"rq_no":,
"id":, "materials":[{
"name":,
"purpose":,
"cost":,
"quantity":,
"status":,
"rq_no":,"id":,
"total":},
...
]}
.....
]'
... The data is to be assigned to variables then appended to the main HTML table

I finally had it working perfectly:
<script type="text/javascript">
function fetchJson(){
$(document).ready(function(){
$.ajax({
url: 'http://api.lynmerc-enterprise.com/requests',
headers: {
'Api-Key':'ZHhjZmIyMHdnazVtdWw='
//'Content-Type':'application/json'
},
//async: false, //return value as variable not to make an async success callback
type: 'GET',
dataType: 'json',
success: function(data){
console.log(data);
//var data2 = JSON.parse(data.data);
var data2 = data.data;
var data2Array = [];
$.each(data2, function(idx, data2){
console.log(data2.p_code);
console.log(data2.date);
console.log(data2.rq_no);
var userfo = data2.user;
console.log(userfo.fullname);
console.log(userfo.project_site);
var material = data2.materials;
var dateRequested = data2.date;
var requestNumber = data2.rq_no;
var requester = userfo.fullname;
var projectSite = userfo.project_site;
$.each(material, function(idx, material){
console.log(material.name);
console.log(material.purpose);
console.log(material.quantity);
console.log(material.cost);
console.log(material.total);
console.log(material.status);
var materialName = material.name;
var purpose = material.purpose;
var quantity = material.quantity;
var cost = material.cost;
var total = material.total;
var requestStatus = material.status;
/*$('#dateRequested').append(dateRequested);
$('#requestNumber').append(requestNumber);
$('#requester').append(requester);
$('#projectSite').append(projectSite);
$('#materialName').append(materialName);
$('#purpose').append(purpose);
$('#quantity').append(quantity);
$('#cost').append(cost);
$('#total').append(total);
$('#requestStatus').append(requestStatus); */
var table = $("#requestsTable");
table.append("<tr><td>"+dateRequested+
"</td><td>"+requester+
"</td><td>"+projectSite+
"</td><td>"+requestNumber+
"</td><td>"+materialName+
"</td><td>"+purpose+
"</td><td>"+quantity+
"</td><td>"+cost+
"</td><td>"+total+"</td></tr>");
});
});
},
error: function(){console.log('Error Encountered')},
//beforeSend: setHeader()
});
});
/* var request;
function setHeader(request){
request.setRequestHeader('Api-Key','ZHhjZmIyMHdnazVtdWw=');
request.setRequestHeader('Content-Type','application/json')
}*/
}
</script>
When using dataType:'json' in the code, we dont parse the json again as jQuery does all that so when we try to parse again it returns an error. Then for it to be appended to html we use $(selector).append where the selector is the element id. In this case when appending to table, we append to so it will be $(#tableBodyId).append("what to append");

Related

ParsIng BIng Image Search using JQuery or Javascript Errors

I can successfully parse Bing Search JSON API correctly. Using Version 7 of both Web Search and Images. For some reason JSONLint is correct for images but but can not parse a damn thing. My JQuery code is below Thanks in advance!
////JQUERY CODE
$(document).on("click", "#i-search", function () {
//API URL
var uri = 'bing-img.php';
//SEARCH PARAMETERS
var e = escape($('#book').val());
var pg = escape($('#pg').val());;
var limit = escape($('#limit').val());;
var market = "en-us";
$.ajax({
url: uri,
method: "GET",
data: { q:e, s:limit, p:pg, m:market },
success: function(data) {
var obj = JSON.parse(data)
//SEARCH RESULTS
var ocean = obj.value; //client prop is an array
for(var i = 0; i < ocean.length; i++){
//alert(ocean[i].thumbnail);
var ocean_format = '<p>' + ocean[i].name +'</p>';
$("#bookout").append(ocean_format);
}//END SEARCH RESULTS
$("#moreout").html(more);
},
error: function() {
// console.log(data);
}
});
}); //END IMAGE SEARCH SUBMIT
/////// VALID BING IMAGE JSON ////////////
https://0ct0p.us/bing-img.php?q=mazda&s=2&p=0&m=en-us
/////CROSS ORGIN ERROR ON FIREFOX
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSMissingAllowOrigin

Only add data to ajax call if it isnt a null value

I have this div
<div class='additional_comments'>
<input type="text" id='additional_comments_box', maxlength="200"/>
</div>
Which will only sometimes appear on the page if jinja renders it with an if statement.
This is the javascript i have to send an ajax request:
$(document).ready(function() {
var button = $("#send");
$(button).click(function() {
var vals = [];
$("#answers :input").each(function(index) {
vals.push($(this).val());
});
vals = JSON.stringify(vals);
console.log(vals);
var comment = $('#additional_comments_box').val();
var url = window.location.pathname;
$.ajax({
method: "POST",
url: url,
data: {
'vals': vals,
'comment': comment,
},
dataType: 'json',
success: function (data) {
location.href = data.url;//<--Redirect on success
}
});
});
});
As you can see i get the comments div, and I want to add it to data in my ajax request, however if it doesnt exist, how do I stop it being added.
Thanks
You can use .length property to check elements exists based on it populate the object.
//Define object
var data = {};
//Populate vals
data.vals = $("#answers :input").each(function (index) {
return $(this).val();
});
//Check element exists
var cbox = $('#additional_comments_box');
if (cbox.length){
//Define comment
data.comment = cbox.val();
}
$.ajax({
data: JSON.stringify(data)
});

Inserting records into MySQL with node.js

Fetching records from a form with ajax to insert into mysql with node.js but only the first column works. The rest of the columns do not insert. Below is my code. What am I doing wrong? Thanks
Ajax
$(document).ready(function (e) {
$("#new-user-form").on('submit',(function(e) {
e.preventDefault();
var data = {};
data.title = $('#title').val();
data.fname = $('#fname').val();
data.mname = $('#mname').val();
data.lname = $('#lname').val();
data.mdname = $('#mdname').val();
$('#loading').show();
//toastr.success('Page Loaded!');
$.ajax({
url: "/new-user",
type: "POST",
data: data,
dataType: 'application/json',
cache: false,
success: function(data)
{
console.log('working');
$('#loading').hide();
}
});
}));
});
new-user.js
var express = require('express'),
router = express.Router(),
db = require('./../db');
router.post('/', function (req,res,next) {
var title = req.body.title;
var first_name = req.body.fname;
var middle_name = req.body.mname;
var last_name = req.body.lname;
var maiden_name = req.body.mdname;
db.insert({first_name:first_name},{last_name:last_name}).into('users').then(function(data){
//res.send(data);
})
});
Do you use https://github.com/felixge/node-mysql?
Try pass the object as one:
db.insert({first_name:first_name, last_name:last_name})
Insted of
db.insert({first_name:first_name},{last_name:last_name})

Reading data from table (HTML, JAVAscript)

I have this table that receive from the server:
(with ajax):
$.each(data, function(i, item) {
$('#MyTable tbody').append("<tr>"d
+"<td>" +data[i].A+ "</td><td>"
+data[i].B
+"</td><td><input type='text' value='"
+data[i].C+"'/></td><td><input type='text' value='"
+ data[i].D+"'/></td>"
+ "</tr>");
});
C and D are edit text, that the user can change. after the changing by the user I want to "take" the all new data from the table and send it by ajax with JSON.
how can I read the data to a JSON?
I start to write one but I am stuck on:
function saveNewData(){
var newData= ...
$.ajax({
type: "GET",
url: "save",
dataType: "json",
data: {
newData: newData},
contentType : "application/json; charset=utf-8",
success : function(data) {
...
},
error : function(jqXHR, textStatus, errorThrown) {
location.reload(true);
}
});
}
thank you
Try something like this,
function getUserData()
{
var newData = new Array();
$.each($('#MyTable tbody tr'),function(key,val){
var inputF = $(this).find("input[type=text]");
var fileldValues = {};
fileldValues['c'] = $(inputF[0]).val();
fileldValues['d'] = $(inputF[1]).val();
//if you want to add A and B, then add followings as well
fileldValues['a'] = $($(this).children()[0]).text();
fileldValues['b'] = $($(this).children()[1]).text();
newData.push(fileldValues);
});
return JSON.stringify(newData);
}
function saveNewData(){
var newData = getUserData();
$.ajax({
type: "GET",
url: "save",
dataType: "json",
data: {
newData: newData},
contentType : "application/json; charset=utf-8",
success : function(data) {
...
},
error : function(jqXHR, textStatus, errorThrown) {
location.reload(true);
}
});
}
http://jsfiddle.net/yGXYh/1/
small demo based on answer from Nishan:
var newData = new Array();
$.each($('#MyTable tbody tr'), function (key, val) {
var inputF = $(this).find("input[type=text]");
var fileldValues = {};
fileldValues['c'] = $(inputF[0]).val();
fileldValues['d'] = $(inputF[1]).val();
newData.push(fileldValues);
});
alert(JSON.stringify(newData));
use the jquery on event binding
try somthing like this. Fiddler Demo
$('#MyTable').on('keyup', 'tr', function(){
var $this = $(this);
var dataA = $this.find('td:nth-child(1)').text() // to get the value of A
var dataB = $this.find('td:nth-child(2)').text() // to get the value of B
var dataC = $this.find('td:nth-child(3)').find('input').val() // to get the value of C
var dataD = $this.find('td:nth-child(4)').find('input').val() // to get the Valur of D
// $.ajax POST to the server form here
// this way you only posting one row to the server at the time
});
I don't normaly do that I would use a data binding libarray such as Knockoutjs or AngularJS

javascript data scraping wikipedia table

I'm trying to scrape this page
<script>
var convertToInt;
var allData = [];
$.ajax({
url: "http://en.wikipedia.org/wiki/Demographics_of_Europe",
type: 'GET',
cache: false,
success: function(data) {
var root, body, table;
root = $("<div></div>")
root.html(data.responseText)
var rows = root.find("table tr:not(:has(th))");
$.each(rows, function(index, value) {
var datatest = $(this.find("td"));
console.log(datatest);
});
},
error: function() {
return console.log("error");
}
});
But the console returns the error "Uncaught TypeError: Object #<HTMLTableRowElement> has no method 'find'"
It should be
datatest = $(this).find("td");
You missed the )

Categories