Heads up before reading. I'm totally new in html and so, so please be patient. I have the following html code and two javascript functions.
<HTML> <HEAD> ..... </HEAD>
<BODY>
<CENTER>
<form id="keyForm">
Όνομα/Επώνυμο: <input type="text" name="keyword"><br><br>
<input type="button" onClick="resetFunction()" value="Επαναφορά">
<input type="button" onClick="my_search(this.form.keyword.value)" value="Αναζήτηση">
</form>
<p id="results"></p>
</CENTER>
<script>
function resetFunction() {
document.getElementById("results").innerHTML = "";
document.getElementById("keyForm").reset();
}
</script>
<script>
function my_search(kw) {
document.getElementById("results").innerHTML = (
<table border="1" style="width:500px">
<tr>
<td>ID</td>
<td>Επίθετο</td>
<td>Όνομα</td>
<td>Ημερομηνία πρόσληψης</td>
<td>Τμήμα</td>
</tr>
</table> );
}
</script>
</BODY>
</HTML>
I want the "results" to be be table that is described in function "my_search" extended by the actual results produced by the following php code.
<?php
header("content-type: text/html;charset=utf-8");
$link = mysqli_connect("127.0.0.1","root", "tralalalalala", "mycompany");
if (!$link) {
printf("Connect failed: %s\n",
mysqli_connect_error());
exit();
}
//printf("Host information: %s<br>",
//mysqli_get_host_info($link));
$key = $_POST['keyword']; //Keyword in initialized in html
//echo $key; echo "<br>";
$stmt = mysqli_prepare($link, "
select e.emp_id, e.first_name, e.last_name, e.hire_date, d.dept_name
from employee e, department d
where e.dept_id = d.dept_id and (e.first_name like ? or e.last_name like ?)");
$likeKey = "%{$key}%";
mysqli_stmt_bind_param($stmt, "ss", $likeKey, $likeKey);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id, $f_name, $l_name, $hire_date, $d_name);
$stmt->store_result();
$rows = $stmt->num_rows;
if ($rows)
printf("Βρέθηκαν %d αποτελέσματα<br>", $rows);
else
printf("Δε βρέθηκαν αποτελέσματα για τη λέξη-κλειδί \"%s\" <br>", $key);
for ($i = 0; $i<$rows; $i++){
mysqli_stmt_fetch($stmt);
printf("%d %s %s %s %s <br>", $id, $f_name, $l_name, $hire_date, $d_name);
}
mysqli_stmt_close($stmt);
mysqli_close($link);
?>
In the end I wanna have something like this
It's Greek but I think you can handle it ;) Thank you for your replies :)
You can append a string using +=
var str;
str += '<tr>';
str += '<td>Text</td>';
str += '<tr>';
-Do not use <center>, it is deprecated
Here is more information about deprecated attributes http://www.w3.org/TR/html4/index/attributes.html
-You have to use AJAX. Here is some information about AJAX jQuery http://api.jquery.com/jquery.ajax/ and http://jquery.com/
You can try this:
$(function(){
$("form").submit(function(){
$.ajax({
url: "", //put the name of the php file
type: "post",
data: { keyword: $(".keyword").val() },
success: function(response){
//add the output from the php file to the div in the html file using
//append() or html()
}
});
});
}
Related
I have some code where I need to update a column of a table (MySQL) calling another php file without leaving the page where some tables might allow inline editing.
I have a point in the php echoing of the page, where an icon can be clicked to save input. The code at that point is:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?php
$sql = "SELECT * FROM table WHERE a_column='certain_value'";
if (mysqli_query($conn, $sql)) {
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$note = $row["note"];
$code = $row["code"];
}
}
}
// some tabled elements not relevant for the issue
echo "<input type='text' id='note_1' name='note_1' value=$note readonly>";
echo "<input type='text' id='new_note' name='new_note'>";
echo "<img src='icon_to_click.png' id='icon_to_click' name='icon_to_click' >";
?>
<script type="text/javascript">
$(document).ready(function() {
$('#icon_to_click').click(function() {
var note_orig = document.getElementById('note_1').value;
var code_val = '<?php echo "$code" ?>';
var note_new = document.getElementById('new_note').value;
if (note_new != note_orig) {
$.ajax({
type: 'POST',
url: 'update_notes.php',
data: {'code': code_val, 'note': note_new},
success: function(response){
document.getElementById('note_1').value = note_new;
}
});
}
});
});
The relevant code of update_notes.php is:
<?php
// connection
$unsafe_note = $_POST["note"];
$code = $_POST["code"];
require "safetize.php"; // the user input is made safe
$note = $safetized_note; // get the output of safetize.php
$sqlupdate = "UPDATE table SET note='$note' WHERE code='$code'";
if (mysqli_query($conn, $sqlupdate)) {
echo "Note updated";
} else {
echo "Problem in updating";
}
// close connection
?>
Now when I run the code and look at the tool, it gives me the error: Uncaught ReferenceError: $ is not defined, linking the error to this line of the previous js code:
$(document).ready(function() {
So, how can I fix that?
It means that you tried to use Jquery in your Javascript Code without calling Jquery Library or the code is called without the library was fully loaded.
I notice :
That you haven't closed your script tag
You use Jquery so you can use $('#id_name') to select element by Id instead of document.getElementById('note_1')
Get element value by using Element.val() instead of Element.value
Try to edit your code like this
<?php
$sql = "SELECT * FROM table WHERE a_column='certain_value'";
if (mysqli_query($conn, $sql)) {
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$note = $row["note"];
$code = $row["code"];
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Some title</title>
</head>
<body>
<form method="post" accept-charset="UTF-8">
<input type='text' id='note_1' name='note_1' value=<?= $code ?> readonly>";
<input type='text' id='new_note' name='new_note'>";
<img src='icon_to_click.png' id='icon_to_click' name='icon_to_click' >";
</form>
<script>
$(document).ready(function() {
$('#icon_to_click').click(function() {
var note_orig = $('#note_1').val();
var code_val = '<?= $code ?>';
var note_new = $('#new_note').val();
if (note_new != note_orig) {
$.ajax({
type: 'POST',
url: 'update_notes.php',
data: {'code': code_val, 'note': note_new},
success: function(response){
$('#note_1').val() = note_new;
}
});
}
});
});
</script>
</body>
</html>
Hey I have faced same error a day before,this is because you have missed using a jquery library script that is needed. please try using some Updated Jquery CDN . :) It will definitely help
OR
include the jquery.js file before any jquery plugin files.
I'm making a quiz website, for that questions and answers will be fetched from database and using PHP and MySQL.
I've stored the options in one single column using JSON.(Stored as string array) Question is displaying correctly but options couldn't; I've written them in similar manner.
quiz.php
echo '
<div id="ques_block">
<br>
<p id="ques"></p>
';
for($i=0; $i<$_SESSION["opt_size"]; $i++)
echo '<p class="opt" id="opt'.$i.'"></p>';
echo '
<div id="nav-for"><img src="next.png" alt="Next =>"></div>
</div>
';
next.php will be called using AJAX when NEXT is clicked.
next.php
$sql = "SELECT QUESTION, ANSWER, OPTIONS FROM user_quiz WHERE CUST_NO=$cust_no AND QUES_NO=$new_ques_no;";
$res = mysqli_query($conn, $sql) or die("bad Query: $sql");
if(mysqli_num_rows($res)==0)
echo "END";
else
{
$row = mysqli_fetch_assoc($res);
$ques = $row["QUESTION"];
$opts = $row["OPTIONS"];
$opt = json_decode($opts);
$resRows = sizeof($opt);
echo '
<script type="text/javascript">
document.getElementById("ques").innerHTML="'.$ques.'";
</script>
';
for($i=0; $i<$resRows; $i++)
echo '<script type="text/javascript">
document.getElementById("opt'.$i.'").innerHTML = "'.$opt[$i].'";
</script>
';
}
Edited:
#ADyson I'll try your method, Thanks,
BTW This is AJAX code as requested:
$(document).ready(function(){
$("#nav-for").click(function(){
$.post("nextQues.php",
{custNo: $("#custNo").val(), quesNo: $("#quesNo").val()},
function(data){
$("#ques").html(data);
}
);
});
});
I am using Ajax to add 3 values to my database, and then immediately append them at the bottom of my Table using the following:
**EDIT: Added the full code, and I currently only adding 1 value to the database, leaving the others empty (Adding only Text1)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function() {
$("#Submit").click(function (e) {
e.preventDefault();
if($("#Text1").val()==='')
{
alert("Please enter some text!");
return false;
}
var myData = 'txt1='+ $("#Text1").val(); //build a post data structure
jQuery.ajax({
type: "POST",
url: "ajax.php",
dataType:"text",
data:myData,
success:function(response){
var row_data = "";
row_data +="<tr><td><?php echo $_POST['txt1'] ; ?></td><td><?php echo $_POST['txt1'];?></td><td><?php echo $_POST['txt1'];?></td></tr>";
$("#mytable").append(row_data);
$("#responds").append(response);
$("#Text1").val(''); //empty text field on successful
$("#FormSubmit").show(); //show submit button
$('table').html(data);
},
error:function (xhr, ajaxOptions, thrownError){
$("#FormSubmit").show(); //show submit button
alert(thrownError);
}
});
});
});
</script>
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "test_database";
$mysqli = new mysqli($servername, $username, $password, $dbname);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
echo "Connected successfully";
if(isset($_POST["txt1"]) && strlen($_POST["txt1"])>0)
{
$contentToSave = filter_var($_POST["txt1"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$insert_row = $mysqli->query("INSERT INTO test_table(fname) VALUES('".$contentToSave."')");
if($insert_row)
{
$mysqli->close(); //close db connection
}else{
header('ERROR');
exit();
}}
?>
<div class="form_style">
<textarea name="content_txt" id="Text1" cols="45" rows="1"></textarea><br>
<button id="Submit">Add record</button>
</div><br>
<table class="table" id="mytable" style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
//initially filling the table with db data
<?php
$sql = "SELECT fname, lname, age FROM test_table";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>". $row["fname"] . "</td><td>" . $row["lname"] . "</td><td>" . $row["age"] . "</td></tr>";
}
} else {
echo "0 results";
}
$mysqli->close();
?>
</table>
</body>
</html>
The posting does work: txt1, txt2 and txt3 are inserting into the database, but what I see at the bottom of the table is '.$_POST['txt1'].' and so on, instead of the actual POST data
if you want to use php code in javascript then try below ==>
success:function(response){
var row_data = "";
row_data +="<tr><td><?php echo $_POST['txt1'] ; ?></td><td><?php echo $_POST['txt2'];?></td><td><?php echo $_POST['txt3'];?></td></tr>";
The argument you named response in the declaration of the function for success setting of the ajax call (I assume you are using jQuery's $.ajax) contains whatever your Web server sent to you.
In your case if you send AJAX request to the code you provided, that is, if the code you provided is exactly that ajax.php you referenced in the url setting of the jQuery.ajax call, THEN THE response VAR WILL CONTAIN FULL HTML TEXT RENDERED, which is probably absolutely useless to you.
Proper usage of the AJAX would be like this:
$.ajax({
// ...
dataType: 'json', // I can remember incorrectly here. It assumes your PHP backend sends JSON-encoded string.
success: function (data) { // data will be an object already parsed from JSON string sent by server.
var row_data = "";
row_data += "<tr><td>";
row_data += data.txt1;
row_data += "</td><td>";
row_data += data.txt2;
row_data += "</td><td>";
row_data += data.txt3;
row_data += "</td></tr>";
}
});
Move the block of code starting with if(isset($_POST["txt1"]) && strlen($_POST["txt1"])>0) to the very beginning of the file and do the following on successful insert to the database:
header("Content-Type: application/json");
echo json_encode(['txt1' => $_POST['txt1'], 'txt2' => #$_POST['txt2'], 'txt3' => #$_POST['txt3']);
die();
This way when handler registered in success will be entered, the response will contain the proper JSON block. You don't need to re-render the whole page on AJAX requests.
You don't need the $("#responds").append(response); block because it'll lie to you due to rendering of the response contents according to HTML rendering rules. Just use the F12 in browser and inspect the server response directly.
I want to pass the output from PHP's file_get_contents() to JavaScript and calculate its length. Everything ok but when passing the variable JavaScript evaluates it as HTML code, so I have to use PHP's json_encode() to keep it "sane" but this way the string length from JavaScript will be different from the one in PHP. Using JS's JSON.parse() doesn't help because again the HTML code gets interpreted. Any idea how can I achieve the same evaluated data length?
EDIT: Basically I need to count all the characters in the page source, that includes tags and special characters. To have the same output computed in JS like the one i get in PHP's strlen($url_data).
EDIT 2: I thought about doing bin2hex() on the $url_data then reconvert in JS and check the length. Would be that reliable?
Here is what I did so far:
<?php
ini_set('display_erros', -1);
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['urlinput']) && !filter_var($_POST['urlinput'], FILTER_VALIDATE_URL) === false) {
$url = filter_var($_POST['urlinput'], FILTER_SANITIZE_URL);
$url_data = #file_get_contents($url);
$js_url_data = json_encode($url_data);
//$url_src = htmlspecialchars($url, ENT_IGNORE);
$url_data_len = mb_strlen($url_data);
$url_src = strip_tags($url_data);
echo '<ul id="resultList">';
echo "<li>The following page contains " . $url_data_len . " characters</li>";
echo "<li>Page URL: " . $_POST['urlinput'] . "</li>";
echo "<li>Page title: " . page_title($url_data) . "</li>";
echo "<li>Protocol: " . parse_url($url, PHP_URL_SCHEME) . "</li>";
echo "<li>Host: " . parse_url($url, PHP_URL_HOST) . "</li>";
echo "</ul>";
//var_dump($url_src);
} else {
$error = "URL is not valid!";
}
}
function page_title($str) {
$matches = array();
if (preg_match('/<title>(.*?)<\/title>/i', $str, $matches)) {
return $matches[1];
}
else {
return null;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PHP file_get_contents()</title>
</head>
<body>
<div class="url_class">
<form id="getsrc" method="post">
<input style="width: 300px;" type="text" name="urlinput" id="urlinput" placeholder="URL">
<input type="submit" name="submit" value="Get SRC">
</form>
</div>
<textarea rows="20" cols="50">
<?php
if (!empty($url_src)) {
echo $url_src;
}
?>
</textarea>
<?php echo '<br><span style="color:red">' . $error . '<span>'; ?>
<?php
if (!empty($js_url_data)) {
$script = <<<EOT
<script>
var url_data = $js_url_data;
var node = document.createElement("li");
var textnode = document.createTextNode("JavaScript page characters: " + url_data.length);
node.appendChild(textnode);
document.getElementById("resultList").appendChild(node);
</script>
EOT;
echo $script;
}
?>
</body>
</html>
Simply use the value calculated by php, it can be used within EOT block:
...
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['urlinput']) && !filter_var($_POST['urlinput'], FILTER_VALIDATE_URL) === false) {
...
$url_data = #file_get_contents($url);
$fileSize = strlen($url_data);
...
}
....
if (!empty($js_url_data)) {
$script = <<<EOT
<script>
...
var textnode = document.createTextNode("JavaScript page characters: " + $fileSize);
...
</script>
EOT;
echo $script;
Since no good answer, I would post my solution to my problem. The only way I could find was to hex-encode $url_data, pass it to JS, decode it and count the characters. For the pack() function I used the one ported in php.js.
...
$js_url_data = bin2hex($url_data);
...
if (!empty($js_url_data)) {
/* This is a good example when one is forced to use inline JS */
$script = <<<EOT
<script>
var url_data = "$js_url_data";
var url_data_len = pack('H*', url_data).length;
var node = document.createElement("li");
var textnode = document.createTextNode("JavaScript calculation page characters: " + url_data_len);
node.appendChild(textnode);
document.getElementById("resultList").appendChild(node);
</script>
EOT;
echo $script;
...
I have a Ajax PHP Show More feature like youtube and Live search scripts but I can't get them to work together. For example my live search works but then the show more feature doesn't work with it on the search results and when I use the show more then the live search doesn't work.
They don't seem to be messing with each other. Can anyone help me out? I am new to this website so I will try my best to show my code and explain it.
INDEX.PHP
<?php
include_once("connect.php");
$sql = "SELECT COUNT(*) FROM database";
$query = mysqli_query($connect,$sql) or die (mysqli_error());
$item_per_page = 3;
$total_rows = mysqli_fetch_array($query);
$pages = ceil($total_rows[0]/$item_per_page);
?>
<!DOCTYPE html>
<head>
<script type="text/javascript">
// Show More Scripted
$(document).ready(function() {
var track_click = 0;
var total_pages = <?php echo $pages; ?>;
$('#news-table-wrap').load("showmore_search.php", {'page':track_click}, function() {track_click++;});
$(".load_more").click(function (e){
$(this).hide();
$('.animation_image').show();
if(track_click <= total_pages){
$.post(showmore_search.php',{'page': track_click}, function(data) {
$(".load_more").show();
$("#news-table-wrap").append(data);
$("html, body").animate({scrollTop: $("#load_more_button").offset().top}, 500);
$('.animation_image').hide();
track_click++;
}).fail(function(xhr, ajaxOptions, thrownError){
alert(thrownError);
$(".load_more").show();
$('.animation_image').hide();
});
if(track_click >= total_pages-1){
$(".load_more").attr("disabled", "disabled");
}
}
});
});
// Live Search Script
function searchNews(value) {
$.post("showmore_search.php", {newsResult:value}, function(data){
$("#news-table-wrap").html(data);
});
}
</script>
</head>
<body>
<input type="text" name="search" id="search" class="search-box" onKeyUp="searchNews(this.value)" placeholder="Search News">
<table id="news-table-wrap" class="news-table-wrap" cellpadding="0" cellspacing="0">
</table>
<div align="center">
<div class="load_more" id="load_more_button">Show More</div>
<div class="animation_image" style="display:none;"><img src="/files/ajax-loader.gif"></div>
</div>
</body>
</html>
SHOWMORE_SEARCH.php
<?php
include_once("connect.php");
$newsResult = $_POST['newsResult'];
$item_per_page = 3;
$page_number = $_POST["page"];
$position = ($page_number * $item_per_page);
$sql = "SELECT * FROM database WHERE headline LIKE '%$newsResult%' OR post LIKE '%$newsResult%' ORDER BY date DESC LIMIT $position, $item_per_page";
$query = mysqli_query($connect,$sql) or die (mysqli_error());
while ($row = mysqli_fetch_array($query)){
$headline = $row['headline'];
$author = $row['author'];
$date = $row['date'];
$post = $row['post'];
$name = $row['name'];
echo "<tr class='news-preview-wrap'>";
echo "<td><div class='news-preview-content'><div class='news-preview-headline'><a href='news_post?name=".$name."'>".$headline."</a></div>
<div class='news-preview-date'>Written by ".$author." on ".$date."</div>
<div class='news-preview-post'>".$post."</div></div>
<div class='news-more'><a href='news_post?name=".$name."'>Read More</a></div></td>";
echo "</tr>";
} else {
echo "<div class='search-error'>No search results were found...</div>";
}
?>
Here is something you can do with Ajax, PHP and JQuery. Hope this helps or gives you a start.
See live demo and source code here.
http://purpledesign.in/blog/to-create-a-live-search-like-google/
Create a search box, may be an input field like this.
<input type="text" id="search" autocomplete="off">
Now we need listen to whatever the user types on the text area. For this we will use the jquery live() and the keyup event. On every keyup we have a jquery function “search” that will run a php script.
Suppose we have the html like this. We have an input field and a list to display the results.
<div class="icon"></div>
<input type="text" id="search" autocomplete="off">
<ul id="results"></ul>
We have a Jquery script that will listen to the keyup event on the input field and if it is not empty it will invoke the search() function. The search() function will run the php script and display the result on the same page using AJAX.
Here is the JQuery.
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
//Listen for the event
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search_st.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
})
;
In the php, shoot a query to the mysql database. The php will return the results that will be put into the html using AJAX. Here the result is put into a html list.
Suppose there is a dummy database containing two tables animals and bird with two similar column names ‘type’ and ‘desc’.
//search.php
// Credentials
$dbhost = "localhost";
$dbname = "live";
$dbuser = "root";
$dbpass = "";
// Connection
global $tutorial_db;
$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$tutorial_db->set_charset("utf8");
// Check Connection
if ($tutorial_db->connect_errno) {
printf("Connect failed: %s\n", $tutorial_db->connect_error);
exit();
}
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);
// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
// Build Query
$query = "SELECT *
FROM animals
WHERE type LIKE '%".$search_string."%'
UNION ALL SELECT *
FROM birf
WHERE type LIKE '%".$search_string."%'"
;
$result = $tutorial_db->query($query);
while($results = $result->fetch_array()) {
$result_array[] = $results;
}
// Check If We Have Results
if (isset($result_array)) {
foreach ($result_array as $result) {
// Format Output Strings And Hightlight Matches
$display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['desc']);
$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['type']);
$display_url = 'https://www.google.com/search?q='.urlencode($result['type']).'&ie=utf-8&oe=utf-8';
// Insert Name
$output = str_replace('nameString', $display_name, $html);
// Insert Function
$output = str_replace('functionString', $display_function, $output);
// Insert URL
$output = str_replace('urlString', $display_url, $output);
// Output
echo($output);
}
}else{
// Format No Results Output
$output = str_replace('urlString', 'javascript:void(0);', $html);
$output = str_replace('nameString', '<b>No Results Found.</b>', $output);
$output = str_replace('functionString', 'Sorry :(', $output);
// Output
echo($output);
}
}