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 )
Related
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");
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)
});
I have been using this jQuery before I use $.ajax(); and it was working good:
$(document).ready(function(){
var urlSerilize = 'some link';
var appList = $("#applications > li > a");
var appCheck = $('input[type=checkbox][data-level="subchild"]');
var installbtn = $('#submitbtn');
var form = [];
var checked = [];
//var appList = $(".body-list > ul > li");
//var appCheck = $('input[type=checkbox][data-level="subchild"]');
appList.click(function(){
console.log('here!');
if($(this).children().find("input").is(":checked")){
$(this).children().find("input").prop('checked', false);
$(this).children('form').removeClass('checked');
$(this).removeClass("li-checked");
var rmValue = $(this).children('form').attr('id');
form = jQuery.grep(form, function(value) {
return value != rmValue;
});
}else{
$(this).children().find("input").prop('checked',true);
$(this).addClass("li-checked");
$(this).children('form').addClass('checked');
form.push($(this).children('form').attr('id'));
}
console.log(form);
});
installbtn.on('click', function () {
event.preventDefault();
jQuery.each( form, function( i, val ) {
console.log(val);
var request = $.ajax({
url: urlSerilize,
type: 'GET',
data: $('#'+val).serialize(),
success: function( response ) {
console.log( response );
$('#applications').html();
$('#apps_box').html();
}
});
request.done(function(msg){
console.log('Ajax done: ' + 'Yeah it works!!!');
});
request.fail(function(jqXHR, textStatus){
console.log('failed to install this application: ' + textStatus);
});
});
});
});
but after I used this ajax code the .click() jQuery event don't work anymore:
$(document).ready(function() {
/* loading apps */
//console.log('active');
var request = $.ajax({
url: 'some link',
type: 'GET',
dataType: 'html',
data: {id: 0},
})
request.done(function(data) {
console.log("success");
$('#applications').empty().append(data);
})
request.fail(function() {
console.log("error");
})
request.always(function() {
console.log("complete");
});
//end loading apps
var showmore = $('.showapps');
showmore.click(function(){
var parent = $(this).parent('.tv_apps');
var displayC = parent.children('.body-list').css('display');
console.log(displayC);
if (displayC=='none') {
parent.children('.body-list').show('400');
$(this).children().find('img').rotate({animateTo: 180});
}else{
parent.children('.body-list').hide('400');
$(this).children().find('img').rotate({animateTo: 0});
};
});
});
at first place I though it was because of the ajax loads and don't stop, then i was wrong.
I have tried the window.load=function(); DOM function to load the script after Ajax finish loading and also was wrong.
So please if there any idea to fix this problem,
Thanks.
This is the event I want it to be fixed:
appList.click(function(){
console.log('here!');
if($(this).children().find("input").is(":checked")){
$(this).children().find("input").prop('checked', false);
$(this).children('form').removeClass('checked');
$(this).removeClass("li-checked");
var rmValue = $(this).children('form').attr('id');
form = jQuery.grep(form, function(value) {
return value != rmValue;
});
}else{
$(this).children().find("input").prop('checked',true);
$(this).addClass("li-checked");
$(this).children('form').addClass('checked');
form.push($(this).children('form').attr('id'));
}
console.log(form);
});
showmore.click(function(){
should be
$('.showapps').on('click', function(){
OR
$(document).on('click','.showapps', function(){
For dynamically added contents, you need to bind events to it.
For more info: http://learn.jquery.com/events/event-delegation/
Thanks everyone, at last I have found the solution.
It was a question of the DOM, when I use the ready method of jquery it loads an empty ul (without content), so then what I figured out in the first time was correct, all I did is to remove the ready and use a simple function that includes all the .click() events, then call it in request.done();.
This is the solution:
function loadInstaller(){
var urlSerilize = 'some link';
var appList = $("#applications > li");
var appCheck = $('input[type=checkbox][data-level="subchild"]');
var installbtn = $('#submitbtn');
var form = [];
var checked = [];
//...etc
};
$(document).ready(function() {
/* loading apps */
//console.log('active');
var request = $.ajax({
url: 'some link',
type: 'GET',
dataType: 'html',
data: {id: 0},
})
request.done(function(data) {
console.log("success");
$('#applications').empty().append(data);
loadInstaller();
})
//...etc
});
I hope this answer will help someone else :)
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
I am trying to populate a dropdownbox with data from a JSON page.
Here is the code I am using:
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$.ajax({
url: "json/wcf.svc/GetTax",
dataType: 'json',
data: data
});
$($.parseJSON(data.msg)).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#taxList');
});
</script>
And here is what the json data returns:
{"d":"{\"16\":\"hello\",\"17\":\"world\"}"}
I am getting an error that "data is undefined." Do I have to somehow tell JQ how to read the json data?
Firstly, the data variable you are passing to the ajax call is not defined (well, not in the code sample you provided), and secondly the ajax call is happening asynchornously, so you need to do something with the returned data, i.e. via a success callback. Example:
$(document).ready(function () {
var data = //define here
$.ajax({
url: "json/wcf.svc/GetTax",
dataType: 'json',
data: data, // pass it in here
success: function(data)
{
$(data.msg).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#taxList');
}
});
});
also you shouldn't need to parse the data returned from the ajax call, as jQuery will automatically parse the JSON for you, ( should need the $.parseJSON(data.msg))
EDIT
Based on the interesting format of the JSON, and assuming that it cannot be changed, this should work (ugly though)
$(document).ready(function () {
var data = //define here
$.ajax({
url: "json/wcf.svc/GetTax",
dataType: 'json',
data: data, // pass it in here
success: function(data)
{
data = data.d.replace(/{/g, '').replace(/}/g, '').split(',');
var obj = [];
for (var i = 0; i < data.length; i++) {
obj[i] = {
value: data[i].split(':')[0].replace(/"/g, '').replace('\\', ''),
label: data[i].split(':')[1].replace(/"/g, '')
};
}
var htmlToAppend = "";
for (var j = 0; j < obj.length; j++) {
htmlToAppend += '<option value="' +
obj[j].value +
'">' + obj[j].label +
'</option>';
}
$('#taxList').append(htmlToAppend);
}
});
});
You need to use the success option to return the data.
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$.ajax({
url: "json/wcf.svc/GetTax",
dataType: 'json',
success: function(data){
$(data.msg).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#taxList');
}
});
});
</script>