I am using JavaScript, PHP and HTML for my application. I have a SQL database that contains tweets. I need to query from database and display tweets after the keyword (connecting to a hyper tree) is clicked. I have researched and tried to include an external php file (generatetweets.php) inside myFunction() at index.php. However it's not working. Anyone can enlighten me or any reference for me to guide?
Thank you in advance.
Extracted example2.js, where child.name refers to the keyword from hyper tree
onComplete: function(){
//Log.write("done");
//Make the relations list shown in the right column.
//ONCLICK FUNCTION FOR KEYWORDS TO LOAD RELATED TWEETS
var node = ht.graph.getClosestNodeToOrigin("current");
var html = "<div><b>Keyword: " + node.name + "</b></div>";
html += "<ul>";
node.eachAdjacency(function(adj){
var child = adj.nodeTo;
var childName=child.name;
html += '<a onClick="myFunction('+'''+child.name+'''+')"><li>'+child.name + '</li></a>';
});
html += "</ul><br />";
$jit.id('inner-details').innerHTML = html;
}
generatetweets.php
<?php
// connect to the database
include "mysqli.connect.php";
// create your SQL statment to retrieve everything from
// the users table
$sql = "SELECT * FROM post WHERE content LIKE '%school%' ORDER BY date DESC";
// run the query
$result = $mysqli->query($sql);
// check for error
if ($mysqli->errno)
{
error_log($mysqli->error);
echo "<br />Something's wrong";
exit();
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<head>
</head>
<body>
<?php
// Check if there are records in the first place
if ($result->num_rows < 1)
{
echo "<h3>No records found</h3>";
}
// Iterate through the records
$counter = 0;
// Use fetch_array to get rows returned one at a time
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
?>
<table>
<tr id="tweetlist">
<td style="width:50px">
<!-- name goes here -->
<!--<img id="img<?=$counter?>" style="padding-right:5px" src="<?=$row["displaypicture"]?>"></img>-->
</td>
<td>
<!-- email textfield goes here -->
<span id="date<?=$counter?>" style="color:#CCFF33">[<?=$row["date"]?>] </span>
<span id="name<?=$counter?>">#<?=$row["username"]?>: </span>
<span id="emailTxt<?=$counter?>"><?=$row["content"]?> <span/>
</td>
</tr>
</table>
<br/>
<?php
$counter++;
}
$result->free();
$mysqli->close();
?>
</body>
Extracted index.php, to display tweets in div "demo"
<body onload="init();">
<!-- Header -->
<div id="header" class="container">
<!-- Logo -->
<h1 id="logo">Mood</h1> <!-- logo from style-n1.css -->
<div id="center-container">
<div id="infovis"></div>
</div>
<div id="right-container">
<div id="inner-details"></div>
<div id="log"></div>
<div id="node_name"></div>
<div id="demo" style="padding-left: 50px">
<script type="text/javascript">
function myFunction() {
$("#demo").load("generatetweets.php");
}
</script>
</div>
</div>
</div>
</body>
Hypertree is referenced from http://philogb.github.io/jit/static/v20/Jit/Examples/Hypertree/example2.html
I obtained tweets using nodejs and append it to div. Here is my code.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
#<input type="text" id="tag" class="hash"/>
<button>submit</button>
</form>
<div id="tweets"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="/socket.io/socket.io.js"> </script>
<script>
var socket = io.connect("link to nodejs");
var link;
var tag;
var a;
function debounce(func, wait, immediate){
var timeout;
return function(){
clearTimeout(timeout);
timeout = setTimeout(function() {
timeout = null;
if (!immediate) func.apply();
}, wait);
if (immediate && !timeout) func.apply();
};
};
var func = debounce(function(){
$('#tweet').html("");
socket.emit('message', $('#tag').val());
tag=$('#tag').val();
link="http://twitter.com/hashtag/"+tag;
a="<a href="+'link'+" target='_blank'> #"+tag+"</a>";
},1000);
$('.hash').keypress(func);
$('.hash').on('change',function(){
$('#tweet').html("");
socket.emit('message', $('#tag').val());
tag=$('#tag').val();
link="http://twitter.com/hashtag/"+tag;
a="<a href="+'link'+" target='_blank'> #"+tag+"</a>";
});
socket.on('message', function(msg){
console.log(msg.length);
$('#tag').val('');
var regex = /(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/ig ;
var hashregex= /(#[a-z0-9][a-z0-9\-_]*)/ig;
console.log(link);
for(var i = 0; i < msg.length; i++){
msg[i].tweettext=msg[i].tweettext.replace(hashregex,a);
msg[i].tweettext=msg[i].tweettext.replace(regex, "<a href='$1' target='_blank'>$1</a>");
$('#tweets').after('<div>UserName: ' + msg[i].username+ '</div>');
$('#tweets').after('<div>Text: ' + msg[i].tweettext+ '</div>');
$('#tweets').after('<div>Time: ' + msg[i].timedate+ '</div>');
$('#tweets').after('<br></br>');
}
});
</script>
</body>
<html>
Related
I followed this tutorial on https://www.webslesson.info/2019/03/php-ajax-live-search-with-multiple-value.html
Everything works well, after hosting on my local computer. Except when I search data not available on my database , I want to get error message " No result found on this table" .
Please check the code.
You can check demo here as well, http://demo.webslesson.info/bootstrap-tags-input-with-php/. "No result found error does not pop up when we search invalid value.
Index.php
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Live Data Search using Multiple Tag in PHP with Ajax</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.css" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput-typeahead.css" />
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.min.js" crossorigin="anonymous"></script>
<style>
.bootstrap-tagsinput {
width: 100%;
}
</style>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<h2 align="center">Live Data Search using Multiple Tag in PHP with Ajax</h2><br />
<div class="form-group">
<div class="row">
<div class="col-md-10">
<input type="text" id="tags" class="form-control" data-role="tagsinput" />
</div>
<div class="col-md-2">
<button type="button" name="search" class="btn btn-primary" id="search">Search</button>
</div>
</div>
</div>
<br />
<div class="table-responsive">
<div align="right">
<p><b>Total Records - <span id="total_records"></span></b></p>
</div>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Customer Name</th>
<th>Gender</th>
<th>Address</th>
<th>City</th>
<th>Postal Code</th>
<th>Country</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<div style="clear:both"></div>
<br />
<br />
<br />
<br />
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
$('#total_records').text(data.length);
var html = '';
if(data.length > 0)
{
for(var count = 0; count < data.length; count++)
{
html += '<tr>';
html += '<td>'+data[count].CustomerName+'</td>';
html += '<td>'+data[count].Gender+'</td>';
html += '<td>'+data[count].Address+'</td>';
html += '<td>'+data[count].City+'</td>';
html += '<td>'+data[count].PostalCode+'</td>';
html += '<td>'+data[count].Country+'</td></tr>';
}
}
else
{
html = '<tr><td colspan="5">No Data Found</td></tr>';
}
$('tbody').html(html);
}
})
}
$('#search').click(function(){
var query = $('#tags').val();
load_data(query);
});
});
</script>
Fetch.php
<?php
//fetch.php
$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
$output = '';
$query = '';
if(isset($_POST["query"]))
{
$search = str_replace(",", "|", $_POST["query"]);
$query = "
SELECT * FROM tbl_customer
WHERE CustomerName REGEXP '".$search."'
OR Address REGEXP '".$search."'
OR City REGEXP '".$search."'
OR PostalCode REGEXP '".$search."'
OR Country REGEXP '".$search."'
";
}
else
{
$query = "
SELECT * FROM tbl_customer ORDER BY CustomerID
";
}
$statement = $connect->prepare($query);
$statement->execute();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$data[] = $row;
}
echo json_encode($data);
?>
as future reference my answer in more than 1 comment line:
In Fetch.php the variable $data will only exist in the case one or more answers are found.
otherwise, the var $data is still not present at the last line: json_encode($data);
Would you have your error_reporting on, it would give you a message about "undefined var data on line X".
PHP will forgive you, and suppose $data has value NULL; So you get a json_encoded form or NULL.
So if you put in the top of your Fetch.php it will always exist and be an empty or a filled array.
This will avoid your error in Javascript where you cannot read the length of NULL.
An empty array however has length = 0.
Making a ajax, so when i click on this Link1 Button, i need to empty the contents in the products_list div
<button type="w3-button">Link1</button>
Please help me on how to make a ajax call when clicking link1 button it empty the products in product_list
The below code contains a javascript to clear the contents of products_list but it do not work
PHP File
<?php
session_start(); //start session
include("config.inc.php"); //include config file
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Stores</title>
<link href="style/style1.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
</head>
<body>
<div align="center">
<h3>Products</h3>
</div>
<script>
$(document).on("click", ".w3-button", function() {
$('.products-wrp').html('')
// $("#products_list").html();
});</script>
<?php
//List products from database
$results = $mysqli_conn->query("SELECT product_name, product_desc, product_code, product_image, product_price FROM products_list");
//Display fetched records as you please
$products_list = '<ul id ="products_list" class="products-wrp">';
while($row = $results->fetch_assoc()) {
$products_list .= <<<EOT
<li>
<form class="form-item">
<h4>{$row["product_name"]}</h4>
<div>
<img src="images/{$row["product_image"]}" height="62" width="62">
</div>
<div>Price : {$currency} {$row["product_price"]}<div>
</form>
</li>
EOT;
}
$products_list .= '</ul></div>';
echo $products_list;
?>
</body>
</html>
Check Code below that will empty the div On Failure on Ajax Request -
function getFailOutput() {
$.ajax({
url:'myAjax.php',
success: function (response) {
console.log(data, response);
$('#output').html(response);
},
error: function () {
//Empty Output Div ON Error Returned From Ajax Request
$('#output').html('');
},
});
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
test success | test failure
<div id="output">waiting for action</div>
I have a jQuery ajax that doesn't work ONLY when there's another jQuery function using javascript's replace function. why is this happening?
note:
this only happens when running on Internet Explorer. It's working fine on Firefox
I'm very new to jQuery (have only been learning jQuery for 2 days). so please be gentle with me :)
this is the html file:
<?php
session_start();
include('koneksi.php');
include('function.php');
unset($_SESSION['cust']);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<script src="jquery-1.12.1.js"></script>
<script src="script.js"></script>
<title>CSS MenuMaker</title>
</head>
<body>
<table class="width100 padding5 border_black" id="tabel_input_master" name="tabel_input_master">
<tr class="my_form">
<td colspan="2">
<div>
<div style="float:left; width:60px">Telepon</div>
<input
type="text"
id="cust_telp"
name="cust_telp"
style="width:200px;"
/>
</div>
<div id="cust_detail" name="cust_detail">
<div style="float:left; width:60px">Name</div>
<input
type="text"
id="cust_name"
name="cust_name"
style="width:200px;"
/>
</div>
</td>
</tr>
</table>
this is the content of script.js:
$(document).ready(function(){
$("#cust_telp").on("change",function(){
var myurl = "show_cust.php?q=" + $(this).val();
var request = $.ajax({
url: myurl,
type: "GET"
});
request.done(function(result){
var cust = JSON.parse(result);
if (cust[0].nama == '') {
$("#cust_name").val('');
$("#cust_name").prop('readonly',false);
}else{
$("#cust_name").val(cust[0].name);
$("#cust_name").prop('readonly', true);
}
});
});
// when I put this script here, the ajax call on [change] event stopped working
$("#cust_telp").on("keyup",function(){
var temp = $(this).val();
temp = temp.replace(/\D/g,'');
$("#cust_telp").val(temp);
});
});
but when I replace the keyup script with this one below, the ajax call works normally again
$("#cust_telp").on("keyup",function(){
var temp = $(this).val();
alert(temp);
});
here's the show_cust.php file
<?php
session_start();
include('koneksi.php');
include('function.php');
$q = (isset($_GET['q'])) ? $_GET['q'] : '';
$outp = '';
unset($cust);
$cust = array();
if ($q != '') {
$sql = "select * from customer where telp1 = '".$q."' or telp2 = '".$q."'";
$query = mysqli_query($link, $sql);
$cust = mysqli_fetch_array($query);
unset($_SESSION['cust']);
$_SESSION['cust'] = $cust;
$outp = "[";
$outp .= '{"name":"' . $cust["name"] . '",';
$outp .= '"address":"' . $cust["address"] . '"}';
$outp .= "]";
}
echo $outp;
?>
A better solution will be to prevent the default nature of keys to prevent the unwanted keys like
$(document).ready(function() {
$("#cust_telp").on("change", function() {
snippet.log('changed: ' + this.value)
});
// when I put this script here, the ajax call on [change] event stopped working
$("#cust_telp").on("keypress", function(e) {
return e.which >= 48 && e.which <= 57;
});
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="width100 padding5 border_black" id="tabel_input_master" name="tabel_input_master">
<tr class="my_form">
<td colspan="2">
<div>
<div style="float:left; width:60px">Telepon</div>
<input type="text" id="cust_telp" name="cust_telp" style="width:200px;" />
</div>
<div id="cust_detail" name="cust_detail">
<div style="float:left; width:60px">Name</div>
<input type="text" id="cust_name" name="cust_name" style="width:200px;" />
</div>
</td>
</tr>
</table>
<?php
include ("dbFunctions.php");
$query = "SELECT * FROM two_three";
$result = mysqli_query($link, $query);
mysqli_close($link);
?>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" href="CSS/main.css" type="text/css"/>
<link rel="stylesheet" href="CSS/easy.css" type="text/css"/>
<title> Easy Game 1 </title>
<center>
<h1> Easy Game 1 </h1>
<h2> Click the image the number of times to get the answer! </h2>
<div class="border_solid">
<div id="timer"></div>
</div>
<hr>
</center>
</head>
<body>
<center>
<form method="post" id="validate">
<div id="display"><script type="text/javascript">document.write(count);</script></div>
<img src="image/ufo.png" class="ufo" onclick="add()"><br>
<input type="button" class="submit" value="submit" name="submit"/>
</form>
</center>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$questID = $row['two_three_id'];
$factor1 = $row['factor1'];
$factor2 = $row['factor2'];
$answer = $row['answer'];
?>
<div class="image-questionid"><u>Question <?php echo $questID; ?></u></div>
<div class="image-questionfactor1"><?php echo $factor1; ?></div>
<div class="image-betweenfactor">X</div>
<div class="image-questionfactor2"><?php echo $factor2; ?></div>
<div class="image-questionequals">= ?</div>
<?php
break;
}
}
?>
</body>
<script type="text/javascript">
var count = 0;
function add() {
count++;
document.getElementById('display').innerHTML = count;
}
var myVar = setInterval(function () {
myTimer()
}, 1000);
var d = 0;
function myTimer() {
document.getElementById("timer").innerHTML = d++;
}
</script>
</html>
So basically this is the code I've done so far, I'd like to do a validation to check the count after the user clicks on submit, and check the count with the database answer. Is there anyone out there who can help me out?
in the form use the method in tag form onsubmit ="validation". after you need to implement the validation method in javascript and make a ajax request (in validation) to another php form, in that php form u make the query to db and returning the number of click you need to do. o you need to implement jquery library.
function validation(){
$.ajax({
url: "your_php_requesting_to_db.php",
success: function(data){
if(data == numberofclicks){
return true;
}else{
return false;
}
}
});
}
Here is the new code, im new in this foro so i don't know how to put in a comment the code, im assumng you got the total clicks you need to do, answering your question of timmer here is a little bit of doc
http://www.w3schools.com/js/js_timing.asp
<?php
include ("dbFunctions.php");
$query = "SELECT * FROM two_three";
$result = mysqli_query($link, $query);
mysqli_close($link);
?>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" href="CSS/main.css" type="text/css"/>
<link rel="stylesheet" href="CSS/easy.css" type="text/css"/>
<title> Easy Game 1 </title>
<center>
<h1> Easy Game 1 </h1>
<h2> Click the image the number of times to get the answer! </h2>
<div class="border_solid">
<div id="timer"></div>
</div>
<hr>
</center>
</head>
<body>
<center>
<form method="post" id="validate" onsubmit="validate()">
<div id="display">
<script type="text/javascript">document.write(count);</script>
</div>
<img src="image/ufo.png" class="ufo" onclick="add()"><br>
<input type="hidden" id="totalClicks" value="<?php /*IF U GOT THE NUMBER OF CLIC FROM BD PUT IN THERE LIKE ECHO $NUMCLICKS */ ?>"/>
<input type="hidden" id="countClic" value="0" />
<input type="button" class="submit" value="submit" name="submit"/>
</form>
</center>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$questID = $row['two_three_id'];
$factor1 = $row['factor1'];
$factor2 = $row['factor2'];
$answer = $row['answer'];
?>
<div class="image-questionid"><u>Question <?php echo $questID; ?></u></div>
<div class="image-questionfactor1"><?php echo $factor1; ?></div>
<div class="image-betweenfactor">X</div>
<div class="image-questionfactor2"><?php echo $factor2; ?></div>
<div class="image-questionequals">= ?</div>
<?php
break;
}
}
?>
</body>
<script type="text/javascript">
var count = 0;
function add() {
count++;
document.getElementById('display').innerHTML = count;
document.getElementById('countClic').value=count;
}
var myVar = setInterval(function () {
myTimer()
}, 1000);
var d = 0;
function myTimer() {
document.getElementById("timer").innerHTML = d++;
}
function validate(){
var totalClics = document.getElementById('totalClicks').value=count;
var clicksCount = document.getElementById('countClic').value=count;
if(totalClics == clicksCount){
return true;
}else{
return false;
}
}
</script>
</html>
I have an Autocomplete that works perfectly but I'm having trouble figuring out how to re-direct the user to a separate web page containing info about his selection upon pressing ENTER on keyboard. The website itself doesn't have to exist, I just want to know the code for it assuming the website already exists.
index.php:
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Autocomplete using PHP/MySQL and jQuery</title>
<link rel="stylesheet" href="css/style.css" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<div class="container">
<div class="header">
</div><!-- header -->
<h1 class="main_title">Autocomplete using PHP/MySQL and jQuery</h1>
<div class="content">
<form>
<p>Table consists of : ID, Location, Slug, Population </p>
<br><br>
<div class="label_div">Search for a Slug : </div>
<div class="input_container">
<input type="text" id="slug" onkeyup="autocomplet2()">
<ul id="list_id"></ul>
</div>
</form>
<br><br><br><br>
<p>List will be ordered from Highest population to lowest population (Top to bottom)</p>
<br><br>
</div><!-- content -->
<div class="footer">
Powered by Jason's Fingers</a>
</div><!-- footer -->
</div><!-- container -->
</body>
</html>
script.js:
// autocomplete : this function will be executed every time we change the text
function autocomplet2() {
var min_length = 3; // min caracters to display the autocomplete
var keyword = $('#slug').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#list_id').show();
$('#list_id').html(data);
}
});
} else {
$('#list_id').hide();
}
}
// set_item : this function will be executed when we select an item
function set_item(item) {
// Changes input to the full name on selecting
$('#slug').val(item);
// Hides list after selection from list
$('#list_id').hide();
}
function change()
ajax_refresh.php:
<?php
// PDO connect *********
function connect() {
return new PDO('mysql:host=localhost;dbname=wallettest', 'root', 'butthead', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
$pdo = connect();
$keyword = '%'.$_POST['keyword'].'%';
$sql = "SELECT * FROM population WHERE slug LIKE (:keyword) ORDER BY population DESC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
// put in bold the written text
$slug = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['slug']);
// add new option
echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['slug']).'\')">'.$slug.'</li>';
}
?>
Listen for the keydown event, and check if the key pressed was the enter key, by checking the keycode.
input.on('keydown', function (ev) {
if (ev.keyCode === 13) { //enter's keycode is 13
//redirect code
}
});
You might also have to do ev.preventDefault() if the enter key would normally do something unwanted.