So I am sort of new to AJAX and I am trying to get this to work. What I am trying to do is create a messaging app that automatically updates every 3 seconds.
Here is my script:
function first() {
var searchUser = $("input[name='username']").val();
$.post("messageSearch.php", {userVal: searchUser}, function(output){
$('#messageField').html(output);
});
}
function searchm() {
var searchUser = $("input[name='username']").val();
$.post("messageSearch.php", {userVal: searchUser}, function(output){
$('#messageField').val(output);
});
}
setInterval( "searchm()", 3000 );
Here is my messageSearch.php:
<?php
session_start();
$userdb = new mysqli('localhost', 'test', '', 'social-network');
if(isset($_POST['userVal'])) {
$searchm = $_POST['userVal'];
$output = '';
if ($searchm == ''){
echo $output;
exit();
}
$uidquery = mysqli_query($userdb, "SELECT * FROM users WHERE username='$searchm' LIMIT 1");
$uid= '';
while($row2 = mysqli_fetch_array($uidquery)) {
$uid = $row2['id'];
}
$uid = 2;
$query = mysqli_query($userdb, "SELECT * FROM messages WHERE p2=$uid AND `read`='n' LIMIT 3");
$count = mysqli_num_rows($query);
if($count == 0) {
$output = 'You have no messages.';
} else {
while($row = mysqli_fetch_array($query)) {
$from = $row['p1'];
$message = $row['message'];
$time = $row['time'];
$time = date('Y-m-d H:i:s', strtotime($time));
$fromResult = mysqli_query($userdb, "SELECT * FROM users WHERE id = '$from'");
while($row1 = mysqli_fetch_array($fromResult)) {
$fromFirst = $row1['first_name'];
$fromLast = $row1['last_name'];
$from = $fromFirst.' '.$fromLast;
}
$output .= '
<li>
<a href="#">
<div>
<strong>'.$fromFirst.' '.$fromLast.'</strong>
<span class="pull-right text-muted">
<em>'.$time.'</em>
</span>
</div>
<div>'.$message.'</div>
</a>
</li>
<li class="divider"></li>
';
}
$output .= '<li><a class="text-center" href="#"><strong>See All Messages</strong> <i class="fa fa-angle-right"></i></a></li>';
}
}
echo ($output);
?>
For some reason the first load works fine though the second one comes up blank. Hopefully you can help, though thanks in advance.
setInterval( "searchm()", 3000 ); should be
setInterval( searchm, 3000 );
Another error, in your PHP:
$query = mysqli_query($userdb, "SELECT * FROM messages WHERE p2=$uid AND `read`='n' LIMIT 3")
should be:
$query = mysqli_query($userdb, "SELECT * FROM messages WHERE p2=".$uid." AND `read`='n' LIMIT 3")
Lastly
$fromResult = mysqli_query($userdb, "SELECT * FROM users WHERE id = '$from'");
to
$fromResult = mysqli_query($userdb, "SELECT * FROM users WHERE id = ".$from);
Related
<?php>
if (isset($_POST['search']))
{
$startDate = $_POST['start'];
$startDate = str_replace('/', '-', $startDate );
$startDate = date("Y-m-d", strtotime($startDate));
echo $startDate;
$endDate = $_POST['end'];
$endDate = str_replace('/', '-', $endDate );
$endDate = date("Y-m-d", strtotime($endDate));
echo $endDate;
$model = $_POST['model'];
echo $model;
$dates = getDatesStartToLast($startDate, $endDate);
for ($i=0; $i < count($dates); $i++){
echo "<tr>";
echo "<td><text class = 'dateselect'>$dates[$i]</text></td>";
$query = mysqli_query($conn, "SELECT * from electec_db where DateInputTime >= '$dates[$i]' and DateInputTime <= '$dates[$i] 23:59:59' and Model = '$model'");
$count = mysqli_num_rows($query);
// echo $count;
echo "<td>$count</td>";
$arrays = array("Result = 'NG'", "Species = 'Burr'", "Species = 'Dirt'", "Species = 'Scratch'", "Species = 'Cracked'", "Species = 'Gas'" );
for ($j=0; $j < count($arrays); $j ++){
$query = mysqli_query($conn, "SELECT * from electec_db where DateInputTime >= '$dates[$i]' and DateInputTime <= '$dates[$i] 23:59:59' and Model = '$model' and $arrays[$j]");
$count = mysqli_num_rows($query);
echo "<td>$count</td>";
// And this is jsp code
<script>
$('.dateselect').click(function() {
var dateSelect = $(this).text();
alert(dataSelect)
}
</script>
This is php code and javascript code.
When I click echo "$dates[$i]"; part,
I want to make react in script like alert dateSelect variable. But it doesn't make any reaction.
How to make a table react in javascript when clicked in php?
Do you have jQuery installed in your project? That's what the $ indicates.. Not sure what the jsp comment is about.
In straight javascript you could do something like this:
document.querySelectorAll('.dateSelect').forEach(item => {
item.addEventListener('click', event => {
alert(event.target.innerHTML)
})
})
<p class="dateSelect">thing1</p>
<p class="dateSelect">thing2</p>
<p class="dateSelect">thing3</p>
Hi I'm trying to make a session in my main page but its just giving me an error of undefined index in uniqueID line 5.
The connection between my webqr.js and server.php have no errors but when I tried to connect it to my wow.php it gives me an error of undefined index.
webqr.js Code
function read(a){
var html=htmlEntities(a);
var audio = new Audio('lib/beep.ogg');
audio.play();
var uniqueID = document.getElementById("mapo").innerHTML= html;
window.location.href = "http://localhost/QR_JEFF/server.php?uniqueID=" + uniqueID; }
server.php Code
session_start();
$db = mysqli_connect('localhost', 'root','','suffrage');
$uniqueID = $_GET['uniqueID'];
$query = "SELECT * FROM applicant_table WHERE unique_id='$uniqueID'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$logged_in_user = mysqli_fetch_assoc($results);
if($logged_in_user['validation_status'] == 'Verified' && $logged_in_user['voting_status'] == 'No'){
$_SESSION['unique_id'] = $uniqueID;
$_SESSION['validation_status'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: wow.php');
}
}
wow.php Code
<?php include('server.php');?>
<?php if (isset($_SESSION['unique_id'])) : ?>
Welcome User:
<input type="text" value="<?php echo $_SESSION['unique_id']; ?>" disabled>
<?php endif ?>
Now I'm receiving this error.
okay so this solve my own question.
session_start();
if(isset($_GET['uniqueID'])){
$uniqueID = " ";
$db = mysqli_connect('localhost', 'root','','suffrage');
$uniqueID = $_GET['uniqueID'];
$query = "SELECT * FROM applicant_table WHERE unique_id='$uniqueID'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$logged_in_user = mysqli_fetch_assoc($results);
if($logged_in_user['validation_status'] == 'Verified' && $logged_in_user['voting_status'] == 'No'){
$_SESSION['unique_id'] = $uniqueID;
$_SESSION['validation_status'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: wow.php');
}
}
}
I put my code in another if statement.
I have a notifications system on my site, that utilizes AJAX to update in real-time. The problem is that it works on every browser except IE 11. After looking around I noticed some people advising to use cache:false in the call. However, this makes the code non-functional across all browsers. Anyone know what the solution is?
JAVASCRIPT:
<script>
$(document).ready(function(){
$('.notif_count').html('0');
function load_unseen_notification(view = '')
{
$.ajax({
url:"notif_follow.php",
method:"POST",
data:{view:view},
dataType:"json",
success:function(data)
{
$('.notif_follow').html(data.notification);
if(data.notif_count > 0)
{
$('.notif_count').html(data.notif_count);
}
}
});
}
load_unseen_notification();
$(document).on('click', '.notif', function(){
$('.notif_count').html('0');
load_unseen_notification('yes');
});
setInterval(function(){
load_unseen_notification();;
}, 5000);
});
</script>
PHP:
<?php
session_start();
require_once 'class.channel.php';
$user_notif = new USER();
$user_id = $_SESSION['userID'];
if(isset($_POST["view"]))
{
if($_POST["view"] != '')
{
$stmt = $user_notif->runQuery("UPDATE notif_follow SET status = 1 WHERE receive_id = ?");
$stmt->bindValue(1,$user_id);
$stmt->execute();
}
$stmt = $user_notif->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$user_id));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $user_notif->runQuery("SELECT * FROM notif_follow WHERE receive_id= ? ORDER BY id DESC LIMIT 5");
$stmt->bindValue(1,$user_id);
$stmt->execute();
$notifs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$notification = '';
if(count($notifs) > 0)
{
foreach($notifs as $notif)
{
$send_id = $notif['send_id'];
$query2 = $user_notif->runQuery("SELECT * FROM following WHERE user1_id=:uid1 AND user2_id=:uid2");
$query2->execute(array(":uid1"=>$user_id,":uid2"=>$send_id));
$query2result = $query2->fetchAll(PDO::FETCH_ASSOC);
if(count($query2result) > 0){
$follow = '<button class="button" style="margin:2px;">Remove Channel</button>';
}
else{
$follow = '<button class="button" style="margin:2px;">Add Channel</button>';
}
$notification .= '
<li>
<div class="notifbox">
<strong style="color: #4b8ed3;">'.$notif["send_name"].'</strong><p style="color: #fff;"> has added you.</p>
'.$follow.'
<button class="button" style="margin:2px;">View Channel</button>
</div>
</li>
<div class="sectionheader3"></div>
';
}
}
else
{
$notification .= '<li><h2 style="color: #4b8ed3; padding: 10px;">No Notifications Found<h2></li>';
}
$count = $user_notif->runQuery("SELECT * FROM notif_follow WHERE receive_id= ? AND status= 0");
$count->bindValue(1,$user_id);
$count->execute();
$countresult = $count->fetchAll(PDO::FETCH_NUM);
if(count($countresult) > 0){
$notif_count = count($countresult);
}
else{
$notif_count = 0;
}
header('Content-type: application/json');
$notif_array = array('notification'=>$notification,'notif_count'=>$notif_count);
echo json_encode($notif_array);
}
?>
Here when I click post button it inserts a random value on database.
If a value already exists on database then show error. It works fine.
But I want to add 2/3 characters at the end of value if it already exists on database. If $check == 1 then I want to add some characters at the end of the value instead of showing alert. How to do this?
<?php
$con = mysqli_connect("localhost","root","","post") or die("unable to connect to internet");
if(isset($_POST['submit']))
{
$slug = $_POST['rand'];
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
// if $check==1 then i want to add 2 characters at the end of $slug .
if($check == 1)
{
// instead of showing alert i want to add 2 more characters at the end of that value and and insert it on database
echo "<script> alert('something is wrong') </script> ";
exit ();
}
else
{
$insert ="insert into slug (post_slug) values ('$slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
}
?>
<form method="POST" >
<?php
$result = "";
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$chararray = str_split($chars);
for($i = 0; $i < 7 ; $i++)
{
$randitem = array_rand($chararray);
$result .= "".$chararray[$randitem];
}
echo $result ;
?>
<input type="hidden" value="<?php echo $result;?>" name="rand" />
<span class="input-group-btn">
<button class="btn btn-info" type="submit" name="submit">POST</button>
</span>
</form>
just run update query if $check == 1
if($check == 1){
$newSlug = $slug."xy";
$update = "update slug set post_slug = '".$newSlug."' where post_slug = '".$slug."'";
$run = mysqli_query($con,$update );
echo "<script> alert('Updated Successfully') </script> ";
exit ();
}
This is helpful for you
<?php
$con = mysqli_connect("localhost","root","","post" ) or die
( "unable to connect to internet");
if(isset($_POST['submit'])){
$tmp_slug = $_POST['rand'];
$slug = $_POST['rand'];
while(check_exiest($tmp_slug))
{
$tmp_rand = rand(11,99);
$tmp_slug = $slug.$tmp_rand;
}
$insert ="insert into slug (post_slug) values ('$tmp_slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
public function check_exiest($slug)
{
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
if($check >= 1)
{
return true;
}
else
{
return false;
}
}
?>
Just few modification in your code to insert new value.
<?php
$con = mysqli_connect("localhost","root","","post") or die("unable to connect to internet");
if(isset($_POST['submit']))
{
$slug = $_POST['rand'];
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
if($check == 1)
{
$slug_new = $slug.'ab'; // Add 2 characters at the end
$update ="UPDATE slug SET post_slug = '$slug_new' WHERE post_slug = '$slug'";
$run = mysqli_query($con,$update);
}
else
{
$insert ="insert into slug (post_slug) values ('$slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
}
?>
This AJAX request takes about a second to execute, and I wondered whether there was a way of speeding it up?
It's a button click event within the context of a Twitter-style follow/unfollow.
JS:
$.ajax
({
type: "POST",
url: "follow.php",
data: {id: id, shop_name: shop_name},
context: this,
success: function(data)
{
if ($(this).html() == 'Add')
{
$(this).toggleClass('btn-primary');
$(this).html('<span class="glyphicon glyphicon-ok"></span> Added');
}
else if ($(this).html() == '<span class="glyphicon glyphicon-ok"></span> Added')
{
$(this).toggleClass('btn-primary');
$(this).html('Add');
}
}
});
PHP:
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);
include('connect.php');
$id = $_POST['id'];
$user_id = $id['id'];
$shop_name = mysqli_escape_string($con, $_POST['shop_name']);
$feed_id_query = "SELECT DISTINCT feed_id FROM shopaholic WHERE shop_name = '$shop_name'";
$feed_id = mysqli_query($con, $feed_id_query) or die(mysqli_error($con));
$row = mysqli_fetch_array($feed_id);
$feed_id = $row[0];
$query = "SELECT * FROM sh_subscriptions WHERE user_id = $user_id AND feed_id = $feed_id";
$result = mysqli_query($con, $query) or die(mysqli_error($con));
// check if row exists
if (mysqli_num_rows($result) > 0)
{
// row already exists, so check whether it is active
$query2 = "SELECT * FROM sh_subscriptions WHERE user_id = $user_id AND feed_id = $feed_id AND active = 1";
$result2 = mysqli_query($con, $query2) or die(mysqli_error($con));
if (mysqli_num_rows($result2) > 0)
{
// row is active, so deactivate it
$query3 = "UPDATE sh_subscriptions SET active = 0 WHERE user_id = $user_id AND feed_id = $feed_id";
$result3 = mysqli_query($con, $query3) or die(mysqli_error($con));
}
else
{
// row is inactive, so activate it
$query4 = "UPDATE sh_subscriptions SET active = 1 WHERE user_id = $user_id AND feed_id = $feed_id";
$result4 = mysqli_query($con, $query4) or die(mysqli_error($con));
}
}
else
{
// row does not exist, so create it
$query5 = "INSERT INTO sh_subscriptions (user_id, feed_id, active) VALUES ($user_id, $feed_id, 1)";
$result5 = mysqli_query($con, $query5) or die(mysqli_error($con));
}
UPDATE
I'm checking the AJAX load times in the console. The vast majority of the time is spent 'waiting', which I presume is the PHP doing its work. It also loads more slowly the first time (anything from 50ms slower at least) and then generally gets faster.
One thing you can try is to add "LIMIT 1" to both selects
$feed_id_query = "SELECT DISTINCT feed_id FROM shopaholic WHERE shop_name = '$shop_name' LIMIT 1";
$query = "SELECT * FROM sh_subscriptions WHERE user_id = $user_id AND feed_id = $feed_id LIMIT 1";
Since you neet only one result in each query
same here
$query2 = "SELECT * FROM sh_subscriptions WHERE user_id = $user_id AND feed_id = $feed_id AND active = 1 LIMIT 1";