Why is my AJAX request so slow? - javascript

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";

Related

Getting Undefined index when making a session

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.

How to input value in mysql depend on date?

Can someone help me? What i'm trying to do is, for example the date today is '2018-05-08' then if user enter on input text it will go on column name "ONE" and the date to column name "DAY1" then if the date is still '2018-05-08' and user enter again the value on ONE will be updated. But if the date is '2018-05-09' it will go on column name "TWO" and date to "DAY2" and if date is still 2018-05-09' it will just update "TWO". If the date is '2018-05-10' it will go on column name "THREE" and date to "DAY3". The DAY1 to DAY2 is good, but even the date is for DAY3 it's just updating the "DAY2" and not inserting into "DAY3". Please help me. Thanks.
<!DOCTYPE html>
<html>
<head>
<title>ASD</title>
</head>
<body>
<?php
include 'db.php';
$month = date('M');
$day1 = date('D');
$day = date('d');
$tot = 0;
$datetocheck = '2018-05-08';
if (isset($_POST['btn'])) {
$sal = $_POST['sal'];
$sql1 = "SELECT * FROM dates WHERE month='$month' and username='mrpopo'";
$result1 = mysqli_query($conn, $sql1);
$resultChecka = mysqli_num_rows($result1);
if ($resultChecka >0){
while($row = mysqli_fetch_assoc($result1)){
$one = $row['one'];
$two = $row['two'];
$three = $row['three'];
$four = $row['four'];
$day1 = $row['day1'];
$day2 = $row['day2'];
$day3 = $row['day3'];
$day4 = $row['day4'];
if ($day1 == $datetocheck) {
$sql23 = "UPDATE `dates` SET one='$sal' WHERE username='mrpopo' ";
mysqli_query($conn, $sql23);
}
elseif($day1 !=$datetocheck){
$sql23 = "UPDATE `dates` SET two='$sal', day2='$datetocheck' WHERE username='mrpopo' ";
mysqli_query($conn, $sql23);
}
elseif($day2==$datetocheck){
$sql23 = "UPDATE `dates` SET two='$sal' WHERE username='mrpopo' ";
mysqli_query($conn, $sql23);
}
elseif($day2 !=$datetocheck){
$sql23 = "UPDATE `dates` SET three='$sal', day3='$datetocheck' WHERE username='mrpopo' ";
mysqli_query($conn, $sql23);
}
elseif($day3 == $datetocheck){
$sql23 = "UPDATE `dates` SET three='$sal' WHERE username='mrpopo' ";
mysqli_query($conn, $sql23);
}
elseif($day3!=$datetocheck){
$sql23 = "UPDATE `dates` SET four='$sal', day4='$datetocheck' WHERE username='mrpopo' ";
mysqli_query($conn, $sql23);
}
elseif ($day4==$datetocheck) {
$sql23 = "UPDATE `dates` SET four='$sal' WHERE username='mrpopo' ";
mysqli_query($conn, $sql23);
}
}
}
else{
$sql= "INSERT INTO `dates` (one, username,month,day1) VALUES ('$sal', 'mrpopo', '$month', '$datetocheck') ";
mysqli_query($conn, $sql);
}
}
?>
<form method="post">
<label><?php echo $day1.' '. $month .' '.$day; ?></label><input type="text" name="sal" >
<button name="btn">Submit</button>
</form>
</body>
</html>
I don't think what do you want but if i underestood correctly you can use this code
<!DOCTYPE html>
<html>
<head>
<title>ASD</title>
</head>
<body>
<?php
$servername="localhost";
$username="user";
$password="password";
$dbname="dbname";
$dsn="mysql:host=$servername;dbname=$dbname";
try{
$connect=new PDO ($dsn,$username,$password);
$connect->exec("SET NAMES 'utf8';");
}catch(PDOException $error){
echo "Error in connect".$error->getMessage();
exit();
}
$date = date("Y-m-d");
$month = date('M');
$day1 = date('D');
$day = date('d');
$gid = $connect->prepare("SELECT MAX(bid) as maxGroup FROM dates");
$gid->execute();
$maxbid = $gid->fetch(PDO::FETCH_ASSOC);
if($maxbid['maxGroup']){$bid=($maxbid['maxGroup']+1);}else{$bid=1;}
$day="Day".$bid;
if (isset($_POST['btn'])) {
$sal = $_POST['sal'];
$count=$connect->query("SELECT * FROM dates WHERE month='$month' AND date='$date' and username='mrpopo'")->fetchColumn();
if ($count >0){
$connect->query("UPDATE `dates` SET text='$sal' WHERE month='$month' AND date='$date' and username='mrpopo'");
}
else{
$sql= ;
$connect->query("INSERT INTO `dates` (text, username,month,date,day) VALUES ('$sal', 'mrpopo', '$month', '$date', '$day')");
}
}
?>
<form method="post">
<label><?php echo $day.' '. $month .' '.$day; ?></label><input type="text" name="sal" >
<button name="btn">Submit</button>
</form>
</body>
</html>

how to add characters to the end of the value if it already exists?

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>";
}
}
}
?>

how to change value on mysql with php and view it dynamically without redirection refresh page

<?php echo"<td align ='center'>\".$bookstatus.\"<img src=\"img/refresh.png\" class=\"icon\"/></td>"; ?>
this link reach to s_bookstatus then change the value of bookstatus.
else if(isset($_GET['s_bookstatus']))
{
$id_commission = $_GET['id_commission'];
$qrycheck = "select * from commission where id_commission='$id_commission'";
$rscheck = mysqli_query($con,$qrycheck) or die(mysqli_error($con));
$rowcheck = mysqli_fetch_array($rscheck);
$s_bookstatus = $rowcheck['book_status'];
$id_book = $rowcheck['id_book'];
$qrybooklist = "select * from booklist where id_book='$id_book' ";
$rsbooklist = mysqli_query($con,$qrybooklist) or die(mysqli_error($con));
$rowbooklist = mysqli_fetch_array($rsbooklist);
$stock = $rowbooklist['stock'];
if($s_bookstatus == 'Available')
{
$check = 'Not Available';
$newstock = $stock - 1;
}
else if($s_bookstatus == 'Not Available')
{
$check = 'Available';
$newstock = $stock + 1;
}
mysqli_query($con,"update booklist set stock = $newstock where id_book = '$id_book' ");
$qry = "update commission set book_status ='$check' where id_commission ='$id_commission' ";
mysqli_query($con,$qry) or die(mysqli_error($con));
echo "<meta http-equiv='refresh' content='0; url=home.php?commission'>";
}
How to change this code to ajax without meta http-equiv refresh so the data changed dynamically in one page.
thank you..
if(isset($_GET['query'])){
$query = $_GET['query'];
$result = mysqli_query($con,$query) or die(mysqli_error($con));
}
else
{
$query = "select * from commission c left join booklist b on c.id_book = b.id_book $filterqry $search";
$result = mysqli_query($con,$query) or die(mysqli_error($con));
}
<td align ='center'>".$bookstatus."<img src=\"img/refresh.png\" class=\"icon\"/></td>
else if(isset($_GET['s_bookstatus']))
{
$id_commission = $_GET['id_commission'];
$query = $_GET['query'];
$qrycheck = "select * from commission where id_commission='$id_commission'";
$rscheck = mysqli_query($con,$qrycheck) or die(mysqli_error($con));
$rowcheck = mysqli_fetch_array($rscheck);
$s_bookstatus = $rowcheck['book_status'];
$id_book = $rowcheck['id_book'];
$qrybooklist = "select * from booklist where id_book='$id_book' ";
$rsbooklist = mysqli_query($con,$qrybooklist) or die(mysqli_error($con));
$rowbooklist = mysqli_fetch_array($rsbooklist);
$stock = $rowbooklist['stock'];
if($s_bookstatus == 'Available')
{
$check = 'Not Available';
$newstock = $stock - 1;
}
else if($s_bookstatus == 'Not Available')
{
$check = 'Available';
$newstock = $stock + 1;
}
mysqli_query($con,"update booklist set stock = $newstock where id_book = '$id_book' ");
$qry = "update commission set book_status ='$check' where id_commission ='$id_commission' ";
mysqli_query($con,$qry) or die(mysqli_error($con));
echo "<meta http-equiv=\"refresh\" content=\"0; url=home.php?commission&query=$query \">";
}

Simple auto-updating AJAX page

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);

Categories