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.
Related
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
I want to try get a traffic light colour scheme with my time text where if the time is between 0.0000 and 10.0000 the text if green if between 10.0100 and 15.0000 the text is orange and between 15.0100 and 20.0000 then its red i cant get my function to run i may be missing something but im not sure what.
currently the mysql query returns result as 14.6263 with this value constantly changing
my current code is :
<!doctype html>
<html>
<head>
<title>time stats</title>
<style>
body {
background-color: black;
}
.box1 {
width: 300px;
height: 400px;
border: 15px solid yellow;
padding: 15px;
margin: 15px;
display: inline-block;
color: white;
font-size:40px;
color: lime;
.container {
text-align: center;
}
</style>
<body>
<div class="box1">
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','username','password','test');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="select avg(time_format(delivery_avg,'%i:%s')) as time_avg from test.del where location = 'yellow'";
$result = mysqli_query($con,$sql);
echo "<table>
<thead>
<th>time Average</th>
</thead>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['time_avg'] . "</td>";
echo "</tr>";}
echo "</table>";
mysqli_close($con);
?>
</div>
function updatecolor() {
//console.log('function called');
{
if ($box1.td < 10)
return '#00FF00';
else if ($box1.td >= 11 && $box1.td<= 15)
return = '#FFA500';
else if ($box1.td >= 16 && $box1.td<= 20)
return = '#ff0000';
}
});
}
var updateInterval = setInterval(updatecolor, 1000);
</body>
</html>
Here's a little function that will return your colors depending on the $valueToCheck parameter of the function:
<?php
function addColor($valueToCheck) {
{
if ($valueToCheck <= 10) {
return '#00FF00';
} else if ($valueToCheck >= 11 && $valueToCheck <= 15) {
return '#FFA500';
} else if ($valueToCheck >= 16 && $valueToCheck <= 20) {
return '#ff0000';
}
};
}
?>
Wrapped it in <?php ?> tags, since it's a PHP function.
Use it in your HTML like so:
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td style=\"color:" . addColor($row['time_avg']) . "\">";
echo $row['time_avg'];
echo "</td>";
echo "</tr>";
}
As for your code:
return = '#FFA500'; is not valid, remove the =.
If $box1 were available:
if ($box1.td < 10)
return '#00FF00';
else if ($box1.td >= 11 && $box1.td<= 15)
What about 10? You never check for 10>x>11.
I am working on a website using CKEditor. I tried to incorporate the Image Uploader plugin (https://ckeditor.com/cke4/addon/uploadimage). When I try to copy in the image, I get an error: "Cannot read property 'getEditor' of undefined". I am fairly certain that I installed the files correctly because I am able to paste a photo into the textarea, but it is unable to post. The documentation (https://docs.ckeditor.com/ckeditor4/docs/#!/guide/dev_file_upload) of the plugin mentioned a lot of different code that the plugin requires, and it is likely that I am missing those files however the documentation is not very clear and is difficult to understand. If the problem is that I am missing those files, I would greatly appreciate it if someone could explain it to me. Here is the code of my file I am using:
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
require_once('../utils.php');
$access = $_REQUEST['access'];
$selectedPost = $_REQUEST['selectedPost'];
$submit = $_REQUEST['submit'];
$create = $_REQUEST['create'];
$delete = $_REQUEST['delete'];
$save = $_REQUEST['save'];
?>
<html>
<head>
<style>
body
{
background-image: url('../imgs/background.jpg');
text-align: left;
}
h2 {
color: #880000;
}
#wrapper
{
font-family: arial;
padding-top: 50px;
padding-bottom: 50px;
padding-left: 20px;
padding-right: 20px;
background: #FFFFFF;
width: 800px;
}
</style>
<script type="text/javascript" language="javascript" src="ckeditor/ckeditor.js"></script>
</head>
<body>
<div id="wrapper">
<?php
// PRINTING OUT PAGE STUFF
echo '<h2>Manage News Posts</h2>';
// Boot you out if you lack the login stuff in the POST
if(!$access) {
echo '<h2>Invalid Login Credentials.</h2>';
echo 'Back';
}
// We are authenticated
else {
// Something was submitted. Do whatever we are trying to, then dump us back
// to the main post selection UI.
if($submit) {
if($create) {
$query = "INSERT INTO blog_posts VALUES (NULL, '" . $_REQUEST['postSubject'] . "', '" . $_REQUEST['postBody'] . "', CURRENT_DATE)";
$insertPost = doQuery($query);
$query = '';
if($insertPost) {
echo '<i><h4>New Post Created!</h4></i>';
}
else {
echo '<i><h4>Error encountered during New Post creation!</h4></i>';
}
}
else if ($save) {
$query = "UPDATE blog_posts SET subject = '" . $_REQUEST['postSubject'] . "', body = '" . $_REQUEST['postBody'] . "' WHERE post_id = " . $selectedPost;
$updatePost = doQuery($query);
$query = '';
if($updatePost) {
echo '<i><h4>Post Updated Successfully!</h4></i>';
}
else {
echo '<i><h4>Error encountered during post update!</h4></i>';
}
}
else if ($delete) {
$query = "DELETE FROM blog_posts WHERE post_id = " . $selectedPost;
$deletePost = doQuery($query);
$query = '';
if($deletePost) {
echo '<i><h4>Post Deleted.</h4></i>';
}
else {
echo '<i><h4>Error encountered during deletion!</h4></i>';
}
}
$selectedPost = false;
$save = false;
$create = false;
$delete = false;
}
// Nothing selected, show the selection page.
if(!$create && !$selectedPost) {
echo '<form method="post" action="admin_posts.php?access=1">';
$query = "SELECT * FROM blog_posts ORDER BY post_id ASC";
$all_posts = getResults($query);
// Lay out selections
foreach($all_posts as $post) {
echo '<input type="radio" name="selectedPost" value="' . $post['POST_ID'] . '"/>' . ' ' . $post['SUBJECT'] . ' - (Posted on ' . $post['POST_DATE'] . ')<br/>';
}
echo '<input type="submit" value="Select" />';
echo '</form>';
// Create post button, gets its own form.
echo '<br/><br/>';
echo '<form method="post" action="admin_posts.php?access=1&create=1">';
echo '<input type="submit" value="Write New Post">';
echo '</form>';
// Back button
echo 'Back';
}
// End initial "nothing selected" box
// Something is selected, display its info for editing.
else {
echo '<br/>';
$post_subject = '';
$post_body = '';
if(!$create) {
$query = "SELECT * FROM blog_posts WHERE post_id = $selectedPost";
$post_data = getSingleRow($query);
$post_subject = $post_data['SUBJECT'];
$post_body = $post_data['BODY'];
}
// Print out the dialogue for creating and editing post
echo '<form method="post" action="admin_posts.php?access=1&submit=1">';
echo '<h4>Subject</h4>';
echo '<input name="postSubject" type="text" value="' . $post_data['SUBJECT'] . '" size=100/>';
echo '<br/>';
echo '<h4>Post Body</h4>';
echo '<textarea id="postBody" name="postBody" type="text" rows="25" cols="75">' . $post_data['BODY'] . '</textarea>';
echo '<br/><br/>';
if($create) {
echo '<input type="hidden" name="saveNewPost" value="1">';
echo '<input type="hidden" name="create" value="1">';
}
else {
echo '<input type="hidden" name="selectedPost" value="' . $selectedPost . '">';
echo '<input type="hidden" name="save" value="1">';
}
echo '<input type="submit" value="Save Post" />';
echo '</form>';
// Delete button. Only if you are editing.
// Gets its own submit form.
if(!$create) {
echo '<form method="post" action="admin_posts.php?access=1&submit=1&delete=1" onsubmit="return confirm(\'Are you sure you want to delete this post?\');">';
echo '<input type="hidden" name="selectedPost" value="' . $selectedPost . '">';
echo '<input type="submit" value="Delete Post">';
echo '</form>';
}
echo '<br/><br/>';
// Back button
echo 'Back';
}
}
?>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript">
bkLib.onDomLoaded(function()
{
CKEDITOR.replace( 'postBody' );
});
</script>
</div>
</body>
</html>
I am trying to make a copy button. It only gives an error in Chrome:
Uncaught SyntaxError: Unexpected token }
I tried lots of different scripts, but none worked. Everything works except the copy button. I even went to the ICT part of our school. They did not have a solution.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
This is the copy script
<script>
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
</script>
This is the end of the copy script
<?php
$str1 = "'";
$str2 = '#';
?>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
</style>
<?php
$link = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sqlget = "SELECT FROM redeem";
$result = $link->query($sqlget);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo"<table>";
echo "<tr><th>Code: </th>
<th id=" . $row['code']. ">" . $row['code']. "</th>
<th>Expires: </th><th>". $row['expires']."</th>
<th><button onclick='copyToClipboard($str2".$row['code'].")'><p id=" . $row['code']. ">...</button></th></tr></table>";
}
} else {
echo "0 results";
}
?>
This code is the working version of the copy button.
<center>
<p id="p1">Hello, I'm TEXT 1</p>
<p id="p2">Hi, I'm the 2nd TEXT</p><br/>
<button onclick="copyToClipboard('#p1')">Copy TEXT 1</button>
<button onclick="copyToClipboard('#p2')">Copy TEXT 2</button>
<br/><br/><input class="textBox" type="text" id="" placeholder="Dont belive me?..TEST it here..;)" />
</center>
Hope you guys/girls can help me out.
copyToClipboard($str2".$row['code'].")
produce : copyToClipboard(#code)
It should be :
"[...]copyToClipboard(\"$str2".$row['code']."\")[...]"
or even better :
"onclick='copyToClipboard(" . '"' .$str2 . $row['code']. '"' . ")'"
With the output copyToClipboard("#code")
FIXED!!!
IT finally woooorrrrkkssss!!!
It took me a while. But thanks to Blag his part of the code. I found it.
<?php $str1 = "'"; ?>
This was the sollution.
<th><button onclick='copyToClipboard(".$str1. $str2 . $row["code"] .$str1. ")'>
im a fairly newbie into javascript and php (just got less than two weeks max)however im trying to learn because i really enjoy this,anyway, right now im trying to do a proyect for the company where i work for ( not that we will use it, but as an incentive).
the proyect is about making a query in sql that would return a table, but using the parameters given in three drop down's
now those three 's must pick three conditionals. ie
$sql ="SELECT * FROM catalogo WHERE escuelas='$e' and grado='$g' and seccion='$p'";
so far i have wrote ( and to be honest copy/paste a lot from different sources)
the basics, but im stuck trying to a query.. anyway here is my code for the index.php
<script>
function showescuelas(str) {
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;
}
}
xmlhttp.open("GET","ajaxdatospersonales.php?e="+str, true);
//xmlhttp.open("GET","ajaxdatospersonales.php?e="+document.getElementById("esc").value+"&gra="+document.getElementById("gra").value+"&sec="+document.getElementById("sec").value,,true);
xmlhttp.send();
}
}
</script>
</header>
<?php include_once("menu.php"); ?>
<div class="container">
<h1> Agregar apartado </h1>
<form id="form" method="post" action="procesadordatospersonales.php" >
<!-- down below is my first filter, it feeds from a table named "escuelas"-->
<p> <label for="escuelas">Escuela:</label>
<select name="escuelas" id="esc" onchange="showescuelas(this.value)">
echo "<option> </option>";
<?php
$con = mysql_connect('localhost', 'root', 'pass') or die(mysql_error());
mysql_select_db('apartados');
$sql = "SELECT escuelas FROM escuelas";
$data = mysql_query($sql,$con);
while($category = mysql_fetch_array($data)){
$catname = $category['escuelas'];
$valueid = $category['escuelas'];
echo '<option value="'.$valueid.'">'.$catname.'</option>';
}
?>
</select>
<br />
</p>
<!-- down below is my second filter, it feeds from a table named "grados"-->
<p> <label for="grado">grado:</label>
<select name="grado" id="gra" onChange="showgrados(this.value)">
echo "<option> </option>";
<?php
$con = mysql_connect('localhost', 'root', 'pass') or die(mysql_error());
mysql_select_db('apartados');
$sql = "SELECT grado FROM grado";
$data = mysql_query($sql,$con);
while($category = mysql_fetch_array($data)){
$catname = $category['grado'];
$valueid = $category['grado'];
echo '<option value="'.$valueid.'">'.$catname.'</option>';
}
?>
</select>
<br />
</p>
<!-- yep you guess it this is the last filter, it feeds from a table named "grados"-->
<p> <label for="seccion" >seccion:</label>
<select name="seccion" id="sec" onChange="showescuelas(this.value)">
echo "<option> </option>";
<?php
$con = mysql_connect('localhost', 'root', 'pass') or die(mysql_error());
mysql_select_db('apartados');
$sql = "SELECT seccion FROM seccion";
$data = mysql_query($sql,$con);
while($category = mysql_fetch_array($data)){
$catname = $category['seccion'];
$valueid = $category['seccion'];
echo '<option value="'.$valueid.'">'.$catname.'</option>';
}
?>
</select>
<br />
</p>
</div>
</div>
<div id="txtHint"><b> info will be listed here.</b></div>
<input type="submit" value="Agregar">
</form>
and this is my "ajaxdatospersonales.php"
<?php
$e=$_GET["e"];
$g=$_GET["g"];
$s=$_GET["s"];
$con = mysqli_connect('localhost','root','pass','apartados');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con);
//i made this array just to check if the variables
$test= array("$e", "$g", "$s");
echo "esta es la escuela " . $test[0] . " y este el grado " . $test[1] . " y la seccion " . $test[2] . ".";
$sql ="SELECT * FROM catalogo WHERE escuelas='$e' and grado='$g' and seccion='$p'";
$result = mysqli_query($con, $sql);
$ii=1;
echo "<table border='1'>
<tr>
<th>agregar</th>
<th>isbn</th>
<th>nombre</th>
<th>autor</th>
<th>editorial</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td> <input type='checkbox' name= isbn".$ii." value=".$row['isbn']. " </td>";
echo "<td>" . $row['isbn'] . "</td>";
echo "<td>" . $row['nombre'] . "</td>";
echo "<td>" . $row['autor'] . "</td>";
echo "<td>" . $row['editorial'] . "</td>";
echo "</tr>";
$ii++;
}
echo "</table>";
mysqli_close($con);
?>
now for some reaso it just dosent work.... i dont know whats going on..
thanks.
now if you decide to help me please, try to be as newbie frendly as possible.
also i already know about sql injection. but this is a proyect for fun