Loading Database Records into a table using AJAX? - javascript

I have been given a code to modify for database records on a website using ajax.
I have the function correctly querying data but the table displayed does not get any of the records displayed with in it. I have code of the functions and the html below.
Please see this link of current version: http://www.eng.nene.ac.uk/~10406206/CSY2028/Ajax/Ajax.html
Function of loadrecords with a callback not sure why a callback is used
<script language="Javascript">
var xmlHttpReq = false;
var xmlHttpReq2 = false;
var xmlHttpReq3 = false;
function loadDatabaseRecordsCallback ()
{
if (xmlHttpReq.readyState == 4)
{
alert ("From Server (Load Records):List.php" + xmlHttpReq.responseText);
var record = xmlHttpReq.responseXML.getElementsByTagName('record');
var s = "";
for (var i = 0; i < record.length; i ++)
{
var rec = record[i];
var id = rec.getElementsByTagName("ID")[0].firstChild.data;
var carname = rec.getElementsByTagName("CARNAME")[0].firstChild.data;
var fueltype = rec.getElementsByTagName("FUELTYPE")[0].firstChild.data;
var transmission = rec.getElementsByTagName("TRANSMISSION")[0].firstChild.data;
var enginesize = rec.getElementsByTagName("ENGINESIZE")[0].firstChild.data;
var doors = rec.getElementsByTagName("DOORS")[0].firstChild.data;
var total = rec.getElementsByTagName("TOTAL")[0].firstChild.data;
var available = rec.getElementsByTagName("AVAILABLE")[0].firstChild.data;
appendRecord (id, carname, fueltype, transmission, enginesize, doors, total, available);
}
}
}
function loadDatabaseRecords ()
{
// Mozilla/Safari
if (window.XMLHttpRequest)
{
xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject)
{
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
alert ("To Server (Load Records): List.php");
xmlHttpReq.open('GET', "List.php", true);
xmlHttpReq.onreadystatechange = loadDatabaseRecordsCallback;
xmlHttpReq.send(null);
}
on the same page as the function is the table which is below
<body>
<form name="f1">
<input value="Load Database" type="button" onclick='JavaScript:loadDatabaseRecords()'></p>
</form>
<table id="DBTable" border="2">
<tr>
<td width="20">ID</td>
<td width="100">Car Name</td>
<td width="100">Fuel Type</td>
<td width="100">Transmission</td>
<td width="80">Engine size</td>
<td width="20">Doors</td>
<td width="20">Total</td>
<td width="20">Available</td>
</tr>
<form name="myform">
<tr>
<td><input type="text" name="id"></td>
<td><input type="text" name="carname"></td>
<td><input type="text" name="fueltype"></td>
<td><input type="text" name="transmission"></td>
<td><input type="text" name="enginesize"></td>
<td><input type="text" name="doors"></td>
<td><input type="text" name="total"></td>
<td><input type="text" name="available"></td>
<td colspan="2"><input type="button" value="add" onClick="JavaScript:addNewRecord()"></td>
<td colspan="2"><input type="checkbox" value="update" onClick="JavaScript:updateRecord()"></td>
<td colspan="2"><input type="checkbox" value="delete" onClick="JavaScript:deleteRecord()"></td>
</tr>
</form>
</table>
</body>
The function calls the List.php which is coded as follows
<?php
$link = mysql_connect ("194.81.104.22", "********", "*****");
mysql_select_db ("*******");
$query = "SELECT * from XYZ";
$result = mysql_query ($query);
for ($i = 0; $i < mysql_num_rows ($result); $i ++)
{
$row = mysql_fetch_object ($result);
print "<b>Car Name:</b> <i>$row->CARNAME</i><br>";
print "<b>Fuel Type:</b> <i>$row->FUELTYPE</i><br>";
print "<b>Transmission:</b> <i>$row->TRANSMISSION</i><br>";
print "<b>Total:</b> <i>$row->TOTAL</i><br>";
print "<b>Available:</b> <i>$row->AVAILABLE</i><br><br>";
}
mysql_close ($link);
?>
So, if you have seen the website you will see that you press the load database button and a box appears with all the database entries. However, once you press enter the table on the page remains empty.
My question is why?
can you explain to me where the problem is?
New to Ajax and apologies if I broke rules on posts it's my first one.

I am not clear with php, but I remember from my asp + ajax experiences:
You bring data back to your browser, but you should "re-paint" the page - you can do this in javascript, or may-be PHP has some ready solutions for this.
When you validated your method appendRecord receive valid values - find your table (DBTable) with javascript by id, and update the values of the row / columns by your record.
I'd recommend you to take a look on http://www.w3schools.com/php/php_ajax_database.asp

You bring data back to your browser, but you should "re-paint" the page - you can do this in javascript, or may-be PHP has some ready solutions for this.
When you validated your method appendRecord receive valid values - find your table (DBTable) with javascript by id, and update the values of the row / columns by your record.

Related

Reload page every 10 seconds with the table content id

I have a table with a list of customers and its ids. The table content will change (I load data from database).
<table name="myCustomers">
<thead>
<tr><th>Name</th></tr>
</thead>
<tbody>
<tr>
<td>Name1</td>
<input type="hidden" value="1" />
</tr>
<tr>
<td>Name2</td>
<input type="hidden" value="2" />
</tr>
<tr>
<td>Name3</td>
<input type="hidden" value="3" />
</tr>
</tbody>
<table>
My page name is test.cfm
I would like, using JavaScript or JQuery, to refresh the page every 10 seconds, but passing the input hidden value as parameter. For example, first it load the page. Then, after 10 seconds, call test.cfm?myID=1... 10 seconds later, test.cfm?myID=2 and so on.
Is it possible using JavaScript or JQuery?
Thanks
Try writing something in JavaScript to grab data from the web server every ten seconds and print it to the table using innerHTML. Method for getting data from server depends on the format of course.
// Gets any query string variable
function qs(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
// Gets your specific query string variable and parses it as an int
function getQueryStringId() {
var id = parseInt(qs("myId"), 10);
return isNaN(id) ? 0 : id;
}
// Does the redirect/refresh after 10 seconds
function init() {
var baseUrl = [location.protocol, '//', location.host, location.pathname].join('');
var currentId = getQueryStringId();
var nextId = currentId + 1;
var nextUrl = baseUrl + "?myId=" + nextId;
window.setTimeout(function () {
window.location.href = nextUrl;
}, 1000);
}
init();
<html>
<head>
<script src="js/jquery-1.11.1.min.js"></script>
</head>
<body>
<form>
<table name="myCustomers">
<thead>
<tr><th>Name</th></tr>
</thead>
<tbody>
<tr>
<td>Name1</td>
<input type="hidden" value="12" />
</tr>
<tr>
<td>Name2</td>
<input type="hidden" value="24"/>
</tr>
<tr>
<td>Name3</td>
<input type="hidden" value="35" class="key1"/>
</tr>
</tbody>
</form>
<table>
<script>
//use need to use cookie or session to keep track of page number
// create an array to store all form values
var col=0;
url();
var pageno;
function url(){
var values=[];
$("input").each(function(){
// insert form value into array
values.push($(this).val());
});
var length=values.length;
var x = document.cookie;
var t = x.replace("username=","");
if(t==0){
document.cookie = "username="+0;
pageno=values[0];
var addr=location.pathname+"?pageid="+pageno;
window.location.replace(addr);
t++;
document.cookie = "username="+t;
}
else if(t<length){
pageno=values[t];
t++;
document.cookie = "username="+t;
var addr=location.pathname+"?pageid="+pageno;
window.location.replace(addr);
setTimeout(url,5000);
}
else{
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
}
}
</script>
</body>
</html>

Show the correct input file name in a dynamic table

I have a simple add function in my table.
I would like to post the name of each uploaded file on the table, but it seems like it's only working on the first 2 rows due to my var i = 0; is not working properly.
Here is my code:
<table id='datarows'>
<tr>
<td>Upload</td><td>Filename</td>
</tr>
<tr>
<td><input type="file" id="ProductImage" name="ProductImage0" onchange="getFileData(this);"/></td>
<td><input id="filename" name="filename0" type="text" /></td>
</tr>
</table>
ADD NEW PRODUCT<br />
<script>
var i = 0;
function addProduct() {
var str = '<tr><td><input type="file" id="ProductImage'+i+'"
name="ProductImage'+i+'" onchange="getFileData2(this);" /></td>'
str = str + '<td ><input id="filename'+i+'" name="filename'+i+'" type="text"
/></td></tr>';
$('#datterrows').append(str);
}
//----- Upload picture/file and add name table 1
function getFileData(myFile) {
var file = document.getElementById("ProductImage").value;
var msg = document.getElementById("filename");
msg.value = "test"+file;
}
//----- Upload picture/file and add name table 2
function getFileData2(myFile) {
var file = document.getElementById("ProductImage"+i).value;
var msg = document.getElementById("filename"+i);
msg.value = "test" + file;
}
</script>
I don't get any errors but all I see is the my input id keeps repeating it self to be productimage0 and not continuing for each element I add.
I hope someone can help, it's been pain in the a**

Javascript returning correct & undefined value

Sorry the title is vague, but I have a form that accepts multiple id and posts the users input to URL to open x amount of tabs depending on the number of account id's.
The link for the first account id is opening with the values inserted into the form but the second account id is just showing "undefined" and from console looks like the second account id isn't getting past the first declaration but skipping to the second.
<form accept-charset="UTF-8" method="post"><div style="margin:0;padding:0;display:inline">
<table class="vat-tax-processor center-table">
<tbody>
<tr>
<td>
<span class="required">*</span>
AWS Account ID (No Dashes)<br>
</td>
<td><textarea autocomplete="off" id="AccountIDs" name="AccountIDs" value=""></textarea></td>
<tr>
<td>
<span class="required">*</span>
VAT Country <br>
</td>
<td><input autocomplete="off" type="text" value="" id="vatCountryCode" name="vatCountryCode"></td>
</tr>
<tr>
<td>
<span class="required">*</span>
Vat Number<br>
</td>
<td><input autocomplete="off" type="text" value="" id="vatNumber" name="vatNumber"></td>
</tr>
<tr>
<td>
<span class="required">*</span>
Registration Type <br>
</td>
<td><input autocomplete="off" type="text" value="Intra-EU" id="currentState" name="currentState"></td>
</tr>
<tr>
<td>
<span class="required">*</span>
Business Legal Name <br>
</td>
<td><input autocomplete="off" type="text" value="" id="businessLegalName" name="businessLegalName"></td>
</tr>
<tr>
<td>
Here is my js:
function addExemption(){
var AccountIDsArray = $('textarea[id=AccountIDs]').val().split('\n');
var vatCountryCodeArray = $('input[id=vatCountryCode]').val().split('\n');
var vatNumberArray = $('input[id=vatNumber]').val().split('\n');
/*var currentStateArray = $('input[id=currentState]').val().split('\n');*/
var businessLegalNameArray = $('input[id=businessLegalName]').val().split('\n');
console.log('I got past part 1 declarations - No issues here');
$.each(AccountIDsArray, function(index, value){
var AccountID = AccountIDsArray[index];
var vatCountryCode = vatCountryCodeArray[index];
var vatNumber = vatNumberArray[index];
/*var currentState = currentStateArray[index];*/
var businessLegalName = businessLegalNameArray[index];
console.log('I got part part 2 declarations - No issues here either');
console.log(AccountID);
var URL = 'https://linkhere';
var URL_Final = encodeURI(URL);
window.open(URL_Final, '_blank');
}
);
Here is a screenshot of what appears on first link and second link:
Account 1
Account 2
There are a couple issues I see with this.
The window is opening in your loop meaning that it will open a window immediately after the first id is printed to the console. I would move window.open() outside of the $.each.
You are risking out of bounds indexing on vatCountryCodeArray, vatNumberArray, currentStateArray and businessLegalNameArray since they are input elements and not textareas.
The 'Undefined' you see if because your function has no return value. See here.
function addExemption(){
var AccountIDsArray = $('textarea[id=AccountIDs]').val().split('\n');
var vatCountryCodeArray = $('textarea[id=vatCountryCode]').val().split('\n');
var vatNumberArray = $('textarea[id=vatNumber]').val().split('\n');
var currentStateArray = $('textarea[id=currentState]').val().split('\n');
var businessLegalNameArray = $('textarea[id=businessLegalName]').val().split('\n');
console.log('I got past part 1 declarations - No issues here');
$.each(AccountIDsArray, function(index, value){
if(value != null && value != ''){
var AccountID = value;
//var vatCountryCode = vatCountryCodeArray[index];
//var vatNumber = vatNumberArray[index];
//var currentState = currentStateArray[index];
//var businessLegalName = businessLegalNameArray[index];
console.log('I got part part 2 declarations - No issues here either');
console.log(AccountID);
}
});
var URL = 'https://linkhere';
var URL_Final = encodeURI(URL);
window.open(URL_Final,'_blank');
return '';
}
I was able to resolve this like so:
function addExemption(){
var AccountIDsArray = $('textarea[id=AccountIDs]').val().split('\n');
console.log('I got past 1st declarations - No issues here');
$.each(AccountIDsArray, function(index, value){
var AccountID = AccountIDsArray[index];
var vatCountryCode = $('#vatCountryCode').val();
var vatNumber = $('#vatNumber').val();
var businessLegalName = $('#businessLegalName').val();
console.log('I got past 2nd declarations - No issues here either');
console.log(AccountID);
var URL = 'https:xxxxx?accountId=' + AccountID + '&vatCountryCode=' + vatCountryCode + '&vatNumber=' + vatNumber + '&currentState=Intra-EU&businessLegalName=' + businessLegalName + '';
var URL_Final = encodeURI(URL);
window.open(URL_Final, '_blank');
});
}

Php form not working, Works as 2 separate pages but not as 1 combined

OK hi, basically I have a PHP form, so you enter something in the form and then on the next page it will display some data depending upon what you put in. I am trying to put this into one webpage rather than 2. It works fine as 2 seperate webpage but when i tried to combine them it doesn't work.
Since when the person first loads the webpage no form would have been submitted meaning that it cant load any data I've done
if (player1 != "")
so that if the php form has been submitted and then that would be true. Of course that's built upon the assumption that with it not submitted it will equal "".
I'm not sure if that's right so that's something to pay attention to.
Here is the form
<form action="hacker.php" method="post">
<table>
<tr>
<td>Hackers name:</td>
<td>
<input type="text" name="player" value="" maxlength="100" />
</td>
</tr>
<tr>
<tr>
<td> </td>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
And here is the page the form sends information to (hacker.php):
<script>
var yqlcallback = function(data) {
var results = data.query.results;
document.body.innerHTML = results.span;
var percentage = results.span;
rating = percentage.slice(0, -1);
if (rating > 30) {
document.body.innerHTML = "This player has now been banned";
} else {
document.body.innerHTML = "Please submit further evidence to have this person banned";
}
};
</script>
<script id="myscript"></script>
<?php
$player = $_POST['player'];
?>
<script>
var player1 = "<?php echo $player; ?>";
var link1 = "https://query.yahooapis.com/v1/public/yql?q=select%20content%20from%20html%20where%20url%3D%22http%3A%2F%2Fwww.team-des-fra.fr%2FCoM%2Fbf3.php%3Fp%3D";
var link2 = "%22%20and%20xpath%3D'%2F%2F*%5B%40id%3D%22content%22%5D%2Fdiv%5B3%5D%2Fdiv%2Fsp an'&format=json&callback=yqlcallback";
var link = link1 + player1 + link2;
document.getElementById('myscript').setAttribute('src', link);
</script>
I tried to combine those 2 into one php file called index.php and make it so that the javascript will only load data if it gets information from a from but it doesn't seem to be working. Hers what i have:
The form action is index.php and the name of the page is index.php, I've done this because I don't want it to redirect to a separate link once the form is submitted.
<!--This is the form used to submit the info-->
<center>
<form action="index.php" method="post">
<table>
<tr>
<td>Hackers name:</td>
<td>
<input type="text" name="player" value="" maxlength="100" />
</td>
</tr>
<tr>
<tr>
<td> </td>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
<!--This gets the data from another website and displays text depending upon what the value of that data is-->
<script>
if (player1 != "") {
var yqlcallback = function(data) {
var results = data.query.results;
document.body.innerHTML = results.span;
var percentage = results.span;
rating = percentage.slice(0, -1);
if (rating > 30) {
document.body.innerHTML = "This player has now been banned";
} else {
document.body.innerHTML = "Please submit further evidence to have this person banned";
}
};
};
</script>
<!--This is changed so that the src is dependant upon what the person entered into the form, code that does that is below. Code above then reads the data sheet this gets-->
<script id="myscript"></script>
<!--This gets the value from the php form then converts it to javascript and creates a link with it used to get the data on that person-->
<?php
$player = $_POST['player'];
?>
<script>
var player1 = "<?php echo $player; ?>";
var link1 = "https://query.yahooapis.com/v1/public/yql?q=select%20content%20from%20html%20where%20url%3D%22http%3A%2F%2Fwww.team-des-fra.fr%2FCoM%2Fbf3.php%3Fp%3D";
var link2 = "%22%20and%20xpath%3D'%2F%2F*%5B%40id%3D%22content%22%5D%2Fdiv%5B3%5D%2Fdiv%2Fspan'&format=json&callback=yqlcallback";
var link = link1 + player1 + link2;
if (player1 != "") {
document.getElementById('myscript').setAttribute('src', link);
}
</script>
You are defining the player1 variable after it is being checked in the script above. Try moving
<script>
if (player1 != "") {
var yqlcallback = function(data) {
var results = data.query.results;
document.body.innerHTML = results.span;
var percentage = results.span;
rating = percentage.slice(0, -1);
if (rating > 30) {
document.body.innerHTML = "This player has now been banned";
} else {
document.body.innerHTML = "Please submit further evidence to have this person banned";
}
};
};
</script>
To below the other script.
You would have to use Ajax for this. Submitting the form will always change the page to the action one(even if it's the same, it will reload).
I recommend using jQuery

How do I change the fixed values of days between two dates into variable and use event handler Javascript to show output?

As the title stated, I would like to make a variable out of "2011-11-2","2011-11-05" which are the date start and date end
<?php echo getWorkingDays("2011-11-2","2011-11-05",$holidays); ?>;
How do I change the fixed value of days between two dates into variable from business day calculation PHP function and using Javascript event handler to show an output?
When user selects date from the date picker from both textfield "DateFrom" and "DateTo" then user required to press the Check Day(s) button to calculate the number of the two date between that have been specified.
Below are the PHP function to get a business day between two dates:
<?php
function getWorkingDays($startDate,$endDate,$holidays){
$days = (strtotime($endDate) - strtotime($startDate)) / 86400 + 1;
$no_full_weeks = floor($days / 7);
$no_remaining_days = fmod($days, 7);
$the_first_day_of_week = date("N", strtotime($startDate));
$the_last_day_of_week = date("N", strtotime($endDate));
if ($the_first_day_of_week <= $the_last_day_of_week) {
if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--;
if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--;
}
else {
if ($the_first_day_of_week == 7) {
$no_remaining_days--;
if ($the_last_day_of_week == 6) {
$no_remaining_days--;
}
}
else {
$no_remaining_days -= 2;
}
}
$workingDays = $no_full_weeks * 5;
if ($no_remaining_days > 0 )
{
$workingDays += $no_remaining_days;
}
foreach($holidays as $holiday){
$time_stamp=strtotime($holiday);
if (strtotime($startDate) <= $time_stamp && $time_stamp <= strtotime($endDate) && date("N",$time_stamp) != 6 && date("N",$time_stamp) != 7)
$workingDays--;
}
return $workingDays;
}
$holidays=array("");
?>
When i echo the fixed value of date it works prefectly fine
<?php echo getWorkingDays("2011-11-2","2011-11-05",$holidays); ?>;
Followed by javascript and form:
<link rel="stylesheet" type="text/css" href="tcal.css" />
<script type="text/javascript" src="tcal.js">
</script>
<form name=fname method='post'>
<tr valign="baseline">
<td nowrap="nowrap" align="right"> </td>
<td nowrap="nowrap" align="right"><div align="left">Date From:</div></td>
<td><div>
<input id="dateFrom" type="text" name="DateFrom" class="tcal" value='' autocomplete="off" />
</div></td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right"> </td>
<td nowrap="nowrap" align="right"><div align="left">Date To:</div></td>
<td><div>
<input id="dateTo" type="text" name="DateTo" class="tcal" value="" autocomplete="off"/>
</div></td>
</tr>
<p>
<input id="leavetakens" name="leavetakens" type="text" value="" readonly="readonly">
<input type="button" value="Check Day(s)" name="btnCalculate" onClick="abc()"></p>
</form>
<script type="text/javascript">
function abc()
{
var jsvar = <?php echo getWorkingDays("2011-11-2","2011-11-05",$holidays); ?>;
var dateFrom = document.getElementById("dateFrom").value;
var dateTo = document.getElementById("dateTo").value;
document.fname.leavetakens.value=jsvar
}
</script>
At this point I only can show the value from the fixed two date specified but how to make it as variable?
<?php $workday=getWorkingDays("2011-11-2","2011-11-05",$holidays); ?>;
It seems that you want to call a server/PHP function (i.e. getWorkingDays()) from the client/JavaScript side. You can achieve this via AJAX in abc().
The full AJAX may look like this:
var dateFrom = document.getElementById("dateFrom").value;
var dateTo = document.getElementById("dateTo").value;
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.fname.leavetakens.value = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "getWorkingDays.php?dateFrom="+dateFrom+"&dateTo="+dateTo, true);
xmlhttp.send();
where getWorkingDays.php takes two parameters, namely dateFrom and dateTo, in the querystring and call the PHP getWorkingDays() function, and then returns/writes the value.
If you use jQuery (or some other JavaScript library), it will significantly save your time and code:
var dateFrom = $("#dateFrom").val();
var dateTo = $("#dateTo").val();
$.get('getWorkingDays.php', {dateFrom: dateFrom, dateTo: dateTo}, function(data) {
$('#leavetakens').val(data);
});
The getWorkingDays.php would look something like this:
<?php echo getWorkingDays($_GET["dateFrom"],$_GET["dateTo"],$holidays); ?>;

Categories