Ajax GET content from php page - html

Hi I have a table which I am trying to update with a call to a MySQL database in a separate php page. This separate page loops through a result set and builds the table through a series of echos. In the main page I am trying to insert that echoed content into a div.
This is all kicked off by the user selecting an option from a drop down box.
This is the separate php page. (It works fine when i manually type in the GET parameters, it is the link between the two pages which doesn't seem to work)
tableGetter.php
<?PHP
$user_name = "rocketeermus_pr";
$password = "zuluhead2";
$database = "rocketeermus_pr";
$server = "pdb1.awardspace.com";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
echo "Bonjour";
if (isset($_GET['composer'])){
echo "Helloooo";
if ($db_found) {
echo "SELECT * FROM catalogue WHERE Composer = '".mysql_escape_string($_GET['composer'])."';";
$SQL = "SELECT * FROM catalogue WHERE Composer = '".mysql_escape_string($_GET['composer'])."';";
$result = mysql_query($SQL);
setlocale(LC_MONETARY,"en_GB");
echo "<table class=\"sortable\" id=\"moder\" width=\"800\">";
echo "<th>TITLE</th><th>COMPOSER</th><th>VOICING</th><th>PRICE</th><th></th></tr>";
while ( $db_field = mysql_fetch_assoc($result) ) {
echo "Hi.";
echo "<tr><td>{$db_field['Title']}</td><td>{$db_field['Composer']}</td><td>{$db_field['Voicing']}</td><td>";
echo money_format("%n", $db_field['Price']);
echo "</td><td> <div class=\"product\"> <input value=\"{$db_field['Title']}\" class=\"product-title\" type=\"hidden\"> <input value=\"0.5\" class=\"product-weight\" type=\"hidden\"> <input value=\"{$db_field['NoVox']}\" class=\"googlecart-quantity\" type=\"hidden\"> <input value=\"{$db_field['Price']}\" class=\"product-price\" type=\"hidden\"> <div title=\"Add to cart\" role=\"button\" tabindex=\"0\" class=\"googlecart-add-button\"> </div> </div> </td></tr>";
}
echo "</table>";
mysql_close($db_handle);
} else {
print "Database NOT Found ";
mysql_close($db_handle);
}
}
?>
And here is the important stuff from the main page:
Javascript:
function getdata()
{
var req = getXMLHTTP();
if (req)
{
//function to be called when state is changed
var queryString1 = "";
req.onreadystatechange = function()
{
//when state is completed i.e 4
if (req.readyState == 4)
{
var ajaxSearchResults1 = document.getElementById("table");
ajaxSearchResults1.innerHTML = req.responseText;
// only if http status is "OK"
if (req.status == 200)
{
var new1 = document.getElementById('composer').value;
queryString1 = "?composer=" + encodeURIComponent(new1);
console.log (queryString1);
}
else
{
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", "tableGetter.php" + queryString1, true);
req.send();
}
}
function getXMLHTTP() {
var xmlhttp;
if(window.XMLHttpRequest){ //For Firefox, Mozilla, Opera, and Safari
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){ //For ie
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}
html:
<div id="menus">
<table>
<tr>
<td><form action=""">
<select name="composer" id ="composer" onchange="getdata();">
<?php
$user_name = "***";
$password = "****";
$database = "****";
$server = "****.com";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT DISTINCT Composer FROM catalogue ORDER BY Composer";
$result = mysql_query($SQL);
setlocale(LC_MONETARY,"en_GB");
while ( $db_field = mysql_fetch_assoc($result) ) {
?>
<option id="composer" onchange="getdata();" value="<?php echo $db_field['Composer'];?>">
<?php
echo $db_field['Composer'];
?>
</option>
<?php
}
}
?>
</select>
</form></td>
</tr>
</table>
</div>
<div id="table">
<?php include("tableGetter.php"); ?>
</div>
The html on the main page works fine, the drop down menu fills up nicely with all the distinct composer names in the database. When an option in the menu is selected the only thing echoed in the "table" div is "Bonjour". It's not getting further than if (isset($_GET['composer'])) in the tableGetter.php page. I'm printing out the queryString1 variable (The get parameters) which is requested in the getData() function and it reports: ?composer=Animuccia%2C%20Paulo which works perfectly when loading the page manually. It just won't work dynamically!
Anybody know what's going on here?

You aren't setting queryString1 before sending the AJAX request. Try this rewrite of getdata().
function getdata()
{
var req = getXMLHTTP();
if (req)
{
//function to be called when state is changed
req.onreadystatechange = function()
{
//when state is completed i.e 4
if (req.readyState == 4)
{
// only if http status is "OK"
if (req.status == 200)
{
var ajaxSearchResults1 = document.getElementById("table");
ajaxSearchResults1.innerHTML = req.responseText;
}
else
{
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
var new1 = document.getElementById('composer').value;
var queryString1 = "?composer=" + encodeURIComponent(new1);
req.open("GET", "tableGetter.php" + queryString1, true);
req.send();
}
}

Related

Datalist attribute is not working in google chrome

Datalist attribute is not working in Google chrome, it is working fine in Firefox
Please have a look here http://prntscr.com/arny81
Thanks for your help in advance.
HTML
<td><input onkeyup="showCustomers(this.value)" placeholder="Enter Customer Name" list="selectCust" name="Cno" />
<datalist id="selectCust">
</datalist>
</td>
Javascript
function showCustomers(str) {
if (str.length == 0) {
document.getElementById("selectCust").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("selectCust").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "getCustomers.php?q=" + str, true);
xmlhttp.send();
}
}
getCustomers.php File
<?php include('conn.php'); ?>
<?php // get the q parameter from URL
$q = $_REQUEST["q"];
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
$sql2 = 'SELECT Customer_Name as Cname,No from customers order by Customer_Name';
$result2 = mysqli_query($connection, $sql2) or die(mysqli_error($connection));
if (mysqli_num_rows($result2) > 0) {
?><option value=""></option><?php
// output data of each row
while($row2 = mysqli_fetch_assoc($result2)) {
if (stristr($q, substr($row2["Cname"], 0, $len))) { ?>
<option value="<?php
echo $row2['No']; ?>"><?php echo $row2["Cname"]; ?></option>
<?php } } ?>
<?php } } ?>
I have not used CSS at all.
Target the ID in your CSS instead, that should work fine.
HTML:
<datalist id="dl">
Your content goes here
</datalist>
CSS:
#dl {
display: block;
}
This works fine in Chrome or any other browser.

Ajax - Inserting values from textarea into database

Hello all on my quest to learn more about ajax I tried making a textarea, in this a text is submitted and then sended to the database, I also made a button to display everything from the database and this works. However when submitted clicking the display all button it just gives this value [object HTMLTextAreaElement] Here is my code:
Select Code/Display
ToDo: <textarea width='200px' height='300px' id='todo'></textarea>
<p id='dbinfo'>Info goes here</p>
<button id='btn'> Send </button>
<button id='request'> Request </button>
<script>
document.getElementById('btn').onclick = function()
{
var dbinfo = document.getElementById('todo').value;
alert(todo); //Here it gives a object htmlcollection ?
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
alert(xmlhttp.readyState + " | " + xmlhttp.status);
var text = xmlhttp.responseText;
alert(text);
document.getElementById('dbinfo').innerHTML = text;
}
xmlhttp.open("POST", "linktodata", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("todo=" +todo);
}
document.getElementById("request").onclick = function()
{
alert("event works");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var result = xmlhttp.responseText;
alert(result);
document.getElementById("dbinfo").innerHTML = result;
}
}
xmlhttp.open("POST", "linktorequest", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
</script>
Data Code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$databasename = "blok-1-am1a";
try
{
if (isset($_POST['todo']))
{
$connection = new PDO("mysql:host=".$servername.";dbname=".$databasename, $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $connection->prepare("INSERT INTO `database` (`id`, `item`) VALUES (NULL, :item)");
$statement->bindParam(':item', $_POST['todo']);
$statement->execute();
}
}
catch(PDOException $e)
{
echo "Error occured : ".$e->getMessage();
}
echo "Success";
?>
Request code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$databasename = "blok-1-am1a";
try
{
$connection = new PDO("mysql:host=".$servername.";dbname=".$databasename, $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $connection->prepare("SELECT * FROM `database` ");
$statement->bindParam(':id', $id);
$statement->execute();
$result = $statement->setFetchMode(PDO::FETCH_ASSOC);
$data = "";
foreach($statement->fetchAll() as $key => $value)
{
$data .= $value['id']." | ".$value['item']."<br>";
}
}
catch(PDOException $e)
{
echo "Error occured: ".$e->getMessage();
}
echo $data;
?>
So yeah whatever I do the request code works but when submitting I always get [object HTMLTextAreaElement]
Silly me, this is a very simple fix, I made the mistake to use the same var as my <p> tag so the fix is litteraly changing that into todo and everything works.
ToDo: <textarea width='200px' height='300px' id='todo'></textarea>
<p id='dbinfo'>Info goes here</p>
<button id='btn'> Send </button>
<button id='request'> Request </button>
<script>
document.getElementById('btn').onclick = function()
{
var todo = document.getElementById('todo').value; //This needed to be changed into todo
}

PHP MySQL Data To AngularJS

I am using this code to pull data from a MySQL.
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
var icon = data[1];
var english = data[2];
var british = data[3];
$('#output').html("<b>id: </b>"+id+"<b> icon: </b>"+icon+"<b> english: </b>"+english+"<b> british: </b>"+british); //Set output element html
}
And it outputs this correctly but my questions is how would put this data into the below.
$scope.items = [
{
english: '<First Row english>',
british: '<First Row british>',
image: '<First Row icon>'
},
{
english: '<Second Row english>',
british: '<Second Row british>',
image: '<Second Row icon>'
}
//So on and so forth for all the records in the DB.
]
This is from api.php not sure if this needs to be returned a certain way?
<?php
require_once 'db.php'; // The mysql database connection script
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$query=mysql_query("SELECT * FROM $tableName") or die(mysql_error());
while($obj = mysql_fetch_object($query)) {
$arr[] = $obj;
}
echo $json_response = json_encode($arr);
?>
<?php
require_once 'db.php'; // The mysql database connection script
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$query=mysql_query("SELECT * FROM $tableName") or die(mysql_error());
$arr[];
while($obj = mysql_fetch_object($query)) {
array_push($arr, $obj);
}
echo $json_response = json_encode($arr);
?>
JS
$http.get('api.php').success(function(data) {
$scope.items = data;
});

Show Chrome extension version on options page?

I've got my manifest file with my version number and an options page. Is there a way to display the installed version and latest available version on the options page without needing to do it manually?
You can get the current version of your extension using chrome.runtime.getManifest().version.
In order to get the "latest version" of your extension, you need to download updates.xml, and extract the version number:
var extensionID = chrome.i18n.getMessage('##extension_id');
var currentVersion = chrome.runtime.getManifest().version;
var url = 'https://clients2.google.com/service/update2/crx?x=id%3D' + extensionID + '%26v%3D' + currentVersion;
var x = new XMLHttpRequest();
x.open('GET', url);
x.onload = function() {
var doc = new DOMParser().parseFromString(x.responseText, 'text/xml');
// Get and show version info. Exercise for the reader.
};
x.send();
If you want to customize your request with PHP, avoiding to update the extension every time Google changes the API, I suggest the following
update_info.php (from your site):
<?php
$last_ver;
$googleupdate = 'http://clients2.google.com/service/update2/crx?response=updatecheck&x=id%3D__id__%26uc';
$ver = $_POST['ver'];
$id = $_POST['id'];
//filter/control for post request very fast for this example
if(isset($id) && isset($ver)){
if(strlen($id)>0){
$urlupdate = str_replace('__id__', $id, $googleupdate);
$last_ver = _GetLastVersion($urlupdate);
if($last_ver>0 && $last_ver>$ver){
echo 'New version available, v'.$last_ver;
}else{
echo 'Your version is update';
}
}else{
echo 'Insert id for response';
}
}else{
echo 'Insert data for response';
}
//if your server do not connect with file_get_contents() use this function
function getContent ($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
$output = curl_exec($ch);
$info = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($output === false || $info != 200) {
$output = null;
}
return $output;
}
//this function return 0 if error or not content load
function _GetLastVersion($url){
try {
$last=0;
//if you have proble you can use getContent($url)
$xmlcontent = file_get_contents($url);
if($xmlcontent){
$doc = new DOMDocument();
$doc->loadXML($xmlcontent);
$items = $doc->getElementsByTagName('updatecheck');
foreach ($items as $item) {
if($item->getAttribute('version')>0){
return $item->getAttribute('version');
}
}
return $last;
}else{
return 0;
}
} catch (Exception $e) {
return 0;
}
}
?>
in your extension send request to your webpage, now you are in control of your script, you can decide which answer back every time

Google MAPs api v2 AJAX not working

My code is not working what is going wrong I can't understand...my code is:
/* =================Call.php========================*/
<?php
/* Include settings My mysql database */
include ("config.php");
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>GG-Tracker (GSM and GPS location combined)</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=myAPIKey&sensor=true" type="text/javascript"></script>
<?php
echo "
<script type=\"text/javascript\">
var map;
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById(\"map\"));
downloadUrl(\"phpsqlajax_genxml.php\", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName(\"marker
\");
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i].getAttribute(\"lat\"));
var lon = parseFloat(markers[i].getAttribute(\"lon\"));
var html = \"<b>\" + \"</b> <br/>\" ;
var marker = new GMarker(new GLatLng(lat, lon));
map.addOverlay(marker);
}
}
}
}
function downloadUrl(url, callback) {
if (window.XMLHttpRequest)
{
request=new XMLHttpRequest();
}
else
{
request=new ActiveXObject(\"Microsoft.XMLHTTP\");
}
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing();
callback(request, request.status);
}
};
request.open(\"GET\", url, true);
request.send();
}
function doNothing() {}
</script>
";
?>
</head>
<body onload="load()" onunload="GUnload()">
<center>
<div id="map" style="width: 800px; height: 600px"></div>
</body>
</html>
/* End of =============Call.php===============*/
My phpsqlajax_genxml.php for genrating XML is:
/* Start of ===========phpsqlajax_genxml.php=============== */
<?php
require("phpsqlajax_dbinfo.php");
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
$connection=mysql_connect ($dbhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("tid",$row['TID']);
$newnode->setAttribute("devid",$row['DevID']);
$newnode->setAttribute("ldate",$row['LDate']);
$newnode->setAttribute("ltime",$row['LTime']);
$newnode->setAttribute("lat", $row['Lat']);
$newnode->setAttribute("lon", $row['Lon']);
$newnode->setAttribute("speed", $row['Speed']);
}
echo $dom->saveXML();
?>
/*=========End of=============phpsqlajax_genxml.php*/
My Database information file is: phpsqlajax_dbinfo.php
/*=========Start of=== phpsqlajax_dbinfo.php============*/
<?php
$dbhost = "localhost";
$username="root";
$password="";
$database="mygps";
$gmaps = "AIzaSyCRf9drwSYjBSeKpvSkEHFKqX_yBpq-Tkk";
?>
/*===========End of phpsqlajax_dbinfo.php==============*/
the above three files cant work.
If I run only phpsqlajax_genxml.php file to generate XML it is working
I can generate XML but it cannot downloaded through JAVA - I think AJAX call is not
working....
What to do auto reload marker from MySQL on some time interval without
reloading whole page like Live Tracking.....
Please Help Me My above code is not working
Thanks for Reading
Pradip
The V2 API is deprecated and you should migrate to V3 of the API.
https://developers.google.com/maps/documentation/javascript/
Is there any reason for using php-echo to output HTML-source?
However, if the code above is really what you actually use, you have a problem here:
var markers = xml.documentElement.getElementsByTagName(\"marker
\");
the line-break will break your script, remove it.