Adding a page with ajax in wordpress - javascript

I'm stuck with my codes for 2 weeks already. I want to have a page with 2 dropdowns. The first DD will show all 'states' from my database and the second DD should be based on the 1st DD's value. I think my codes are OK but the problem is the integration with wordpress itself. Is there any codes/functions/etc needed for a page to be read as ajax?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>None</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function parseResponse(adminResponse,nList){
var nText = adminResponse.getElementsByTagName('optionText');
var nVal = adminResponse.getElementsByTagName('optionVal');
nList.options.length = 1;
for (i=0; i<nText.length; i++)
{
var nOption = document.createElement('option');
nOption.appendChild(document.createTextNode(nText[i].firstChild.data));
nOption.value = nVal[i].firstChild.data;
nList.appendChild(nOption);
}
}
function update(nVal,nList,getFile){
var adminRequest = window.XMLHttpRequest ? new XMLHttpRequest()
: window.ActiveXObject
? new ActiveXObject("Microsoft.XMLHTTP")
: null;
adminRequest.onreadystatechange = function()
{
if (adminRequest.readyState == 4)
{
if (adminRequest.status == 200)
{
var adminResponse = adminRequest.responseXML;
parseResponse(adminResponse,nList);
}
else {
alert('Error ' + getFile + ' --- ' + adminRequest.statusText);
}
}
}
var infoStr = "?choice="+nVal;
adminRequest.open("GET", getFile + infoStr, true);
adminRequest.send(null);
}
function init(){
var nForm = document.forms[0];
nForm['state'].onchange = function()
{
if (this.value != "")
{
update(this.value,nForm['city'],'<?php echo get_template_directory_uri(); ?>/updateGroup.php');
}
}
}
navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);
</script>
<style type="text/css">
body {background-color: #eae3c6; margin-top: 60px;}
form {width: 430px; margin: auto;}
fieldset {width: 410px; background-color: #f0fff0; border: 1px solid #87ceeb;}
legend {font-family: times; font-size: 14pt; color: #00008b; background-color: #87ceeb;
padding-left: 3px; padding-right: 3px ; margin-bottom:5px;}
select {font-family: tahoma; font-size: 10pt; width: 160px; margin-left: 35px; margin-bottom: 10px;}
</style>
</head><?php /* Template Name: Practice */
?>
<body>
<?php
global $wpdb;
$query = "SELECT * FROM zipcode GROUP BY FULLSTATE ASC";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$dd .= "<option value='".$row['STATE']."'>".$row['FULLSTATE']."</option>";
}
?>
<form action="">
<fieldset>
<legend>Form</legend>
<select name="state">
<option value="">Select State</option>
<?php echo $dd; ?>
</select>
<select name="city" onchange="alert(this.value)">
<option value=""> Make a selection </option>
</select>
</fieldset>
</form>
</body>
</html>
First, I pasted those codes in notepad++ and saved it as practice.php. Uploaded it to my wordpress theme directory. Typing http://www.site.com/practice.php shows 'page not found' so i went to wordpress dashboard and created a new page -> assigned the template named 'practice'. typed http://www.site.com/practice.php again and it works.
<?php
$choice = $_GET['choice'];
$xml = "<?xml version='1.0' ?><options>";
global $wpdb;
$query = "SELECT * FROM zipcode WHERE STATE = '$choice'";
$result = #mysql_query($query);
$num = #mysql_num_rows($result);
if ($result && $num > 0)
{
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$xml .= "<optionText>" . $row['CITY'] . "</optionText><optionVal>" . $row['CITY'] . "</optionVal>";
}
}
$xml .= "</options>";
#mysql_free_result($result);
#mysql_close();
header("Content-Type: text/xml");
echo $xml;
?>
Ok so next i created a page with the codes above and named it updateGroup.php. uploaded it on wordpress theme directory.
Tested my codes and...I can't get it to work!! :(
Please i need help. should i add get_header and get_footer for my reference page? or do i need to configure something in wordpress to recognize my ajax?

Related

Why does reload specific section not work?

I've tried different codes, but the codes always not working. I want to reload just the specific section every 5 seconds, not reloading the whole page. It's important not to refresh the whole page, because it includes an chat function. If I would reload the whole page, people can't enter text without loosing it every 5 seccond. Like I said, I've tried some codes from stackOverflow but somehow they don't work for me.
Here's my code
<script type="text/javascript">
$(document).ready(function(){
setInterval(function(){
$("#context").load(window.location.href + " #context" );
}, 5000);
});
</script>
<--variables explained --->
$fid = $_GET['fid']
$username = $_SESSION['username']
$db :
$servername = "localhost";
$dbname = "psychopath";
$username = "root";
$password = "";
try{
$dsn = "mysql:host=" . $servername . ";dbname=" . $dbname;
$db = new PDO($dsn, $username, $password);
echo "";
}catch(PDOException $e){
echo $e.getMessage();
}
<--- variables END ----->
$display_messages = $db->prepare("SELECT * FROM mychat_from WHERE (user_to_name = ? OR userfrom_name = ?) AND (user_to_id = ? OR userfrom_id = ?)");
$display_messages->execute([$username , $username, $fid, $fid]);
while($row=$display_messages->fetch(PDO::FETCH_ASSOC)){
$userfrom = $row['userfrom'];
if($userfrom != $username){
$messagefrom2 = $row['message_from'];
$messagefrombreak2 = wordwrap($messagefrom2, 27, "\n", true);
?>
<?php
?><section id="context" name="context"><?php echo '<b> '.$userfrom.'</b>said:<br>';
echo "<section style='background: black; float: left; margin-left: 5px; border-radius: 7px; color: white;'> <font style='float: left;'> ".$messagefrombreak2."</font></section>";?>
</section>
<?php echo "<br><br>";
?>
And here is full code:
<!-- end snippet -->if(isset($_GET['fid'])){
$fid = $_GET['fid'];
?>
<section>
<section>
<?php
$get_friend = $db->prepare("do stuff");
$get_friend->execute([$fid]);
while($row=$get_friend->fetch(PDO::ROW STUFF)){
}
?>
</section>
<section>
<?php
$username = $_SESSION['username'];
$get_id = $db->prepare("do stuff");
$get_id->execute([$fid]);
while($row=$get_id->fetch(ROW STUFF)){
$get_your_id = $db->prepare("do stugg");
$get_your_id->execute([$username]);
while($row=$get_your_id->fetch(ROW STUFF)){
$display_messages = $db->prepare("DO STUFF");
$display_messages->execute([$your_id, $your_id, $fid, $fid]);
while($row=$display_messages->fetch(DO STUFF)){
$userfrom = $row['userfrom'];
if($userfrom != $username){
$messagefrom2 = $row['message_from'];
$messagefrombreak2 = wordwrap($messagefrom2, 27, "\n", true);
?>
<?php
?><div id="container" name="container"><div id="context" name="context"><?php echo '<b> '.$userfrom.'</b>said:<br>';
echo "<section style='background: black; float: left; margin-left: 5px; border-radius: 7px; color: white;'> <font style='float: left;'> ".$messagefrombreak2."</font></section>";?>
</div></div>
<?php echo "<br><br>";
?>
<script type="text/javascript">
$(document).ready(function(){
setInterval(function(){
$("#context").load(window.location.href + " #container" );
}, 5000);
});
</script>
<?php
}else{
$messagefrom = $row['message_from'];
$messagefrombreak = wordwrap($messagefrom, 27, "\n ", true);
echo "<font style='float: right;'><b>You </b>said: </font><br>";
echo "<section style='background: #960505; float: right; margin-right: 5px; border-radius: 7px; color:
white;'><font style='float: right;'> ".$messagefrombreak." </font></section><br><br>";
}}}}
?>
</section>
use ajax and json
ajax to make a call to server within the page
json little simple format
use setInterval
like
var myVar = setInterval(my_func, 5000);
my_func is a function that will hold ajax action. and do what do you need

persistent checkboxes, dynamic table, php javascript

I've been working on this nonstop and none of the online suggestions have worked.
I have a dynamically created table that refreshes every 5 seconds. There are checkboxes on the table, if you check a box it highlights the row. When the page refreshes all checked states are lost, I need them to be saved, either by local storage or a cookie or even writing out to a file.
Please help and thanks in advance.
My currently working code that does not retain the checked state:
<HTML>
<HEAD>
<TITLE>list</TITLE>
<META name="description" content="">
<META name="keywords" content="">
<meta http-equiv="refresh" content="5" >
<style>
.inv {
display: none;
}
table.sortable thead {
background-color:#999;
color:#222222;
font-weight: bold;
cursor: default;
}
table.sortable tbody {
counter-reset: sortabletablescope;
}
table.sortable thead tr::before {
content: "";
display: table-cell;
}
table.sortable tbody tr::before {
content: counter(sortabletablescope);
counter-increment: sortabletablescope;
display: table-cell;
}
</style>
<script src="../../sorttable.js"></script>
<script>
function toggle_highlight(inputTagReference)
{
var is_checked = inputTagReference.checked; //true or false
if(is_checked)
{
inputTagReference.parentNode.parentNode.style.backgroundColor="yellow";
}
else
{
inputTagReference.parentNode.parentNode.style.backgroundColor="";
}
}
</script>
</HEAD>
<BODY BGCOLOR="#dddddd" TEXT="#000000" LINK="#0000FF" VLINK="#800080">
<h1 align="center">List</h1>
<p align="center"> </p>
<p align="center">
<?php
echo '<div>';
//Create file with headers
system("cmd /C makeit.bat");
//Create html table
echo '<p align="center"> </p>';
echo '<p align="center"> </p>';
echo '<table class="sortable" align="center">';
$row = 0;
$handle = fopen("readylist.txt", "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($row == 0) {
// this is the first line of the file
// it contains titles of columns
$num = count($data);
echo "<thead>\n<tr>";
$row++;
for ($c=0; $c < $num; $c++) {
echo "<th align='left' height='75' width='135'>" . $data[$c] . "</th>";
}
echo "<td></td>";
echo "</tr>\n</thead>\n\n<tbody>";
} else {
// this handles the rest of the lines of the file
$num = count($data);
echo "<tr id=Row0$row>";
$row++;
for ($c=0; $c < $num; $c++) {
echo "<td id=Col0$c>" . $data[$c] . "</td>";
}
echo "<td><input type='checkbox' name='Chk$row id=Chk$row' value='Chk$row' onclick='toggle_highlight(this)'></td>";
echo "</tr>\n";
}
}
fclose($handle);
echo "</tbody>\n</table>";
echo '</div>';
?>
</p>
</BODY>
</HTML>
Here it is with nonworking solution:
<HTML>
<HEAD>
<TITLE>list</TITLE>
<META name="description" content="">
<META name="keywords" content="">
<meta http-equiv="refresh" content="5" >
<style>
#checkbox-container{
margin: 10px 5px;
}
#checkbox-container div{
margin-bottom: 5px;
}
#checkbox-container button{
margin-top: 5px;
}
input[type=text] {
padding: .5em .6em;
display: inline-block;
border: 1px solid #ccc;
box-shadow: inset 0 1px 3px #ddd;
border-radius: 4px;
}
.inv {
display: none;
}
table.sortable thead {
background-color:#999;
color:#222222;
font-weight: bold;
cursor: default;
}
table.sortable tbody {
counter-reset: sortabletablescope;
}
table.sortable thead tr::before {
content: "";
display: table-cell;
}
table.sortable tbody tr::before {
content: counter(sortabletablescope);
counter-increment: sortabletablescope;
display: table-cell;
}
</style>
<script src="../../sorttable.js"></script>
<script src="../../jquery.js"></script>
<script>
var formValues = JSON.parse(localStorage.getItem('formValues')) || {};
var $checkboxes = $("#checkbox-container :checkbox");
var $button = $("#checkbox-container button");
function allChecked(){
return $checkboxes.length === $checkboxes.filter(":checked").length;
}
function updateButtonStatus(){
$button.text(allChecked()? "Uncheck all" : "Check all");
}
function handleButtonClick(){
$checkboxes.prop("checked", allChecked()? false : true)
}
function updateStorage(){
$checkboxes.each(function(){
formValues[this.id] = this.checked;
});
formValues["buttonText"] = $button.text();
localStorage.setItem("formValues", JSON.stringify(formValues));
}
$button.on("click", function() {
handleButtonClick();
updateButtonStatus();
updateStorage();
});
$checkboxes.on("change", function(){
updateButtonStatus();
updateStorage();
});
// On page load
$.each(formValues, function(key, value) {
$("#" + key).prop('checked', value);
});
$button.text(formValues["buttonText"]);
</script>
<script>
function toggle_highlight(inputTagReference)
{
var is_checked = inputTagReference.checked; //true or false
if(is_checked)
{
inputTagReference.parentNode.parentNode.style.backgroundColor="yellow";
}
else
{
inputTagReference.parentNode.parentNode.style.backgroundColor="";
}
}
</script>
</HEAD>
<BODY BGCOLOR="#dddddd" TEXT="#000000" LINK="#0000FF" VLINK="#800080">
<h1 align="center">List</h1>
<p align="center"> </p>
<p align="center">
<?php
echo '<div id="checkbox-container">';
//Create file with headers
system("cmd /C makeit.bat");
//Create html table
echo '<p align="center"> </p>';
echo '<p align="center"> </p>';
echo '<table class="sortable" align="center">';
$row = 0;
$handle = fopen("readylist.txt", "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($row == 0) {
// this is the first line of the file
// it contains titles of columns
$num = count($data);
echo "<thead>\n<tr>";
$row++;
for ($c=0; $c < $num; $c++) {
echo "<th align='left' height='75' width='135'>" . $data[$c] . "</th>";
}
echo "<td></td>";
echo "</tr>\n</thead>\n\n<tbody>";
} else {
// this handles the rest of the lines of the file
$num = count($data);
echo "<tr id=Row0$row>";
$row++;
for ($c=0; $c < $num; $c++) {
echo "<td id=Col0$c>" . $data[$c] . "</td>";
}
echo "<td><input type='checkbox' name='Chk$row id=Chk$row' value='Chk$row' onclick='toggle_highlight(this)'></td>";
echo "</tr>\n";
}
}
fclose($handle);
echo "</tbody>\n</table>";
echo '</div>';
?>
</p>
</BODY>
</HTML>
here is the code from the page that answered the persistent checkbox question, this page works for me, but the code from it on my page does not.
<html >
<head>
<meta charset="UTF-8">
<title>CodePen - A Pen by SitePoint</title>
<style>
#checkbox-container{
margin: 10px 5px;
}
#checkbox-container div{
margin-bottom: 5px;
}
#checkbox-container button{
margin-top: 5px;
}
input[type=text] {
padding: .5em .6em;
display: inline-block;
border: 1px solid #ccc;
box-shadow: inset 0 1px 3px #ddd;
border-radius: 4px;
}
</style>
</head>
<body translate="no" >
<input type="text" placeholder="Type something here" />
<div id="checkbox-container">
<div>
<label for="option1">Option 1</label>
<input type="checkbox" id="option1">
</div>
<div>
<label for="option2">Option 2</label>
<input type="checkbox" id="option2">
</div>
<div>
<label for="option3">Option 3</label>
<input type="checkbox" id="option3">
</div>
<button>Check All</button>
</div>
<script src='../../jquery.js'></script>
<script>
var formValues = JSON.parse(localStorage.getItem('formValues')) || {};
var $checkboxes = $('#checkbox-container :checkbox');
var $button = $('#checkbox-container button');
function allChecked() {
return $checkboxes.length === $checkboxes.filter(':checked').length;
}
function updateButtonStatus() {
$button.text(allChecked() ? 'Uncheck all' : 'Check all');
}
function handleButtonClick() {
$checkboxes.prop('checked', allChecked() ? false : true);
}
function updateStorage() {
$checkboxes.each(function () {
formValues[this.id] = this.checked;
});
formValues['buttonText'] = $button.text();
localStorage.setItem('formValues', JSON.stringify(formValues));
}
$button.on('click', function () {
handleButtonClick();
updateButtonStatus();
updateStorage();
});
$checkboxes.on('change', function () {
updateButtonStatus();
updateStorage();
});
$.each(formValues, function (key, value) {
$('#' + key).prop('checked', value);
});
$button.text(formValues['buttonText']);
//# sourceURL=pen.js
</script>
</body>
</html>
Well, it's been a day, and I don't see anything here.
My assumption is that you guys are finding this just as difficult as I am.
I am still working on this and here is my logic.
I will have to get the insidehtml of one of the cells in the row as part of the onclick event, then set a cookie or use session to store the variable based on the row, and then an onload event that reads that session or cookie and checks the appropriate boxes and highlights the appropriate rows.
If anyone has any comments or suggestions, they are entirely welcome.
tia

Autocomplete Arrow Key Scroll

I am making a Ajax driven live search . But now I want to click the dropdown list to fill the html textbox. How can I modify my codes to include a function where the user can scroll through the results list using the up/down arrow keys. Here is the JavaScript code.
<script type="text/javascript">
function fill(Value) {
$('#name').val(Value);
$('#display').hide();
}
$(document).ready(function() {
$("#name").keyup(function() {
var name = $('#name').val();
if (name == "") {
$("#display").html("");
} else {
$.ajax({
type: "POST",
url: "ajax.php",
data: "name=" + name,
success: function(html) {
$("#display").html(html).show();
}
});
}
});
});
and here is the code in ajax.php page
if(isset($_POST['name'])) {
$name=trim($_POST['name']);
$query=mysqli_query($con,"SELECT * FROM mobile WHERE name LIKE '%$name%' LIMIT 0,5");
echo "<ul>";
while($query2=mysqli_fetch_array($query))
{ ?>
<div class="ajaxcontainer">
<li onclick='fill("<?php echo $query2[' name ']; ?>")'>
<a href="preview.php?id=<?php echo $query2['name']; ?>">
<div class="ajaximage">
<img src="<?php echo $query2['photo'];?>">
</div>
<div class="ajaxh1">
<h1><?php echo $query2['name']; ?></h1>
</div>
</a>
</li>
</div>
<?php } } ?>
good news.. after working 3 hours.. i got the solution to ur problem. Checkout the solution. let me know if you have any problems in this solution.I
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<style type="text/css">
ul{
position: absolute;
top: 5px;
left: 36px;
list-style: none;
}
li{
border: 1px solid grey;
width: 202px;
margin: 0px;
}
input{
width:200px;
}
</style>
<script>
function showHint(str){
if(str=="" || !str){
$("ul").empty();
return;
}
$.ajax({
type: "GET",
url: "gethint.php",
data: "q="+str,
success: function(html) {
var names = html.split(",");
var listItems ="";
var dropDown =$("#dropDown");
dropDown.innerHTML="";
$("ul").empty();
names.forEach(name =>{
var li = document.createElement("li");
li.appendChild(document.createTextNode(name));
dropDown.append(li);
$("li").click(function(){
$("#txt1").val($(this).text());
});
});
}
});
}
</script>
<h3>Start typing a name in the input field below:</h3>
<form action="">
<div style="position:relative">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)">
<ul id="dropDown"></ul>
</div>
</form>
</body>
</html>
This is my php file.
<?php
require("connection.php");
$sql ="SELECT name FROM users";
$a=array();
// OR $a=[];
$result=$conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$a[]=$row["name"];
//echo $row["name"];
}
}
else{
echo "No data to generate suggestions";
}
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
?>

How to select text and display it in another textfield using JavaScript or jQuery

I have a PHP/AJAX search script working just fine. The problem is when I type something in the text field the suggestions appear below, but they cannot be selected. In short, I want to select one of the suggestion and show the value in the search text field upon selecting it.
I have tried a solution in JavaScript, but it doesn't work. It shows an error in the console like "the select value is null".
ajax.php
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
</head>
<body>
<input id="sear" autocomplete="off" type="text" name="search"
placeholder="Seaarch here" onkeyup="search(this.value)">
<div onclick="ali()" id="list" ></div>
<script>
function search(str){
if(str.length ==0){
document.getElementById("list").innerHTML="Please Enter Something";
return;}
xml=new XMLHttpRequest();
xml.onreadystatechange=function(){
if(xml.readyState==4 && xml.status==200){
document.getElementById("list").innerHTML=xml.responseText;}
}
xml.open("GET","search.php?char="+str,true);
xml.send();
}
</script>
<script>
document.addEventListener("DOMContentLoaded",function(){
function ali(){
var acs;
var x=document.getElementById("#list").select();
acs=x.value;
document.getElementById("#sear").innerHtml=acs;
}
});
</script>
</body>
search.php
<?php
$con=mysqli_connect("localhost","root","","userdiary");
$str=$_GET['char'];
$sql="SELECT * FROM `login` WHERE `user_id` LIKE '$str%' OR `user_name` LIKE
'$str%'";
$query=mysqli_query($con,$sql);
if(mysqli_num_rows($query)>0){
while($res=mysqli_fetch_assoc($query)){
echo "<option>" .$res['user_name']."</option>"."<hr>";
}
}
else{
echo "No match Found..";
}
?>
If the #sear element looks something like this once suggestions populate into it:
<div id="list">
<option>test</option>
<option>test a</option>
<option>test b</option>
</div>
then you can try this for your jQuery script:
$('#list option').on('click', function() {
$('#sear').val($(this).text());
});
You typed select in worng way. It should be something as follows:
<select onchange="ali()" id="list" ></select>
You can check this code I used it yesterday. You just have to change the name of SQL part according to your goal
Also what I give you is jQuery ui you have to add
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" />
and your input must have auto class
search.php:
<?php
define('DB_SERVER', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'some');
if (isset($_GET['term'])){
$return_arr = array();
try {
$conn = new PDO("mysql:host=".DB_SERVER.";port=8889;dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT Tname FROM Topic WHERE Tname LIKE :term');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
while($row = $stmt->fetch()) {
$return_arr[] = $row['Tname'];
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
}
?>
and jQuery UI
$(function() {
$(".auto").autocomplete({
source: "search.php",
minLength: 1,
});
});
and css
.ui-menu .ui-menu-item a {
text-decoration: none;
display: block;
padding: 5px .4em;
line-height: 1.5;
min-height: 0;
font-weight: normal;
z-index:11;
}
ul#ui-id-1{
z-index:11;
display: none;
top: 132px;
left: 354.5px;
width: 283px;
}

Calling Javascript from a Form using Onsubmit

I am newbie in PHP and AJAX, and I am in trouble and don't know how to solve it.
I am creating this page that shows a recordset that resulted from a query.
There are 2 pages: getdata.php and phpajax.php. phpajax.php calls getdata.php via Javascript.
What I have done:
I manage to make it work by using button "Try it" (using static value)
What I want:
How to display the data properly using "Submit" button on a single click (ATM the data appears for a couple of seconds after I click Submit twice, then disappears because the page suddenly refreshes) ?
How to pass the value of SELECT and TEXT into fshowdata() using the Submit Button ?
How to pass the value of SELECT and TEXT into fshowdata() using the "Try It" Button ?
Here is the for the phpajax.php:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script>
function fshowdata(str1,date1) {
//alert("The form was submitted");
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
//document.getElementById("demo").innerHTML = str1 + " " + date1;
xmlhttp.open("GET","getdata.php?q="+str1+"&"+"t="+date1,true);
xmlhttp.send();
}
}
</script>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<p id="demo">Click the button to change the text in this paragraph.</p>
<?php
$con = mysql_connect('localhost','root','123');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb')or die('Could not select database');
$sql="SELECT DISTINCT(rides) FROM t_trx ORDER BY rides ";
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
echo "<form onsubmit='"."fshowdata(`some rides`,`a date`)"."' action='".""."'>";
echo "Choose Rides : "." "."<select id='"."rides"."' name='"."rides"."'>";
echo "<option value='"."ALL"."'>ALL</option>";
while($row = mysql_fetch_array($result)) {
echo "<option value='".$row["rides"]."'>".$row["rides"]."</option>";
}
mysql_free_result($result);
echo "</select>";
mysql_close($con);
echo "<input id='"."date2"."' type='"."TEXT"."' name = '"."date2"."'>";
echo "<input id='"."button1"."' type='"."SUBMIT"."' value = '"."SUBMIT"."'>";
echo "</form>";
echo "<button onclick='"."fshowdata(`ROLLER COASTER`,`18/07/2015`)"."'>";
echo "Try it";
echo "</button>";
?>
<br>
<div id="txtHint"><b>Data will be shown here...</b></div>
</body>
</html>
And for the getdata.php:
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$q = $_GET['q'];
echo $q;
$date_ = $_GET['t'];
echo $date_;
$con = mysql_connect('localhost','root','123');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb')or die('Could not select database');
$sql="SELECT * FROM t_trx WHERE rides = '".$q."' AND date1 = '".$date_."' LIMIT 10";
echo $sql;
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
echo "<table>
<tr>
<th>Rides</th>
<th>Number</th>
<th>Date</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['Rides'] . "</td>";
echo "<td>" . $row['Number'] . "</td>";
echo "<td>" . $row['Date'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
</body>
</html>
Thanks guys. I appreciate your help...
use below code to skip refresh page
onsubmit="return fshowdata(`some rides`,`a date`)"
in the fshowdata function, you should return false.

Categories