Hani Q Hani Q - 1 month ago 5
Javascript Question

jQuery, Assign td text to a variable and post it

I am relatively new to JavaScript and have a problem I hope your can help

What I am trying to do is this

$("tr:not(:first-child)").each(function(){
var sitename = $("this" + "td:nth-child(1)").text();
var type= $("this" + "td:nth-child(2)").text();
var address= $("this" + "td:nth-child(3)").text();
var city= $("this" + "td:nth-child(4)").text();
var lat= $("this" + "td:nth-child(5)").text();
var long= $("this" + "td:nth-child(6)").text();
var ftime= $("this" + "td:nth-child(7)").text();
$.post('./watchdog.php',{ oadata: sitename});
}).end().remove();


I am selecting the "tr" in a a table except the first one which contains "th". Then I am just stripping the td and assigning the text value to variable. In the end I am posting this data to a PHP script that basically inserts this in a MySQL DB. the problem is i keep getting NULL value in the database.

Here is my Table as generated in the HTML

Site Name Type Address City Lat Long Fault Time
ISB056 Spur Opposite Plot No. 435, Sector I-10/4 Islamabad 73.04393 33.64677 12:02 PM
ISB078 Spur SEECS NUST H-12 Islamabad Islamabad 72.990044 33.64246 12:02 PM

Answer

This

$("this" + "td:nth-child(1)").text()

generates the selector thistd:nth-child(1) which does not make sense at all. I think you want:

$(this).find("td:nth-child(1)").text()

But easier would be to just take an array with e.g.

var data = $(this).children('td').map(function() {
                 return $(this).text();
           }).get();

and then send the data like

$.post('./watchdog.php',{ sitename: data[0], type: data[1],...});