<?php
require 'connect.inc.php';
$query = "SELECT `item`, `up`, `down` FROM mytable ORDER BY RAND() LIMIT 1";
$query_run = mysql_query($query);
if ($query_run = mysql_query($query)) {
while ($query_row = mysql_fetch_assoc($query_run)) {
$item = $query_row['item'];
$up = $query_row['up'];
$down = $query_row['down'];
?>
<div id="one">
<div id="votes">
<?php
echo "$up votes";
?>
</div>
</div>
<div id="or">
<div id="item">
<?php echo $item ?>
</div>
</div>
<div id="two">
<div id="votes">
<?php
echo "$down votes";
?>
</div>
</div>
<?php }
} else {
echo mysql_error();
}
?>
This is my code. I need to make it so when a user clicks the div id="one" or id="two" execute this sql query (if div one was clicked (same thing for two))
UPDATE mytable SET up=$up+1 WHERE id="1(can be any id)"
Also, can I do that math in an sql query?
Thanks
Alright so this consist of 3 parts:
1.html.
2.JS/ajax.
3.php.
1.) HTML.
<div data-action="up" class="clicker" id="<?php echo $item; ?>">
<div id="votes">
<?php
echo "$up votes";
?>
</div>
</div>
<div id="or">
<div id="item">
<?php echo $item ?>
</div>
</div>
<div data-action="down" class="clicker" id="<?php echo $item; ?>">
<div id="votes">
<?php
echo "$down votes";
?>
</div>
</div>
2.) JS/Ajax.
<script type='text/javascript' >
$('.clicker').click(function (){
doAjaxCall($(this).attr('id'), $(this).attr('data-action'));
});
function doAjaxCall(varID, vote){
var pageUrl = document.URL;
ar post = '{"ajax":"yes", "varID":' + varID + ', "vote":' + vote + '}';// Incase you want to pass dynamic ID
$.post(pageUrl,post,function(data){
var response = $.parseJSON( data )
if(response.success){
//do whatever you like.
alert('baaaam');
}
});
}
</script>
3.) php.
if($_POST['ajax'] == 'yes'){
$field = $_POST['vote'];
$query = "UPDATE mytable SET `$field` = `$field` +1 WHERE id=".$_POST['var_id'];
$query_run = mysql_query($query);
$return = array();
$return['success'] = false;
if($query_run){
$return['success'] = true;
}
echo json_encode($return);
die()
}
Update whole Page
if($_POST['ajax'] == 'yes'){
$field = $_POST['vote'];
$query = "UPDATE mytable SET `$field` = `$field` +1 WHERE id=".$_POST['var_id'];
$query_run = mysql_query($query);
$return = array();
$return['success'] = false;
if($query_run){
$return['success'] = true;
}
echo json_encode($return);
die()
}
$query = "SELECT `item`, `up`, `down` FROM mytable ORDER BY RAND() LIMIT 1";
$query_run = mysql_query($query);
if ($query_run = mysql_query($query)) {
while ($query_row = mysql_fetch_assoc($query_run)) {
$item = $query_row['item'];
$up = $query_row['up'];
$down = $query_row['down'];
?>
<div data-action="up" class="clicker" id="<?php echo $item; ?>">
<div id="votes">
<?php
echo "$up votes";
?>
</div>
</div>
<div id="or">
<div id="item">
<?php echo $item ?>
</div>
</div>
<div data-action="down" class="clicker" id="<?php echo $item; ?>">
<div id="votes">
<?php
echo "$down votes";
?>
</div>
</div>
<script type='text/javascript' >
$('.clicker').click(function (){
doAjaxCall($(this).attr('id'), $(this).attr('data-action'));
});
function doAjaxCall(varID, vote){
var pageUrl = document.URL;
var post = '{"ajax":"yes", "varID":' + varID + ', "vote":' + vote + '}';// Incase you want to pass dynamic ID
$.post(pageUrl,post,function(data){
var response = $.parseJSON( data )
if(response.success){
//do whatever you like.
alert('baaaam');
}
});
}
</script>
<?php }
} else {
echo mysql_error();
}
?>
Basically this is the whole thing. if you want i can also put the pieces together for you.
You can add and onClick() event in javascript/jquery. Then, do a POST like this
$("#div1").onClick(function(){
var info = $(this).val();
$.post("fileWithQuery.php",{toUpdate: info},function(data){ // (fileName to post, variables to send via POST, callBack function)
// Show a message
});
});
You just need to create that php file.
Related
I'm currently doing a private chat (style messenger), and I got a problem..
I have a href a link which sends an ID using GET to another page, the thing is that on the other page I load a jquery script which again sends to another page, suddenly it no longer finds the ID GET, what should I do? I want to actualise the page (the messages) thanks (noted that I'm new, I'm not enough good to use ajax or something..)
message.php
message
<?php
// $allUsers = 'SELECT * FROM members WHERE name LIKE "%cc%" ORDER BY id DESC' / SEARCH MEMBERS
$allUsers = $dbh->query('SELECT * FROM members ORDER BY id DESC LIMIT 0, 5');
if ($allUsers->rowCount() > 0)
{
while ($user = $allUsers->fetch())
{
?>
<div id="s_un_main">
<div class="s_un_main_pun">
<img src="../images/avatar/<?php echo $user['avatar'];?>">
<p><?php echo $user['name']; ?></p>
</div>
<div class="s_un_main_pdeux">
<a class="private" target="_blank" href="private.php?id=<?php echo $user['id']; ?>">Message</a>
</div>
</div>
<?php
}
}
else
{
echo "<p>" . "Aucun utilisateur trouvé. " . "</p>";
}
?>
private.php
private
<div id="get_name">
<?php
// USERINFO
if (isset($_SESSION['id']) AND !empty($_SESSION['id']))
{
$getid = $_GET['id'];
$req = $dbh->prepare('SELECT * FROM members WHERE id = :getid');
$req->bindValue('getid', $getid);
$req->execute();
$userinfo = $req->fetch();
}
?>
<div>
<img id="img_header" width="50" src="../images/avatar/<?php echo $userinfo['avatar'];?>">
</div>
<?php echo "<p>" . $userinfo['name'] . "</p>"; ?>
</div>
<section id="zz">
<div id="show_msg">
<?php
// AFFICHER LES MESSAGES
$getid = $_GET['id'];
$takeMsg = $dbh->prepare('SELECT * FROM private WHERE id_sender = :sender AND id_receipter = :receipter OR id_sender = :senderr AND id_receipter = :receipterr');
$takeMsg->bindValue('sender', $_SESSION['id']);
$takeMsg->bindValue('receipter', $getid);
$takeMsg->bindValue('senderr', $getid);
$takeMsg->bindValue('receipterr', $_SESSION['id']);
$takeMsg->execute();
while ($message = $takeMsg->fetch())
{
if ($message['id_receipter'] == $_SESSION['id'])
{
?>
<p style="color: red"><?php echo $message['message']; ?></p>
<?php
}
elseif ($message['id_receipter'] == $_GET['id'])
{
?>
<p style="color: green "><?php echo $message['message']; ?></p>
<?php
}
}
?>
</div>
</section>
<form id="private_form" method="POST" action="">
<textarea name="message"></textarea>
<input type="submit" name="send"></input>
</form>
<script>
setInterval('load_messages()', 1500);
function load_messages()
{
$('#zz').load('private_message.php');
}
</script>
private_message.php
error
<!-- DB -->
<?php include("../db/db.php"); ?>
<!-- DB -->
<?php
// AFFICHER LES MESSAGES
$getid = $_GET['id'];
var_dump($getid);
$takeMsg = $dbh->prepare('SELECT * FROM private WHERE id_sender = :sender AND id_receipter = :receipter OR id_sender = :senderr AND id_receipter = :receipterr');
$takeMsg->bindValue('sender', $_SESSION['id']);
$takeMsg->bindValue('receipter', $getid);
$takeMsg->bindValue('senderr', $getid);
$takeMsg->bindValue('receipterr', $_SESSION['id']);
$takeMsg->execute();
while ($message = $takeMsg->fetch())
{
if ($message['id_receipter'] == $_SESSION['id'])
{
?>
<p style="color: red"><?php echo $message['message']; ?></p>
<?php
}
elseif ($message['id_receipter'] == $_GET['id'])
{
?>
<p style="color: green "><?php echo $message['message']; ?></p>
<?php
}
}
?>
var_dump($id) = not found
Someone pls help me. I have search form and displaying data from database and im using jquery twbsPagination. So my problem is the space in url if the user search two or more words.I used encodeURIComponent(); its work perfectly fine its display data. but when i click on page 2. its display no data and when i go back to the first page the datas is not showing anymore. help me pls. im debugging for 12 hrs sorry for my english.
this is my form
<div class="input-group input-group-lg">
<input id="searchBar" type="text" class="form-control" placeholder="Search job">
<span class="input-group-btn">
<button id="searchBtn" type="button" class="btn btn-info btn-flat">Go!</button>
</span>
</div>
and this is my script
<script>
function Pagination(){
<?php
$limit=5;
$sql="SELECT COUNT(id_jobpost) AS id from job_post";
$result=$conn->query($sql);
if($result->num_rows > 0)
{
$row = $result->fetch_assoc();
$total_records = $row['id'];
$total_pages = ceil($total_records / $limit);
} else {
$total_pages = 1;
}
?>
$('#pagination').twbsPagination({
totalPages: <?php echo $total_pages;?>,
visible: 5,
onPageClick: function(e, page){
e.preventDefault();
$(".target-content").html("Loading....");
$(".target-content").load("job-pagination.php?page="+page);
}
});
}
</script>
<script>
$(function(){
Pagination();
});
</script>
<script>
$("#searchBtn").on("click", function(e){
e.preventDefault();
var searchResult = $("#searchBar").val();
var filter = "searchBar";
if (searchResult != "") {
$('#pagination').twbsPagination('destroy');
Search(searchResult,filter);
}else{
$('#pagination').twbsPagination('destroy');
Pagination();
}
});
<script>
function Search(val,filter){
$('#pagination').twbsPagination({
totalPages: <?php echo $total_pages; ?>,
visible: 5,
onPageClick: function(e, page){
e.preventDefault();
val = encodeURIComponent(val);
$(".target-content").html("Loading....");
$(".target-content").load("search.php?page="+page+"&search="+val+"&filter="+filter);
}
});
}
</script>
and this is my search.php
<?php
session_start();
require_once("db.php");
$limit = 5;
if (isset($_GET['page'])) {
$page = $_GET['page'];
}else{
$page = 1;
}
$start_from = ($page-1) * $limit;
$search = $_GET['search'];
$sql = "SELECT * FROM job_post WHERE jobtitle LIKE '%$search%' ORDER BY id_jobpost DESC LIMIT $start_from, $limit";
$result=$conn->query($sql);
if ($result->num_rows>0) {
while ($row=$result->fetch_assoc()) {
$sql1 = "SELECT * FROM company WHERE id_company='$row[id_companyname]'";
$result1 = $conn->query($sql1);
if($result1->num_rows > 0) {
while($row1 = $result1->fetch_assoc())
{
?>
<div class="attachment-block clearfix">
<img class="attachment-img" src="uploads/logo/<?php echo $row1['logo']; ?>" alt="Attachment Image">
<div class="attachment-pushed">
<h4 class="attachment-heading"><?php echo $row['jobtitle']; ?> <span class="attachment-heading pull-right">₱<?php echo $row['maximumsalary']; ?>/Month</span></h4>
<div class="attachment-text">
<div><strong><?php echo $row1['companyname']; ?> | <?php echo $row1['province'].",".$row1['city']; ?> | Experience Required(in years): <?php echo $row['experience']; ?></strong></div>
</div>
</div>
</div>
<?php
}
}
}
}else{
echo "<center><strong>No Job Matched!</strong></center>";
}
$conn->close();
?>
I think the error is in your search.php page code. You need to change your ending limit.
$limit = 5;
if (isset($_GET['page'])) {
$page = $_GET['page'];
}else{
$page = 1;
}
$start_from = ($page-1) * $limit;
$search = $_GET['search'];
$sql = "SELECT * FROM job_post WHERE jobtitle LIKE '%$search%' ORDER BY id_jobpost DESC LIMIT $start_from, $limit";
When you are on the first page, you are doing: LIMIT 0, 5. When you are on the second page, you are doing: LIMIT 5, 5.
I suggest:
$limit = 5;
if (isset($_GET['page'])) {
$page = $_GET['page'];
}else{
$page = 1;
}
$start_from = ($page-1) * $limit;
$end_at = $page * $limit;
$search = $_GET['search'];
$sql = "SELECT * FROM job_post WHERE jobtitle LIKE '%$search%' ORDER BY id_jobpost DESC LIMIT $start_from, $end_at";
However I also noticed that in your search page you are doing a query inside of a query, I think a better way to do this is with a join so you only hit the database once. I don't know the structure of your database but the below code is an example of a better way to go about it so that you only hit the database once:
<?php
session_start();
require_once("db.php");
$page_size = 5;
if (isset($_GET['page'])) {
$page = $_GET['page'];
}else{
$page = 1;
}
$start_from = ($page-1) * $page_size;
$end_at = $page * $page_size;
$search = $_GET['search'];
$sql = "
SELECT
j_p.*,
c.*
FROM
job_post j_p,
company c
WHERE
jobtitle LIKE '%$search%'
and c.id_company = j_p.id_companyname
ORDER BY
id_jobpost DESC
LIMIT
$start_from,
$end_at
";
$result=$conn->query($sql);
if ($result->num_rows>0) {
while($row1 = $result1->fetch_assoc()) {
?>
<div class="attachment-block clearfix">
<img class="attachment-img" src="uploads/logo/<?php echo $row1['logo']; ?>" alt="Attachment Image">
<div class="attachment-pushed">
<h4 class="attachment-heading"><?php echo $row1['jobtitle']; ?> <span class="attachment-heading pull-right">₱<?php echo $row1['maximumsalary']; ?>/Month</span></h4>
<div class="attachment-text">
<div><strong><?php echo $row1['companyname']; ?> | <?php echo $row1['province'].",".$row1['city']; ?> | Experience Required(in years): <?php echo $row1['experience']; ?></strong></div>
</div>
</div>
</div>
<?php
}
}else{
echo "<center><strong>No Job Matched!</strong></center>";
}
$conn->close();
?>
I want to use Ajax to call a PHP page without refresh.
Here is my code
<?php
global $db;
$cmd = "SELECT * FROM posts order by date desc";
$result = mysqli_query($db,$cmd);
while ($row = mysqli_fetch_assoc($result)){
$post_txt = $row['text'];
$post_image = $row['image'];
$postid = $row['postid'];
$date = $row['date'];
$userid = $row['userid'];
$new_date=time_elapsed_string($date);
?>
<?php
global $db;
$sql = "SELECT * FROM user WHERE id = '$userid'";
$result2 = mysqli_query($db,$sql);
while($row2 = mysqli_fetch_assoc($result2)){
$acountname = $row2['name'];
$acountlast_name = $row2['lastname'];
}
?>
<?php
echo"
<div id='postShare'>
<div class='col-xs-7' id='listPost'>
<div class='list-group'>
<input type='hidden' value='$userid' id='user_id_input_hidden'>
<li class=list-group-item text-center'><span class='pull-right'><p><a href='profile.php' id='prof_btn'>$acountname $acountlast_name</a></p></span>
<span class='pull-left'><p>$new_date</p></span>
<hr>
<center><h5 id='show_post_title'>$post_txt</h5></center> <hr>";?>
I want to load profile.php with Ajax:
$(document).ready(function(){
$('#prof_btn').click(function(){
var userid = $('#user_id_input_hidden').val();
var dataString = 'userid=' + userid;
$.ajax({
url:'profile.php',
type:'POST',
data:dataString,
success:function(prof){
$('html').empty();
$('html').append(prof);
}
});
return false;
});
});
But it only works for the newest posts in echo not for any posts. What is wrong?
When you load the profile, the #prof_btn element you added the event to are gone, and replaced by new ones that don't have any events bound.
You have two options:
Reapply the events manually.
Use event delegation to delegate the events to a parent element that doesn't get replaced.
Move the echo inside the loop
global $db;
$sql = "SELECT * FROM user WHERE id = '$userid'";
$result2 = mysqli_query($db, $sql);
while ($row2 = mysqli_fetch_assoc($result2)) {
$acountname = $row2['name'];
$acountlast_name = $row2['lastname'];
echo"
<div id='postShare'>
<div class='col-xs-7' id='listPost'>
<div class='list-group'>
<input type='hidden' value='$userid' id='user_id_input_hidden'>
<li class=list-group-item text-center'><span class='pull-right'><p><a href='profile.php' id='prof_btn'>$acountname $acountlast_name</a></p></span>
<span class='pull-left'><p>$new_date</p></span>
<hr>
<center><h5 id='show_post_title'>$post_txt</h5></center> <hr>
";
}
Remove the last bracket here:
while($row2 = mysqli_fetch_assoc($result2)){
$acountname = $row2['name'];
$acountlast_name = $row2['lastname'];
---> }
and put in the end here:
<center><h5 id='show_post_title'>$post_txt</h5></center> <hr>";
--> }?>
I'm trying to make it so when I click a span icon it will send the article_id to my php sql page which deletes my article, I'm using jQuery Ajax to send the id, the id sends alright on the jQuery side but after the http post request is done my table row is still there, can anyone see if somethings wrong with my code, thanks in advance!
<?php
$sql_categories = "SELECT art_id, art_title, art_company, art_cat_id, art_sta_id, art_date, art_rating, art_price, cat_id, cat_name, sta_id, sta_name
FROM app_articles LEFT JOIN app_categories
ON app_articles.art_cat_id = app_categories.cat_id
LEFT JOIN app_status
ON app_articles.art_sta_id = app_status.sta_id
ORDER BY art_order ASC";
if($result = query($sql_categories)){
$list = array();
while($data = mysqli_fetch_assoc($result)){
array_push($list, $data);
}
foreach($list as $i => $row){
?>
<div class="row" id="page_<?php echo $row['art_id']; ?>">
<div class="column one">
<span class="icon-small move"></span>
<span class="icon-small edit"></span>
<span id="<?php echo $row['art_id']; ?>" class="icon-small trash"></span>
</div>
<div class="column two"><p><?php echo $row['art_title']; ?></p></div>
<div class="column two"><p><?php echo $row['art_company']; ?></p></div>
<div class="column two"><p><?php echo $row['cat_name']; ?></p></div>
<div class="column one"><p><?php echo $row['art_date']; ?></p></div>
<div class="column one"><p><?php echo $row['art_rating']; ?></p></div>
<div class="column one"><p><?php echo $row['art_price']; ?></p></div>
<div class="column one"><p><?php echo $row['sta_name']; ?></p></div>
<div class="column one"><span class="icon-small star"></span></div>
</div>
<?php
}
}
else {
echo "FAIL";
}
?>
jQuery
$(document).ready(function(){
$(".trash").click(function(){
var del_id = $(this).attr('id');
$.ajax({
type:'POST',
url:'ajax-delete.php',
data: 'delete_id='+del_id,
success:function(data) {
if(data) {
}
else {
}
}
});
});
});
PHP mySQL Statement
if(isset($_POST['delete_id'])) {
$sql_articles = "DELETE FROM app_articles WHERE art_id = ".$_POST['delete_id'];
if(query($sql_articles)) {
echo "YES";
}
else {
echo "NO";
}
}
else {
echo "FAIL";
}
?>
the reason your row is still there because AJAX call does not refresh the page. If you want your row to be removed you gotta do something like:
ASSUMING that your span click event is inside the row
$(".trash").click(function(){
var del_id = $(this).attr('id');
var rowElement = $(this).parent().parent(); //grab the row
$.ajax({
type:'POST',
url:'ajax-delete.php',
data: {delete_id : del_id},
success:function(data) {
if(data == "YES") {
rowElement.fadeOut(500).remove();
}
else {
}
}
});
Replace:
data: 'delete_id='+del_id,
with:
data: delete_id : del_id,
I have tried to make a real time chat, but i have a problem: setInterval (for checking for new messages) does not work :/...
This is my jQuery code
$(function(){
setInterval(function() {
$.ajax({
url: "./ajax/checknew.php",
success: function(data) {
$("#chMsgCont").append(data);
}
});
},1000);
$('#chMsgCont').load('./ajax/msg.php', function() {
var div = $('#chMsgCont');
var o = div.offset().top;
div.scrollTop( o + 12302012 );
});
});
My msg.php
<?php
include("../system/config.site.php");
$query = mysql_query("SELECT * FROM chat_msg ORDER BY timestamp ASC");
while($p = mysql_fetch_assoc($query)) {
$auth = mysql_fetch_assoc(mysql_query("SELECT * FROM chat_users WHERE id = '".$p['auth_id']."'"));
$update = mysql_query("UPDATE chat_msg SET new = 'no' WHERE id = '".$p['id']."'");
?>
<div class="chatMsg">
<p id="chatPMsg">
<span class="chatTime"><?php echo date("H:i", $p['timestamp']); ?></span>
<b><?php echo $auth['name']." ".$auth['surname']; ?></b><br />
<?php echo stripslashes($p['msg']); ?>
</p>
<p id="chatImg">
<img src="./images/thumb<?php echo $p['auth_id']; ?>.png" />
</p>
<div style="clear:both;"><!– –> </div>
</div>
<?php
}
?>
My checknew.php
<?php
include("../system/config.site.php");
$query = mysql_query("SELECT * FROM chat_msg WHERE new = 'yes' ORDER BY timestamp ASC");
if(mysql_num_rows($query) > 0) {
while($p = mysql_fetch_assoc($query)) {
$auth = mysql_fetch_assoc(mysql_query("SELECT * FROM chat_users WHERE id = '".$p['auth_id']."'"));
?>
<div class="chatMsg">
<p id="chatPMsg">
<span class="chatTime"><?php echo date("H:i", $p['timestamp']); ?></span>
<b><?php echo $auth['name']." ".$auth['surname']; ?></b><br />
<?php echo stripslashes($p['msg']); ?>
</p>
<p id="chatImg">
<img src="./images/thumb<?php echo $p['auth_id']; ?>.png" />
</p>
<div style="clear:both;"><!– –> </div>
</div>
<?php
}
} else {
echo "";
}
?>
setInterval refuses to append the results of the query :/, how is it possible?
May it must call window.setInterval() ?