Can't get this to work and could use an extra pair of eyes to find what I'm doing wrong or what might be missing. I created a form using the RSForm Pro component for Joomla 3.3.1. The purpose of the form is to allow a user to file warranty claims on our products. If a user needs to file a repeat claim on a product then an input field is displayed with a button to retrieve data from the database and auto fill the owner's info for the user. For every claim submitted an "id" is generated. This "id" is the number the user should be entering to retrieve data if needing to submit a repeat claim. I have an ajax function that runs onclick and looks for a php file that connects to the database and retrieves the requested info.
Here is the ajax...
var ajax = getHTTPObject();
function getHTTPObject()
{
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} else {
//alert("Your browser does not support XMLHTTP!");
}
return xmlhttp;
}
function updateOwnerInfo()
{
if (ajax)
{
var idValue = document.getElementById("owner_id").value;
if(idValue)
{
var url = "/templates/uma-solar/html/com_rsform/getClaimInfo.php";
var param = "?id=" + escape(idValue);
ajax.open("GET", url + param, true);
ajax.onreadystatechange = handleAjax;
ajax.send(null);
}
}
}
function handleAjax()
{
if (ajax.readyState == 4)
{
ownerarr = ajax.responseText.split(",");
var owner_name = document.getElementById('owner_name');
var owner_address = document.getElementById('owner_address');
var owner_city = document.getElementById('owner_city');
var owner_state = document.getElementById('owner_state');
var owner_country = document.getElementById('owner_country');
var owner_county = document.getElementById('owner_county');
var owner_zip = document.getElementById('owner_zip');
var owner_phone = document.getElementById('owner_phone');
var owner_email = document.getElementById('owner_email');
owner_name.value = ownerarr[0];
owner_address.value = ownerarr[1];
owner_city.value = ownerarr[2];
owner_state.value = ownerarr[3];
owner_country.value = ownerarr[4];
owner_county.value = ownerarr[5];
owner_zip.value = ownerarr[6];
owner_phone.value = ownerarr[7];
owner_email.value = ownerarr[8];
}
}
Here is the php...
define( '_JEXEC', 1 );
define('JPATH_BASE', '/var/www/joomla.umasolar.com/');
/* Required Files */
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
/* To use Joomla's Database Class */
require_once ( JPATH_BASE .'/libraries/joomla/factory.php' );
/* Create the Application */
$app = JFactory::getApplication('site');
$app->initialise();
//-----process DB query-------
$db = JFactory::getDBO();
$sql='SELECT
owner_name,
owner_address,
owner_city,
owner_state,
owner_county,
owner_country,
owner_zip,
owner_phone,
owner_email
FROM #__rsform_warranty_claim WHERE _id=mysql_real_escape_string($_GET[
"owner_id"])';
$db->setQuery($sql);
//----------------------------
$row = $db->loadObjectList();
echo $row['owner_name'] . ", " . $row['owner_address'] . ", " . $row['owner_city'] . ", " . $row['owner_state'] . ", " . $row['owner_country'] . ", " . $row['owner_county'] . ", " . $row['owner_zip'] . ", " . $row['owner_phone'] . ", " . $row['owner_email'];
The form is not public so here are a couple screenshots that might be useful...
And here is the text that is filling in the input fields which just appears to be a 404, but in the title it shows 1064 - Error: 1064...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb" lang="en-gb" dir="ltr">
<head>
<title>1064 - Error: 1064</title>
<link rel="stylesheet" type="text/css" href="/templates/uma-solar/html/com_rsform/templates/uma-solar/css/style.css" />
<link rel="stylesheet" type="text/css" href="/templates/uma-solar/html/com_rsform/templates/uma-solar/bootstrap/css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="/templates/uma-solar/html/com_rsform/templates/uma-solar/bootstrap/css/bootstrap-responsive.css" />
<script type="text/javascript" src="/templates/uma-solar/html/com_rsform/templates/uma-solar/bootstrap/js/bootstrap.js"></script>
</head>
<body class="error">
<center>
<div class="errorbox">
<div class="block">
<h1>404</h1>
<h3>Page not found</h3>
</div>
<p>Sorry! The page you are looking for cannot be found. Please use the provided search box to find what you are looking for
There are no errors generating in the error log with this code. Had some issues figuring out the correct path to the required Joomla files in the PHP code, but it appears I fixed that issue. Any and all help would be greatly appreciated!
Finally got it working after following Joomla's instructions on selecting data using JDatabase. I'm sure this can work using standard SQL statements, but Joomla can be picky sometimes and it's just easier to follow their rules. The AJAX was fine, but here's what I changed the PHP to...
define( '_JEXEC', 1 );
define('JPATH_BASE', '../../../../');
//Required Joomla Files
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
//Connect to Joomla's Database Class
require_once ( JPATH_BASE .'/libraries/joomla/factory.php' );
//Create the Application
$app = JFactory::getApplication('site');
$app->initialise();
$input = $app->input;
$id = $input->getInt('id');
//Connect to db
$db = JFactory::getDBO();
//Create new query object
$query = $db->getQuery(true);
$query->select($db->quoteName(array('owner_name', 'owner_address', 'owner_city', 'owner_state', 'owner_county', 'owner_country', 'owner_zip', 'owner_phone', 'owner_email')));
$query->from($db->quoteName('#__rsform_warranty_claim'));
$query->where($db->quoteName('_id') . '=' . $db->quote($id));
//Reset the query using our newly populated query object
$db->setQuery($query);
//Get a single record from the DB table
$row = $db->loadAssoc();
echo $row['owner_name'] . ", " . $row['owner_address'] . ", " . $row['owner_city'] . ", " . $row['owner_state'] . ", " . $row['owner_country'] . ", " . $row['owner_county'] . ", " . $row['owner_zip'] . ", " . $row['owner_phone'] . ", " . $row['owner_email'];
Related
I am trying to get certain data from my database on my (1) HTML page and display it on the (2) HTML page.
My codes for (1) html file:
<html>
<head>
<script src="example.js"></script>
</head>
<body>
.
.
.
<button item="' + count + '" onclick="getData(this)">Example</button>
.
.
.
</body>
</html>
And the JS for it:
.
.
.
var currentIndex = 0;
//This function is to display the details of an individual item
function getData(element) {
var request = new XMLHttpRequest();
request.open("GET", "/theroute", true);
request.setRequestHeader("Content-Type", "application/json");
request.onload = function () {
var example = JSON.parse(request.responseText);
var item = element.getAttribute("item");
currentIndex = item;
document.getElementById("data1").textContent = example[item].name;
document.getElementById("data2").src = example[item].age;
}
request.send();
}
.
.
.
I want to get these data in my (2) HTML page (for example):
<html>
<head>
<script src="example.js"></script>
</head>
<body>
<h4 id="data1"></h4>
<h4 id="data2"></h4>
</body>
</html>
I saw this Get data from one html file and display it using another html file, but I'm not sure how to use this for my case here.
Sorry, I am new to this, so giving a detailed explanation for your solution would be very helpful. I am using vanilla JS only so please no jQuery. Any help would be appreciated
I hope this might prove of use to you. The button(s) have had the custom item attribute replaced with the dataset equivalent to ensure the html is valid. Normally I'd suggest also using external event handlers rather than adding onclick=getdata() to the elements inline but for brevity here they remain.The function, when invoked by clicking a button, will construct the relevant querystring to send to the endpoint ( for you it would be /theroute?id=X&name=Y&age=Z etc ) which queries the database and sends the response back. The response is used to generate the menu of hyperlinks which take the user to page 2 when clicked. I think this is what you were trying to explain. You could copy the entire code and create a new page to see in action.
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' && !empty( $_GET['item'] ) ){
ob_clean();
/*
emulate "/theroute" and send some data back to the ajax callback.
This data would really be fetched from the database but below is
simply randomly generated data for display/test purposes.
*/
$payload=[];
$item=$_GET['item'];
for( $i=0; $i < 10; $i++ ){
$payload[]=[
'id' => $i,
'name' => 'Geronimo '.uniqid().' '.$item,
'age' => mt_rand(16,80)
];
}
exit( json_encode( $payload ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script>
function getData( e ) {
var xhr = new XMLHttpRequest();
var ul=document.getElementById('menu');
/* The above PHP code is to emulate the real endpoint /theroute */
xhr.open( "GET", location.href +'?task=fetch&item='+e.target.dataset.item, true );
xhr.setRequestHeader( "Content-Type", "application/json" );
xhr.onload = function() {
var json = JSON.parse( xhr.response );
json.forEach(obj=>{
var id=obj.id;
var name=obj.name;
var age=obj.age;
var li=document.createElement('li');
li.appendChild( createhyperlink(id,name,age) );
ul.appendChild( li );
});
}
xhr.send();
}
function createhyperlink(id,name,age){
var a=document.createElement('a');
a.href='page2.html?id='+id+'&name='+name+'&age='+age;
a.innerHTML='View '+name;
return a;
}
</script>
</head>
<body>
<ul id='menu'></ul>
<?php
for( $i=1; $i <=10; $i++ ){
echo "<button data-item='{$i}' onclick='getData(event)'>Example #{$i}</button>";
}
?>
</body>
</html>
I am developing a survey form for recreational activities. The user is required to input a location which is then searched in a MYSQL database to ensure that the name entered matches the standard names for locations. The results are to be displayed in a select form to allow the user to choose the specific location.
The query appears to be working correctly. I have verified the return string via an alert window. However, the form appears for a brief second then disappears. I have tried writing the innerHTML string to both a tag and directly to the form. Other posts on this topic that I have found indicated that a form tag is not closed properly. This does not appear to be my problem.
When I run the php script from a test page using hard coded locations, and no other elements on the page, it works just fine.
My js script:
<script> function getLoc(){
var dataRequest;
try {
// Opera 8.0+, Firefox, Safari
dataRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
dataRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
dataRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser needs to be updated to run this
application!");
return false;
}
}
}
dataRequest.onreadystatechange = function() {
if(dataRequest.readyState == 4) {
if (dataRequest.status==200 ||
window.location.href.indexOf("http")==-1){
document.getElementById("locDropDown").innerHTML =
dataRequest.responseText;
}
else{
alert("An error has occured making the request");
}
}
}
var queryString = "";
queryString =
encodeURIComponent(document.getElementById('locStr').value.toUpperCase());
dataRequest.open("POST", "retrieveLoc.php", true);
dataRequest.setRequestHeader("Content-type", "application/x-www-form-
urlencoded");
dataRequest.send("searchValue=" + queryString);
}
</script>
<div>
<form id="floc">
<strong>Where Did You Go:</strong> <input type="text" id = "locStr"
placeholder="location">
<input type="submit" value="Search" onclick="getLoc()">
</form>
</div>
<!-- <div id="dataDiv"> -->
<form id="locDropDown">
</form>
<!-- </div> -->
The relevant portion of my php script:
<?php
$queryStr = htmlspecialchars($_POST['searchValue']);
$queryStr .= "%";
// Check sql
$locSql = "SELECT location FROM `location_lkup` \n"
. "WHERE location LIKE '" .$queryStr. "' \n"
. "ORDER BY `location_lkup`.`location` ASC";
$locRslt = $conn->query($locSql);
//Build Result String
/* $display_string = "<form id = 'locDropDown'>"; */
$display_string .= "<select name = 'locChoices'>";
// If returned records >0 insert a new row in the select form for each loc
returned
if ($locRslt -> num_rows > 0) {
$rowcounter = 1;
while($row = $locRslt -> fetch_array(MYSQLI_ASSOC)) {
$display_string .= "<option value = " . $rowcounter . ">" . $row['location']
. "</option>";
$rowcounter++;
}
}
else {
$display_string .= "<option value = '1'> NO DATA </option>" ;
}
$display_string .= "</select>";
$display_string .= "<input type = 'button' value= 'Select' onclick=
'getSelectedloc()'>";
/* $display_string .= "</form>"; */
echo $display_string;
?>
Any suggestions would be greatly appreciated. Thanks.
I have a database with 6 Nations rugby results and teams, and I want to get the data from the results database using AJAX and display on a php page. This is a page i'm using called getData.php
<?php
$year=$_GET['year'];
$connection = mysqli_connect("localhost","root","");
mysqli_select_db($connection,"6nationsDB");
// for results
$result = mysqli_query($connection,"SELECT * FROM results WHERE
year(`date`)='$year' ORDER BY rnd, date");
$rs = array();
$i=0;
while($rs[] = mysqli_fetch_assoc($result)) {
// do nothing ;-)
}
// for team details
$result2 = mysqli_query($connection,"SELECT * FROM teams ORDER BY id");
$rs2 = array();
$i=0;
while($rs2[] = mysqli_fetch_assoc($result2))
{
}
mysqli_close($connection);
unset($rs[count($rs)-1]); //removes a null value
// print("{ \"results\":" . json_encode($rs) . "}");
print("{ \"results\":" . json_encode($rs) . " , \"teams\":" .
json_encode($rs2) . "}");
?>
Trying to access the select statements in getData.php to get data from the database
Browse.php
<link rel="stylesheet" href="design.css" type="text/css">
<!DOCTYPE html>
<html>
<div id="getData"></div>
<script type ="text/javascript">
dis();
function dis()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "getData.php",false);
xmlhttp.send(null);
document.getElementById("getData").innerHTML=xmlhttp.responseText;
}
</script>
I am using a joomla module i would like to modify to auto load the default list of results.
currently, when the page loads no result is shown. If all search fields are empty and the user clicks the search button, the page will load all data. If information in placed in the search fields, the results will be broken down to match what was typed in.
I want the page to auto load all data when the page loads without the user clicking search.
How do i achieve this?
I believe the module uses ajax and i believe the info that affects this is below:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: text/html');
define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
ini_set("display_errors", "On");
error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE & ~E_WARNING);
$my_path = dirname(__FILE__);
$my_path = explode(DS.'modules',$my_path);
$my_path = $my_path[0];
if (file_exists($my_path . '/defines.php')) {
include_once $my_path . '/defines.php';
}
if (!defined('_JDEFINES')) {
define('JPATH_BASE', $my_path);
require_once JPATH_BASE.'/includes/defines.php';
}
require_once JPATH_BASE.'/includes/framework.php';
$app = JFactory::getApplication('site');
$app->initialise();
///////////////////////////////////////////////////////////////////////////////////////////////
$name = $_GET['name'];
$value = mb_strtolower($_GET['value']);
$next = mb_strtolower($_GET['next']);
$db = JFactory::getDBO();
$query = "SELECT * FROM #__k2_extra_fields WHERE published = 1";
$db->setQuery($query);
$results = $db->loadObjectList();
$extra_val = '';
$extra_id = 0;
foreach($results as $result) {
if(trim(mb_strtolower($result->name)) == trim($value) . " " . trim($next) || trim(mb_strtolower($result->name)) == trim($next) . " " . trim($value)) {
$extra_val = $result->value;
$extra_id = $result->id;
break;
}
}
require_once(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'lib'.DS.'JSON.php');
$json = new Services_JSON;
$extra_val = $json->decode($extra_val);
if($extra_val != '') {
foreach($extra_val as $val) {
echo "<option>" . $val->name . "</option>";
}
echo "<option>".$extra_id."</option>";
}
?>
Please help!
to auto load search result we must need to store search query in session variable,
http://docs.joomla.org/How_to_use_user_state_variables
http://docs.joomla.org/API15:JApplication/getUserStateFromRequest
This are the links which will describe very well about how to manage request variable in session, so there is no variable in request it will get value from the session.
try to use something like this
<html>
<head>
<script>
function myFunction()
{
alert("Page is loaded");
}
</script>
</head>
<body onload="myFunction()">
<h1>Hello World!</h1>
</body>
</html>
then you can easily change myFunction to trigger your search on click event
<script>
function myFunction()
{
document.getElementById('YOUR-BUTTON-ID').onclick();
}
</script>
I can't seem to work this one out. Been a few days and still no progress after re-writing it more times than I can count on my hands.
Here is the Javascript (On same page as html)
Summary: User types text into the input box. That gets sent off to be processed, which then gets sent back and displayed on the screen in the box ID'd as DisplayText on the html page.
<script type="text/javascript">
function SendText() {
if (document.getElementById("Text").innerHTML == "") {
return;
} else
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("DisplayText").innerHTML = xmlhttp.responseText;
}
}
Text = document.getElementById("Text").value;
xmlhttp.open("GET", "php/Test.php?Chat=" + Text, true);
xmlhttp.send();
}
}
</script>
Here is the HTML (Same page as the script)
<div>
<p>
<span id="DisplayText">
TEXT GOES HERE
</span>
</p>
</div>
<form action="" onsubmit="SendText();">
<input type="" name="" id="Text" />
<input type="submit" value="Send" name="Send" />
</form>
The PHP code is here
<?php
session_start();
include ("Connect.php");
$Connection = mysqli_connect("localhost", "root", "", "chatsystem");
$Create = "CREATE TABLE " . $_SESSION["Username"] . "Chat(Username VARCHAR(255), Chat VARCHAR(255))";
////////////////////////////////////////////////////////////////////////////////
$DatabaseExist = $Connection->query("SELECT 1 FROM " . $_SESSION["Username"] . "Chat");
if ($DatabaseExist !== false) {
echo "Database exists";
doSomething();
} else {
echo "Database does not exist";
mysqli_query($Connection, $Create);
doSomething();
}
////////////////////////////////////////////////////////////////////////////////
function doSomething() {
// Get the sent chat
$Input = $_REQUEST["Chat"];
// Insert into the database the new chat sent
mysqli_query($Connection, "INSERT INTO " . $_SESSION["Username"] . "chat (`Username`, `Chat`) VALUES ('$_SESSION[Username], '$Input')");
// Select everything from the database
$Result = $Connection->query("SELECT * FROM " . $_SESSION["Username"] . "Chat");
// Display everything from the database in an orderly fashion
// --
// For the length of the database
// Append to a variable the next table row
// --
while ($Row = $Result->fetch_array()) {
// Make Variable accessable
global $Input;
// Append username to the return value
$Input = $Input . $Row["Username"] . " : ";
// Append chat to the return value
$Input = $Input . $Row["Chat"] . "<br />";
}
}
// Will return the value
echo $Input;
?>
My connection to the Database is fine. I'm using it on other pages that work.
So lets assume that's not the problem. :P
Any help or insight from anyone who knows or can think of something that is wrong, I would be very grateful for.
I'm new to AJAX.
You do a wrong test with
if (document.getElementById("Text").innerHTML == "")
It should be the same way you use to get the text for sending in the AJAX
if (document.getElementById("Text").value == "")
So check its value property and not its innerHTML as input elements do not have html content..
Be careful though because your code is wide-open to SQL injection attacks.
1st : use input's value property instead innerHTML
eg. use
if (document.getElementById("Text").value == "")
instead of
if (document.getElementById("Text").innerHTML == "")
2nd : use return false; at the form's onsubmit event; to prevent current page to be refreshed as you are using ajax. Otherwise the page will get refreshed and it wont display the php page's output,
eg. use
onsubmit="SendText(); return false;"
instead of just
onsubmit="SendText();"
Try AJAX Long Polling technique for chat application. Here is example
http://portal.bluejack.binus.ac.id/tutorials/webchatapplicationusinglong-pollingtechnologywithphpandajax