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>";
--> }?>
Related
How to detect link in some text which is included from chat database and detect default meta information and put it to text like on discord.
ATTACHMENT
CODE
<?
session_start();
include('../../php/connect.php');
if(isset($_GET['uid']) && isset($_GET['cid']) && isset($_SESSION['user'])) {
$uid = $_GET['uid'];
$user = $_SESSION['user'];
$check = mysqli_query($con, "SELECT * FROM users WHERE id = '$uid'");
$ch = mysqli_fetch_array($check);
if($ch['username'] == $user) {
$cid = $_GET['cid'];
$uq = mysqli_query($con, "SELECT * FROM users WHERE id = '$cid'");
$u = mysqli_fetch_array($uq);
$asd = $u['username'];
$photo = $ch['photo'];
$query = mysqli_query($con, "SELECT * FROM users WHERE username = '$asd'");
$q = mysqli_fetch_array($query);
$row = mysqli_query($con, "SELECT * FROM messages WHERE (user1,user2,type) = ('$user','$asd','message') OR (user2,user1,type) = ('$user','$asd','message') ORDER BY id ASC");
while($result = mysqli_fetch_object($row)) { $date = date_create($result->sent); $time = date_format($date, 'H:i'); $date = date_format($date, 'd.m.Y');
?>
<div class="message" id="message">
<div class="hr-text">
<span>
<? echo $date; ?>
</span>
</div>
<div id="avatar" class="avatar-u"><img src="<? if($result->user1 == $asd) { echo '../../img/avatars/'.$q['photo']; } elseif($result->user1 == $user) { echo '../../img/avatars/'.$photo; } ?>">
</div>
<span class="username-u">
<? echo $result->user1; ?>
</span>
<span class="time">
<? echo $time; ?>
</span>
<div class="message-content">
<? echo '<xmp>'.$result->content.'</xmp>'; ?>
</div>
</div>
<?
}
} else {
header('location: ../index.php');
}
} else {
header('location: ../index.php');
}
?>
AJAX imports this site to #content-frame every 750ms.
I just want for example paste detected link to <a> element and then write some meta information like in ATTACHMENT upper
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'm making a personal website and I just wanted it to be a bit easier for me to add/edit my posts without manually going into phpmyadmin.
When I go to the edit_post.php page and press update I get an "=" sign next to the pid eg.(foo.php?pid=3), and if i let it redirect to the blog page it doesn't update it.
Blog page
<?php
session_start();
include_once("../IncBlog/db.php");
?>
<?php include "../Includes/navHead.php"; ?>
<title>Adam Brickhill - Life Journal </title>
</head>
<body>
<div class="box">
<div class="header">
<nav class="nav"><p class="title"><a class="postLink" href="../IncBlog/post.php">- Lone Tree -</a></p></nav>
</div>
<!-- JOURNAL !-->
<?php
require_once("../nbbc/nbbc.php");
$bbcode = new BBCode;
$sql = "SELECT * FROM posts ORDER BY id DESC";
$res = mysqli_query($db, $sql) or die(mysqli_error());
$posts = "";
if (mysqli_num_rows($res) > 0) {
while ($row = mysqli_fetch_assoc($res)) {
$id = $row['id'];
$title = $row['title'];
$img = $row['img'];
$content = $row['content'];
$date = $row['date'];
$admin = "<div><a href='../IncBlog/del_post.php?pid$id'>Delete</a> <div><a href='../IncBlog/edit_post.php?pid$id'>Edit</a>";
$output = $bbcode->Parse($content);
ob_start();
include('../IncBlog/blogSkel.php');
$posts .= ob_get_contents();
ob_end_clean();
}
echo $posts;
}
else {
echo "There are no posts to display";
}
?>
<div class="journal">
<div class="catagories">
</div>
<!-- Date !-->
<!-- Picture !-->
<!-- Description !-->
</div>
<?php include "../Includes/navFooter.php"; ?>
<!-- SCRIPTS !-->
<?php include "../Includes/navScriptImport.php"; ?>
</div>
</body>
</html>
Edit Page
<?php
session_start();
include_once("db.php");
if (!isset($_SESSION['username'])) {
header("Location: login.php");
return;
}
$pid = $_SERVER['REQUEST_URI'];
$pid = trim($pid, "/IncBlog/edit_post.php?pid");
$pid = strip_tags($pid);
$pid = stripslashes($pid);
$pid = mysqli_real_escape_string($db, $pid);
//echo "$pid";
if ($pid == "") {
header("Location: ../Nav/life.php");
}
if (isset($_POST['update'])) {
$title = strip_tags($_POST['title']);
$content = strip_tags($_POST['content']);
$img = strip_tags($_POST['image']);
$title = mysqli_real_escape_string($db, $title);
$content = mysqli_real_escape_string($db, $content);
$img = mysqli_real_escape_string($db, $img);
$date = date("l jS \of F Y h:i:s A");
$sql = "UPDATE posts SET title='$title', content='$content', img='$img', date='$date' WHERE id=$pid";
if ($title == "" || $content == "") {
echo "The database is hungry you can't feed it nothing!";
return;
}
mysqli_query($db, $sql);
header("Location: ../Nav/life.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Blog - Post</title>
</head>
<body>
<?php
$sql_get = "SELECT * FROM posts WHERE id=$pid LIMIT 1";
$res = mysqli_query($db, $sql_get);
if (mysqli_num_rows($res) > 0) {
while ($row = mysqli_fetch_assoc($res)) {
$title = $row['title'];
$content = $row['content'];
$img = $row['image'];
echo "<form action='edit_post.php?pid=$pid' method='post' enctype='multipart/form-data'>";
echo " <input placeholder='Title' type='text' name='title' value='$title' autofocus size='48'><br /><br />";
echo " <input placeholder='Image' type='text' name='image' value='$img' autofocus size='48'><br /><br />";
echo " <textarea placeholder='Content' name='content' rows='40' cols='40'>$content</textarea><br />";
}
}
?>
<input type="submit" name="update" value="Update">
</form>
</body>
</html>
You have to set the columns and set the values for the columns.
UPDATE posts SET ( title, content, img, date ) VALUES ($title, $content, $img, $date) WHERE id = $pid;
$date = date("l jS \of F Y h:i:s A");
use instead of above line
$date = date('Y-m-d H:i:s', strtotime());
$sql = 'UPDATE posts SET title='".$title."', content='".$content."', img='".$img."', date='".$date."' WHERE id='".$pid."'";
Ok so I figured it out, very small programmers blindness but hey we all get it.
Line 66 echo "<form action='edit_post.php?pid$pid' method='post' enctype='multipart/form-data'>";
Where it says "?pid$pid" I just needed to remove the "=" that i had there.
I have a database with a few images already set, I would like to have the url display an ID from each query as the user hits next. The user should be able to share the URL and paste it into their browser, the url should pull that unique ID from the query. The issue i am having is every time i paste a url, I get a random image and not the image that is in the ID. I'm at a loss here and im not sure what to do :( here's the code I have so far.
<?php
if (isset($_GET['id'])) {
include("PHP/db.php");
echo $where = $_GET["id"];
echo $query = "SELECT * FROM images WHERE ID =" . $where;
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($result);
$ID = $row['ID'];
$title = $row['name'];
$image = "<img height=500 width=600 src=http://www.goupics.com/img/" . $row['name'] . " >";
}
if($_GET['next4']) {
echo 'HELLO THIS IS THE NEXT IF METHOD';
include("PHP/db.php");
$query = "SELECT * FROM images ORDER BY RAND() LIMIT 1";
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($result);
$ID = $row['ID'];
$title = $row['name'];
$image = "<img height=500 width=600 src=http://www.goupics.com/img/" . $row['name'] . " >";
}
?>
<body>
</div>
<div id="title"> <?php echo $title ?> </div>
<div id="mainpic">
<?php echo $image ?>
</div>
<div id="prevnext">
<div id="next">
<a href="?id=<?php echo $ID ?>" name="name4" >Next</a>
</div>
<div id="prev">
Previous
</div>
</div>
Try this:
<?php
include("PHP/db.php");
$query2 = "SELECT * FROM images ORDER BY RAND() LIMIT 1";
$result2 = mysqli_query($dbc, $query2);
$rand_row = mysqli_fetch_array($result2);
$rand_id = $rand_row ['ID'];
if (!isset($_GET['id'])) {
$_GET['id'] = $rand_id;
}
if (isset($_GET['id'])) {
echo $where = $_GET["id"];
echo $query = "SELECT * FROM images WHERE ID =" . $where;
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($result);
$ID = $row['ID'];
$title = $row['name'];
$image = "<img height=500 width=600 src=http://www.goupics.com/img/" . $row['name'] . " >";
}
?>
<body>
</div>
<div id="title"> <?php echo $title ?> </div>
<div id="mainpic">
<?php echo $image ?>
</div>
<div id="prevnext">
<div id="next">
<a href="?id=<?php echo $rand_id; ?>" name="name4" >Next</a>
</div>
<div id="prev">
Previous
</div>
</div>
I changed:
-link to next is now id=rand
-changed your code to give me a "rand ID" and its already defined on the href of the page you load
It will go inside condition (next == true).
Make sure that your variables are initialized before use.
<?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.