I'm trying to get the autocomplete to be linked to another page on the server. here as follows:
<?php
if($_POST)
{
$q=$_POST['searchword'];
$q=addslashes($q);
if(strlen($q) >0) {
$sql_res=mysql_query("select `id`, `firstName`, `lastName`, `email`, `photo`, `phone` from contacts where user_id = '$_SESSION[user_id]' AND lower(concat_ws(' ', firstname, lastname)) like '%$q%' order by id LIMIT 5");
while($row=mysql_fetch_array($sql_res))
{
$id = $row['id'];
$firstName=$row['firstName'];
$lastName=$row['lastName'];
$photo=$row['photo'];
$phone=$row['phone'];
$email = $row['email'];
$b_firstName='<b>'.$q.'</b>';
$b_lastName='<b>'.$q.'</b>';
$final_firstName = str_ireplace($q, $b_firstName, $firstName);
$final_lastName = str_ireplace($q, $b_lastName, $lastName);
$img_src = base64_decode($photo);
$imgbinary = fread(fopen($img_src, "r"), filesize($img_src));
$img_str = base64_encode($imgbinary);
?>
<div class="display_box" align="left">
<img src=<?php echo "'data:image/jpg;base64,$img_str'";?> style="width:58px; height:48px; float:left; margin-right:6px;" />
<span class="name"><?php echo $final_firstName; ?></span> <?php echo $final_lastName; ?>
<br/>
<span style="font-size:9px; color:#999999"><?php echo $phone; ?></span>
<span style="font-size:9px; color:#999999"><br/><?php echo $email; ?></span>
</div>
<?php
}
}
}
?>
that's the search.php.
Now on the main page I have this in the header:
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function(){
$(".search-text").keyup(function()
{
var inputSearch = $(this).val();
var dataString = 'searchword='+ inputSearch;
if(inputSearch!='')
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#divResult").html(html).show();
}
});
}return false;
});
jQuery("#divResult").click(function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("put tag close div tag here").html($name).text();
$('#inputSearch').val(decoded);
});
jQuery(document).click( function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#divResult").fadeOut();
}
});
});
</script>
<style type="text/css">
.contentArea{
width:600px;
margin:0 auto;
}
#inputSearch
{
width:250px;
border:solid 1px #000;
padding:3px;
}
#divResult
{
position:absolute;
width:255px;
display:none;
margin-top:-1px;
border:solid 2px #dedede;
border-top:0px;
overflow:hidden;
border-bottom-right-radius: 6px;
border-bottom-left-radius: 6px;
-moz-border-bottom-right-radius: 6px;
-moz-border-bottom-left-radius: 6px;
box-shadow: 0px 0px 5px #999;
border-style: solid;
border-color: #333 #000000 #000000;
background-color: white;
}
.display_box
{
padding:4px; border-top:solid 1px #dedede;
font-size:12px; height:50px; line-height: 1.5;
}
.display_box:hover
{
background:#3399ff;
color:#FFFFFF;
cursor:pointer;
}
</style>
and this is the search bar:
<input class="search-text" id="inputSearch" name="search" type="text" placeholder="Search " value="" /><div id="divResult">
</div>
So basically what i'm trying to do is when a user searches and the auto complete comes up, they can click on the image/suggestion and it takes them to the page associated with that image.
Also if they click enter, the search will pick the first autocoplete and direct them to that page.
I'm new to javascript/jquery
First of all, you need to return unique data belongs to specific user in your ajax response.
For example, you can use user id. Your autocomplete item will be like;
<div class="display_box" align="left" id="<?php echo $id; ?>">
<img src=<?php echo "'data:image/jpg;base64,$img_str'";?> style="width:58px; height:48px; float:left; margin-right:6px;" />
<span class="name"><?php echo $final_firstName; ?></span> <?php echo $final_lastName; ?><br/>
<span style="font-size:9px; color:#999999"><?php echo $phone; ?></span>
<span style="font-size:9px; color:#999999"><br/><?php echo $email; ?></span>
</div>
When you clicked specific item, it will redirect related page. In your JS;
$(".display_box").on("click", function() {
var userId = $(this).attr("id");
window.location = "/user/" + userId;
});
Related
I have a form which i want to post problem is this when ever page refresh form submit auto I just want form only form submit when I click on the button.otherwise form not post thanks in advance
<?php
session_start();
//mail("ifaisal24#gmail.com","hhhhhh",print_r($_REQUEST,TRUE));
define('HOST','xxxxx');
define('USER','xxxxx');
define('PASS','Ixxxxx_');
define('DB','xxxx');
$con = mysqli_connect(HOST,USER,PASS,DB);
require_once 'include/DB_Functions.php';
if (!isset($_SESSION['email'])){
?>
<script>
window.location = 'login2.php';
</script>
<?php
}
$db = new DB_Functions();
$response = array("error" => FALSE);
if (isset($_POST['sender_email'])&& isset($_POST['reciver_email'])&& isset($_POST['data'])) {
// receiving the post params
$sender_email = $_SESSION['email'];
$_POST['sender_email']=$_SESSION['email'];
$reciver_email = $_POST['reciver_email'];
$data =$sender_email.' : '. $_POST['data'];
///echo $sender_email;
//die();
// create a new chat
$user_data = $db->storeData($data,$sender_email,$reciver_email);
//die;
if ($user_data) {
// chat stored successfully
$response["error"] = FALSE;
// $response["uid"] = $user_data["unique_id"];
$response["user_data"]["sender_email"] = $user_data["sender_email"];
$response["user_data"]["reciver_email"] = $user_data["reciver_email"];
$response["user_data"]["data"] = $user_data["data"];
$response["user_data"]["created_at"] = $user_data["created_at"];
echo json_encode($response);
}
}
// if (isset($_REQUEST['sender_email'])&& isset($_REQUEST['reciver_email'])&& isset($_REQUEST['fatch_server_data'])) {
// $sender_email = $_REQUEST['sender_email'];
// $reciver_email = $_REQUEST['reciver_email'];
$sql = "select * from user_data WHERE (sender_email='$sender_email' AND reciver_email='$reciver_email') OR
(reciver_email ='$sender_email' AND sender_email='$reciver_email')" ;
//$sql = "select * from user_data";
$res = mysqli_query($con,$sql)or mysql_error();
$resultt = array();
while($row = mysqli_fetch_array($res)){
array_push($resultt,
array(
'data'=>$row[3],
'created_at'=>$row[4]
// 'email'=>$row[3]
));
}
// }
json_encode(array("resultt"=>$resultt));
mysqli_close($con);
?>
<?php
define('HOST','mxxxxx');
define('USER','axxxxxxx');
define('PASS','Ixxxxxxx_');
define('DB','axxxxxxxx');
$con = mysqli_connect(HOST,USER,PASS,DB);
$sql = "select * from users";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array(
// 'id'=>$row[0],
'email'=>$row[3],
));
}
json_encode(array("result"=>$result));
mysqli_close($con);
?>
<html>
<head>
<style>
#userschat {
font-family:tahoma;
font-size:12px;
color:black;
border: 5px teal solid;
height: 325px;
width: 300px;
overflow-y:scroll;
}
#usersOnLine {
font-family:tahoma;
font-size:12px;
color:black;
border: 10px teal solid;
height: 625px;
width: 300px;
overflow-y:scroll;
}
#allcon{
margin-bottom: 15px;
font-family:tahoma;
font-size:12px;
color:black;
border: 10px teal solid;
height: 40px;
width: 300px;
}
#contact{
float:right;
}
#all{
float:left;
}
#data {
width: 250px;
height: 30px;
border: 5px teal solid;
float:left;
margin-top:1px;
}
#send {
border: 5px teal solid;
width: 57px;
height: 30px;
float:right;
margin:1px;
}
.container{
width:970px;
height:auto;
margin:0 auto;
}
#messageForm{
}
.clickAble{
display: inline-block;;
cursor:pointer;
}
</style>
<meta http-equiv="refresh" content="600">
</head>
<body bgcolor="beige">>
<div class="container">
<form method="post" action="login2.php">
<input type="submit" id="l_btn" name="l_btn" value="Logout" />
</form>
<?php
if ($_POST) {
// here is where your code would be included
session_destroy();
header("Location:chat.php" . $_SERVER['REQUEST_URI']);
exit();
}
?>
<div id = "welcome"><h2>Welcome to Chat</h2>
<?php echo $_SESSION['email']; ?>
</div>
<div id = "all">
<h1> Chat Box</h1>
<div id="receiver">
<h3>receiver</h3>
<!-- NOTICE THAT THIS IS NEW NOW... -->
<!-- IT'S IMPORTANT THAT YOU HAVE THIS PARAGRAPH EXACTLY AS IT IS HERE -->
<p class='bubbled-data'></p>
</div>
<div id="sender"><h3>sender</h3>
<?php echo $_SESSION['email']; ?>
</div>
<div id="userschat">
<h4 style = " margin-top: 4px; margin-left: 7px">
<?php
foreach($resultt as $key => $val)
{
echo $val['data'];
echo "<br>";
echo $val['created_at'];
echo "<br>";
echo "<br>";
}
?>
</h4>
</div>
<form id="messageForm" action = "<?php $_PHP_SELF ?>" method = "POST">
<input type="hidden" name="sender_email" id="sender_email" value="">
<input type="hidden" name="reciver_email" id="reciver_email" value="">
<input type="text" name="data" id="data" placeholder="data" onFocus="fun1(this)" onBlur="fun2(this)" required="" />
<input id="send" type="submit" value="Send">
</form>
</div>
<div id = "contact">
<div id = "allcon">
<h1 style = " text-align: center; margin-top: 4px;"> All Contacts </h1>
</div>
<div id="usersOnLine" >
<h2 style = " margin-top: 4px; margin-left: 7px">
<?php
foreach($result as $key => $val){
echo "<span class='clickAble'>" . $val['email'] . "</span>";
echo "<br>";
echo "<br>";
}
?>
</h2>
</div>
</div>
</div>
<!-- JAVASCRIPT - JQUERY -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
var objDiv = document.getElementById("userschat");
objDiv.scrollTop = objDiv.scrollHeight;
(function ($) {
$(document).ready(function (e) {
var receiver = $("#receiver");
var clickAbles = $(".clickAble");
receiver.find(".bubbled-data").text(localStorage.getItem("nameValue"));
$("#reciver_email").val(localStorage.getItem("nameValue"));
// BIND THE clickAble SPAN TO AN ON-CLICK EVENT...
// SO THAT WITH EACH CLICK, YOU CAN SIMPLE APPEND THE CONTENT OF THAT SPAN TO THE RECEIVER DIV
clickAbles.on("click", function (evt) {
var nameValue = $(this).text();
receiver.find(".bubbled-data").text(nameValue);
$("#reciver_email").val(nameValue);
localStorage.setItem("nameValue", nameValue);
});
});
})(jQuery);
</script>
</body>
</html>
here is the full code.i edit it
A Post/Redirect/Get design would be a viable solution to your problem. An example of code that would accomplish this is:
if ($_POST) {
// here is where your code would be included
header("Location: " . $_SERVER['REQUEST_URI']);
exit();
}
The header function then redirects the user to the same page, which means that the $_POST information is lost, hence refreshing the page would not re-send the form.
UPDATE:
Using #kyeiti's solution, I managed to get the other info where I need it, but I'm unable to navigate; I can go back and forward on the left side, but I can't get the right side to update. Also, if this could be accomplished with a single external PHP file it would be great. To make things clear, I put the whole thing online, you can check it out here. Also, I updated the code sections to reflect the latest changes.
UPDATE 2:
After some more help from #kyeiti, I'm trying to get it working with only 1 external PHP. The JS code is exactly as per #kyeiti's updated answer, while my art.php (now the only external file) looks like below. When I open index.php, I get nothing related to the two divs in the code. I also tried inserting them into the index file itself, but obviously that didn't work either...
Current art.php:
<?php
$username = "root"; //mysql username
$password = ""; //mysql password
$hostname = "localhost"; //hostname
$databasename = '2199'; //databasename
//get pic id from ajax request
if(isset($_POST["pic"]) && is_numeric($_POST["pic"]))
{
$current_picture = filter_var($_POST["pic"], FILTER_SANITIZE_NUMBER_INT);
}else{
$current_picture=1;
}
//Connect to Database
$mysqli = new mysqli($hostname, $username, $password, $databasename);
if ($mysqli->connect_error){
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//get next picture id
$result = $mysqli->query("SELECT id FROM gola WHERE id > $current_picture ORDER BY id ASC LIMIT 1")->fetch_object();
if($result){
$next_id = $result->id;
}
//get previous picture id
$result = $mysqli->query("SELECT id FROM gola WHERE id < $current_picture ORDER BY id DESC LIMIT 1")->fetch_object();
if($result){
$prev_id = $result->id;
}
//get details of current from database
$result = $mysqli->query("SELECT artikel, slika1 FROM gola WHERE id = $current_picture LIMIT 1")->fetch_object();
if($result){
//construct next/previous button
$prev_button = (isset($prev_id) && $prev_id>0)?'<span class="glyphicon glyphicon-circle-arrow-left rujz"></span>':'';
$next_button = (isset($next_id) && $next_id>0)?'<span class="glyphicon glyphicon-circle-arrow-right rujz"></span>':'';
//output html
echo "<div id='loaded_picture'>";
echo "test"; // Put everything that goes into the picture div here
echo "</div>";
echo "<div id='loaded_text'>";
echo "test"; // And everything that goes into the text div here
echo "</div>";
}
Original post:
I have two main divs in my page, the left side displays a photo and the right side should display some info about a specific product.
I get all the data out of MySQL and managed to hack together a working solution to navigate. I can go forward and backward using next/prev buttons and the image changes.
Now for some code:
HTML (index.php):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="layout.css">
<link href='https://fonts.googleapis.com/css?family=Syncopate' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.post( "art.php", { pic: "1"}, function( data ) {
$("#picture").html( data );
});
$.post( "info.php", { id: "1"}, function( data ) {
$("#info").html( data );
});
$("#picture").on("click",".get_pic", function(e){
var picture_id = $(this).attr('data-id');
$("#picture").html("<div style=\"margin:50px auto;width:50px;\"><img src=\"loader.gif\" /></div>");
$.post( "art.php", { pic: picture_id}, function( data ) {
$("#picture").html( data );
});
return false;
});
$("#info").on("click",".get_info", function(e){
var info_id = $(this).attr('data-id');
$("#info").html("<div style=\"margin:50px auto;width:50px;\"><img src=\"loader.gif\" /></div>");
$.post( "info.php", { pic: info_id}, function( data ) {
$("#info").html( data );
});
return false;
});
});
</script>
<title>2199</title>
</head>
<body>
<div class="navbar-wrapper">
<div class="container"> <img src="logo.png" class="boxy"> </div>
</div>
<div class="jumbotron special">
<div id="picture" align="center"> </div>
</div>
<div class="jumbotron special2">
<div id="info" align="center"> </div>
</div>
</body>
</html>
HTML (art.php):
$username = "root"; //mysql username
$password = ""; //mysql password
$hostname = "localhost"; //hostname
$databasename = '2199'; //databasename
//get pic id from ajax request
if(isset($_POST["pic"]) && is_numeric($_POST["pic"]))
{
$current_picture = filter_var($_POST["pic"], FILTER_SANITIZE_NUMBER_INT);
}else{
$current_picture=1;
}
//Connect to Database
$mysqli = new mysqli($hostname, $username, $password, $databasename);
if ($mysqli->connect_error){
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//get next picture id
$result = $mysqli->query("SELECT id FROM gola WHERE id > $current_picture ORDER BY id ASC LIMIT 1")->fetch_object();
if($result){
$next_id = $result->id;
}
//get previous picture id
$result = $mysqli->query("SELECT id FROM gola WHERE id < $current_picture ORDER BY id DESC LIMIT 1")->fetch_object();
if($result){
$prev_id = $result->id;
}
//get details of current from database
$result = $mysqli->query("SELECT artikel, slika1 FROM gola WHERE id = $current_picture LIMIT 1")->fetch_object();
if($result){
//construct next/previous button
$prev_button = (isset($prev_id) && $prev_id>0)?'<span class="glyphicon glyphicon-circle-arrow-left rujz"></span>':'';
$next_button = (isset($next_id) && $next_id>0)?'<span class="glyphicon glyphicon-circle-arrow-right rujz"></span>':'';
//output html
echo '<div class="prod_img" style="background-image: url(pictures/';
echo $result->slika1;
echo '); background-size: contain; background-repeat: no-repeat; background-position: center center;">';
echo '<h3>';
echo $prev_button;
echo $result->artikel;
echo $next_button;
echo '</h3>';
echo '</div>';
}
HTML (info.php):
<?php
$username = "root"; //mysql username
$password = ""; //mysql password
$hostname = "localhost"; //hostname
$databasename = '2199'; //databasename
//get pic id from ajax request
if(isset($_POST["info"]) && is_numeric($_POST["info"]))
{
$current_info = filter_var($_POST["info"], FILTER_SANITIZE_NUMBER_INT);
}else{
$current_info=1;
}
//Connect to Database
$mysqli = new mysqli($hostname, $username, $password, $databasename);
if ($mysqli->connect_error){
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//get next picture id
$result2 = $mysqli->query("SELECT id FROM gola WHERE id > $current_info ORDER BY id ASC LIMIT 1")->fetch_object();
if($result2){
$next_id = $result2->id;
}
//get previous picture id
$result2 = $mysqli->query("SELECT id FROM gola WHERE id < $current_info ORDER BY id DESC LIMIT 1")->fetch_object();
if($result2){
$prev_id = $result2->id;
}
//get details of current from database
$result2 = $mysqli->query("SELECT artikel, slika1, slika2, slika3, dim1, dim2, dim3, obdelava, dodatno FROM gola WHERE id = $current_info LIMIT 1")->fetch_object();
if($result2){
//construct next/previous button
$prev_button = (isset($prev_id) && $prev_id>0)?'<span class="glyphicon glyphicon-circle-arrow-left rujz-wht"></span>':'';
$next_button = (isset($next_id) && $next_id>0)?'<span class="glyphicon glyphicon-circle-arrow-right rujz-wht"></span>':'';
//output html
echo '<div class="info">';
echo '<h3 style="color: #fff !important;">';
echo $prev_button;
echo $result2->artikel;
echo $next_button;
echo '</h3>';
echo '<br />';
echo '<p>';
echo $result2->slika1;
echo '<br />';
echo $result2->slika2;
echo '<br />';
echo $result2->slika3;
echo '<br />';
echo $result2->dim1;
echo '<br />';
echo $result2->dim2;
echo '<br />';
echo $result2->dim3;
echo '<br />';
echo $result2->obdelava;
echo '<br />';
echo $result2->dodatno;
echo '</p>';
echo '</div>';
}
CSS (shall you need it):
html, body {
height: 100%;
background-color: #fff;
font-size: 62.5%;
}
.special, .special .jumbotron {
height: 100%;
background-color: white;
border: 0px solid red;
margin-bottom: 0px !important;
}
.special2, .special2 .jumbotron {
height: 100%;
background-color: #62a70f;
border: 0.5rem solid #fff;
border-radius: 3rem;
margin-bottom: 0px !important;
padding: 1rem;
}
.logo {
border: 1px solid red;
width: 10%;
min-height: 100%;
position: relative;
height: 100%;
}
#picture {
border: 0px red solid;
height: 100%;
background: #fff;
}
.prod_img {
height: 100%;
}
h3 {
font-family: 'Syncopate', sans-serif;
font-size: 24px;
font-size: 2.4rem;
color: #62a70f;
}
.boxy {
border: 0.5rem solid white;
position: fixed;
bottom: 2.5%;
right: 5%;
width: 25%;
padding: 1rem;
/* height: 30rem;*/
background-color: rgba(64,64,64,1);
border-radius: 3rem;/* background-image: url(logo.png);
background-size: contain;
background-repeat: no-repeat;*/
}
#media (min-width:768px) {
.boxy {
border: 0.5rem solid white;
position: fixed;
bottom: 5%;
right: 45%;
width: 10%;
/* height: 30rem;*/
background-color: rgba(64,64,64,1);
border-radius: 3rem;/* background-image: url(logo.png);
background-size: contain;
background-repeat: no-repeat;*/
}
.navbar {
min-height: 10% !important;
max-height: 10% !important;
height: 10%;
background-image: url(logo.png);
background-size: contain;
background-repeat: no-repeat;
border: 0px solid green;
background-color: #0e0e0e;
animation-name: example;
animation-duration: 1s;
animation-timing-function: ease;
}
.navbar-header {
border: 0px solid green;
min-height: 100%;
}
.logo {
visibility: collapse;
}
.special, .special .jumbotron {
width: 50%;
float: left;
margin-bottom: 0px !important;
}
.special2, .special2 .jumbotron {
width: 50%;
float: left;
margin-bottom: 0px !important;
}
h3 {
font-size: 48px;
font-size: 4.8rem;
}
.rujz {
font-size: 36px;
font-size: 3.6rem;
color: #62a70f;
margin: 0.5em;
}
.rujz-wht {
font-size: 36px;
font-size: 3.6rem;
color: #fff;
margin: 0.5em;
}
}
#keyframes example {
0% {
bottom:-10%;
}
100% {
bottom:0%;
}
}
Now, my question is the following:
The image and product name display correctly inside <div id="picture" align="center"> </div>
What I want to accomplish is get other data from the database and display it in the other half of the screen. Since it all happens inside art.php, it's not as easy as typing echo $results->columnName, so I'd need a bit of help.
Thanks in advance :)
You could create an other file like art.php to display the data you need and add an other post to that file to your onclick-event.
This is how I would edited the javascript from index.php:
$(document).ready(function() {
$.post( "art.php", { pic: "1"}, function( data ) {
$("#picture").html( data );
});
$.post( "text.php", { id: "1"}, function( data ) {
$("#text").html( data );
});
$("#picture").on("click",".get_pic", function(e){
var picture_id = $(this).attr('data-id');
$("#picture").html("<div style=\"margin:50px auto;width:50px;\"><img src=\"loader.gif\" /></div>");
$.post( "art.php", { pic: picture_id}, function( data ) {
$("#picture").html( data );
});
$.post( "text.php", { id: picture_id}, function( data ) {
$("#text").html( data );
});
return false;
});
});
I can't really say much about text.php, since I don't know what information you want to display (or how you want to display it).
Edit: If you want only one post and only one external file you could use jQuerys .find-Function to extract portions from the ajax-data.
Javascript:
$(document).ready(function() {
$.post( "art.php", { pic: "1"}, function( data ) {
$("#picture").html( $(data).find("#loaded_picture") );
$("#text").html( $(data).find("#loaded_text") );
});
$("#picture").on("click",".get_pic", function(e){
var picture_id = $(this).attr('data-id');
$("#picture").html("<div style=\"margin:50px auto;width:50px;\"><img src=\"loader.gif\" /></div>");
$.post( "art.php", { pic: picture_id}, function( data ) {
$("#picture").html( $(data).find("#loaded_picture") );
$("#text").html( $(data).find("#loaded_text") );
});
return false;
});
});
And in the art.php:
//get pic id from ajax request
if(isset($_POST["pic"]) && is_numeric($_POST["pic"])) {
$current_picture = filter_var($_POST["pic"], FILTER_SANITIZE_NUMBER_INT);
} else {
$current_picture=1;
}
/* Put connect to database and other preparations here */
echo "<div>";
echo "<div id='loaded_picture'>";
// Put everything that goes into the picture div here
echo "</div>"
echo "<div id='loaded_text'>";
// And everything that goes into the text div here
echo "</div>";
echo "</div>";
By looking at your index.php i think you are having trouble updating your
$result->artikel
in the table section when you call another image in. If this is the case then you can do this wrap your $result->artikel in art.php file with a div like <div class="artikel">$result->artikel</div> and echo it. Now you can do this to update your table section with the new data.
$("#picture").on("click",".get_pic", function(e){
var picture_id = $(this).attr('data-id');
$("#picture").html("<div style=\"margin:50px auto;width:50px;\"><img src=\"loader.gif\" /></div>");
$.post( "art.php", { pic: picture_id}, function( data ) {
$("#picture").html( data );
//you should give class name to p that's easy after to work
$("table thead th:nth-child(2) p").html($(".artikel").html());
});
return false;
});
This will update your table section also
I have created a chat application using PHP, mysql, and ajax for posting data to the server. I have tested it by spamming the chat repeatedly, and everything works for about 7 or 8 seconds until my chat will not post further. On refresh, I get a "NO DATA RECEIVED" error from google chrome. Basically I think I am overloading my site. Is there a way that I could optimize this chat? Or is it not a server-side issue at all?
This is my jQuery that is posting to my server:
$(document).ready(getMessage());
//Send message
$('#send').click(function() {
var message = $('#message').val();
var username = $('#un').val();
var id = $('#id').val();
var fullname = $('#name').val();
$.ajax({
url: 'chat/send_message.php',
type: 'POST',
data: {
message: message,
username: username,
user_id: id,
fullname: fullname
},
success: function() {
$('#message').val('');
getMessage();
}
});
return false;
});
function getMessage() {
$.post('chat/get_message.php', {getMessage: true}, function(message) {
$('#chatbox').html(message);
$('#chatbox').scrollTop($('#chatbox')[0].scrollHeight);
});
}
setInterval(getMessage, 5000);
This is the PHP that handles the sending of the message. It just stores it in a database:
<?php
//Message sending
if(isset($_POST['message'])) {
try {
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
} catch (PDOException $e) {
echo("Could not connect to the server.");
}
$message = $_POST['message'];
$timesent = date('Y-m-d H:i:s');
$id = $_POST['user_id'];
$fullname = $_POST['fullname'];
$username = $_POST['username'];
$query = $pdo->prepare("INSERT INTO `message`(`message`,`user_id`,`timesent`,`fullname`,`username`) VALUES (:message,:user_id,:timesent,:fullname,:username)");
$query->execute(array(
':message' => $message,
':user_id' => $id,
':timesent' => $timesent,
':fullname' => $fullname,
':username' => $username,
));
} else {
echo("Could not send message");
}
This is my HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><head>
<?php
include 'resources/head.php';
if(!$user->isLoggedIn()) {
Redirect::to('index.php');
}
?>
<title>GoonSquad | Chat</title>
<style type="text/css">
form, p, span {
margin:0;
padding:0; }
input { font:12px arial; }
a {
color:#0000FF;
text-decoration:none; }
a:hover { text-decoration:underline; }
#wrapper {
margin:0 auto;
padding-bottom:0;
background: rgba(0, 0, 0, 0.13);
width: 1000px;;
border:1px solid #ACD8F0;
text-align: center;
}
#chatbox {
text-align:left;
margin:0 auto;
margin-bottom:25px;
padding:10px;
background:#fff;
height:400px;
width:940px;
border:1px solid #ACD8F0;
overflow:auto; }
#message {
width:860px;
border:1px solid #ACD8F0;
margin-right: 5px;
}
#submit { width: 60px; }
.error { color: #ff0000; }
#menu { padding:12.5px 25px 12.5px 25px; }
.welcome {
margin-left:auto;
margin-right: auto;
margin-top: 20px;
font-size: 150%;
}
.message {
width: 100%;
height: auto;
background-color: #cccccc;
margin-bottom: 6px;
border-radius: 3px;
padding: 6px;
}
.msgln { margin:0 0 2px 0; }
</style>
</head>
<body>
<?php include 'resources/header.php' ?>
<div id="row">
<div id="large-9 columns" class="override" role="content">
<div id="wrapper" class="left-align">
<div id="menu">
<p class="welcome">GoonSquad Chat</p>
<div style="clear:both"></div>
</div>
<div id="chatbox">
</div>
<form id="messenger" action="" enctype="multipart/form-data">
<input type="text" id="message" class="left" autocomplete="off" size="63" maxlength="2000">
<input type="submit" id="send" class="button tiny" value="Send" >
<input type="hidden" id="id" value="<?php echo $user->data()->id; ?>">
<input type="hidden" id="name" value="<?php echo $user->data()->fullname?>">
<input type="hidden" id="un" value="<?php echo $user->data()->username?>"
</form>
</div>
</div>
</div>
<script type="text/javascript" src="scripts/chat.js"></script>
</body>
</html>
I have a situation i am generating dynamic html using jQuery like
var list_of_addressbook_entries = {};
var filter = []
function save(){
var user = $("#addressbook_user").val();
var desg = $("#desg").val();
var ahtml='<div id ="user_'+user+'" class="addr_list" style=" font-size: 30px;display:block; background: none repeat scroll 0% 0% peachpuff;margin:1px 1px 1px 1px ;">'
ahtml = ahtml + '<span style="display: block; float: left; font-size: 30px; margin: 2px 24px 2px 21px;" >'+user+'</span>'
if(desg == 'M'){
ahtml = ahtml + '<span style="display: block; float: left; font-size: 30px; margin: 2px 24px 2px 21px;">Moderator</span>'
}
else{
ahtml = ahtml + '<span style="display: block; float: left; font-size: 30px; margin: 2px 24px 2px 21px;">Attendee</span>'
}
ahtml = ahtml + '<div onclick="remove_video(\''+user+'\')"><span ><img src="/UI/user/img/delet.jpeg" alt="Smiley face" height="42" width="42" /> </span></div></div>'
var ua = "'"+user+"'";
filter.push(ua);
$.ajax({
type: "GET",
url: "<?php echo SITE_URL;?>/UI/user/filterbox.php",
data: "list="+ filter+"&Where=addressbook" ,
success: function(json){
$('#addorguser').html(json);
// if(!json.error) location.reload(true);
},
error: function (xhr, textStatus, errorThrown) {
alert(json);
}
});
$("#organization").append(ahtml);
}
function remove_video(user){
alert(user);
$("#user_"+user).hide();
}
After calling the save() i am appending dynamically generated html to a div there is a remove_video function i also defined in the dynamic html .
But when i am clicking on dynamic div to remove the div the remove_video function is not getting called .
I am also not getting any error .
Help me plz .
*Updated Html *
<div id="organization" name="organization">
</div>
<div>Address Book</div><br>
<div id="box1">
<?php
if (isset($_SESSION["user_name"])){
$get_user_name = $_SESSION["user_name"];
?>
<div id="addorguser" style="display: block; float: left;">
<select id ="addressbook_user" name="addressboook_user">
<?php
$asql = "SELECT * from demo_addressbook WHERE user_created_id IN(SELECT id FROM demo_user WHERE user_name = '$get_user_name') AND type = 1 ";
// $result = mysql_query($query);
// mysql_real_escape_string($asql);
$aresult = mysql_query($asql) or die (mysql_error());
while($arow_list=mysql_fetch_assoc($aresult)){
?>
<option value="<?php echo $arow_list['guest_name']; ?>"><?php echo $arow_list['guest_name']; ?></option>
<?php
}
?>
</select>
</div>
<select name="desg" id="desg">
<option value="A">Attendee</option>
<option value="M">Moderator</option>
</select>
<input type="button" id ="aadd" onclick="save()" name="button" value="Add"/>
</div>
<?php
}
?>
Try this exemple:
$('#aadd').on('click', function(e){
alert('Click');
});
or this one
$('#aadd').click(function(e){
alert('Click');
});
I have a question for you to upgrade my knowledge.
I am trying to create an inline editing page, the data are stored in a database.
In the table "content" I create 2 fields for testing purpose, the "id" and the "text" field.
If I want to modify the field with the "id=25" or id=X, I know how to do it manually, just specify in the MySQL Query "WHERE id=25", but if I have a list of 1000 entries, how can I modify the query to get the ID on the fly?
Here is the code, I am playing on:
index.php file
<style>
body {
font-family: Helvetica,Arial,sans-serif;
color:#333333;
font-size:13px;
}
h1{
font-family: Georgia, Times, serif;
font-size: 28px;
}
a{
color: #0071D8;
text-decoration:none;
}
a:hover{
text-decoration:underline;
}
:focus {
outline: 0;
}
#wrap{
width: 500px;
margin:0 auto;
overflow:auto;
}
#content{
background: #f7f7f7;
border-radius: 10px;
}
#editable {
padding: 10px;
}
#status{
display:none;
margin-bottom:15px;
padding:5px 10px;
border-radius:5px;
}
.success{
background: #B6D96C;
}
.error{
background: #ffc5cf;
}
#footer{
margin-top:15px;
text-align: center;
}
#save{
display: none;
margin: 5px 10px 10px;
outline: none;
cursor: pointer;
text-align: center;
text-decoration: none;
font: 12px/100% Arial, Helvetica, sans-serif;
font-weight:700;
padding: 5px 10px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
color: #606060;
border: solid 1px #b7b7b7;
background: #fff;
background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#ededed));
background: -moz-linear-gradient(top, #fff, #ededed);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#ededed');
}
#save:hover
{
background: #ededed;
background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#dcdcdc));
background: -moz-linear-gradient(top, #fff, #dcdcdc);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#dcdcdc');
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$("#save").click(function (e) {
var content = $('#editable').html();
$.ajax({
url: 'save.php',
type: 'POST',
data: {
content: content
},
success:function (data) {
if (data == '1')
{
$("#status")
.addClass("success")
.html("Data saved successfully")
.fadeIn('fast')
.delay(3000)
.fadeOut('slow');
}
else
{
$("#status")
.addClass("error")
.html("An error occured, the data could not be saved")
.fadeIn('fast')
.delay(3000)
.fadeOut('slow');
}
}
});
});
$("#editable").click(function (e) {
$("#save").show();
e.stopPropagation();
});
$(document).click(function() {
$("#save").hide();
});
});
</script>
</head>
<body>
<div id="wrap">
<div id="status"></div>
<div id="content">
<div id="editable" contentEditable="true">
<?php
//get data from database.
include("db.php");
$sql = mysql_query("select * from content");
$row = mysql_fetch_array($sql);
echo $row['id'];
echo "<br />";
echo $row['text'];
?>
</div>
<button id="save">Save</button>
</div>
</div>
</body>
And here is the save.php file:
include("db.php");
$content = $_POST['content']; //get posted data
$content = mysql_real_escape_string($content); //escape string
$sql = "UPDATE content SET text = '$content' WHERE id = '$id' ";
if (mysql_query($sql))
{
echo 1;
}
I know that this could be a stupid question but I am a newbie.
Thank you in advance for the help.
UPDATE:
thanx to Luis I fixed my old problem but I don't know why if I put all the code in a while only the "Save" button of the first entry is working good, the rest not, any hint?
At the moment I am testing only "description_text".
Here is the "while" code:
<?php
/////////// Now let us print the table headers ////////////////
$query =" SELECT * FROM gallery ORDER BY id DESC ";
$result = mysql_query($query) or die(mysql_error());
echo "<div style='width: 100%; text-align: center;'>";
echo "<table style='margin: auto auto;'>";
echo "<tr><th>ID</th><th>Image</th><th>Category</th><th>Description</th><th>Added on</th></tr>";
while($ordinate = mysql_fetch_array($result))
{
$id = $ordinate['id'];
$img_name = $ordinate['img_name'];
$category = $ordinate['category'];
$description_text = $ordinate['description_text'];
$insert_datetime = $ordinate['insert_datetime'];
echo "<tr><td style='width: 20px;'>".$id."</td><td style='width: 210px;'><img src='../../upload/content/uploaded_images/". $img_name ."' width='200px'></td><td style='width: 100px;'>".$category."</td><td style='width: 100px;'><div id='status'></div><div id='content'><div id='editable' contentEditable='true'>".$description_text."</div><button id='save'>Save</button></div></td><td style='width: 100px;'>".$insert_datetime."</td></tr>";
}
echo "</table><br /><br /></div>";
?>
on index.php move this part of code to the beginning, so you can use same vars in the rest of the script.
<?php
//get data from database.
include("db.php");
$sql = mysql_query("select * from content");
$row = mysql_fetch_array($sql);
// echo $row['id']; but keep this ones in its original place inside their <%php %> tags
// echo "<br />";
// echo $row['text'];
?>
Later in the ajax call, insert this PHP lines:
data: {
content: content
<?php
echo ", id: ".$row['id'];
echo ", token: '".md5('my SALT text'.(int)$row['id'])."'"; // strongly!!! recomended, not mandatory
?>
},
and on save.php
$id = (int)$_POST['id']; // (int) sanitizes id
$token = $_POST['token'];
if(md5('my SALT text'.$id)!=$token) die(); // or whatever but do not execute update
// perhaps echo 0; die();
// ... rest of your code ....
$sql = "UPDATE content SET text = '$content' WHERE id = $id"
the token, prevents the risk that someone uses your save.php as a way to inject whatever on every post on the table.
At least, an advice: use mysqli_query (notice the i) instead of mysql_query as this last is deprecated. Also, but with more diferences, you can use PDO
Instead of simply echoing the $row['id'], echo it inside an HTML element with specific id, so that it can be accessed from jQuery and can be posted.
<span id="idfield"><?php echo $row['id']; ?></span>
<button id="save">Save</button>
</div>
Then, inside the javascript :
$("#save").click(function (e) {
var content = $('#editable').html();
var id = $('#idfield').html();
Use it as a parameter in POST:
$.ajax({
url: 'save.php',
type: 'POST',
data: {
content: content,
id: id
},