I have this ajax request code
function hehe2(){
var a = $(".film2numb").val();
return $.ajax({
type : "GET",
url : "php/controller1.php?page=semuafilm",
data : "data="+a,
cache: false,
success: function(data){
$('.semuafilm').load('php/film.php');
},
});
}
and it requests this php code, basically it prints out HTML data from SQL
<?php
$indicator = $_SESSION['p'];
if ($indicator == 'filmbaru') {
# code...
$batas = $_SESSION['a'];
if (!$batas) {
$batas = 1;
}
if ($batas>1) {
$batas = $batas * 8;
}
include('connect.php');
$queryfilm = "select * from tb_film order by film_year desc, film_id desc limit $batas ,8";
$exec = $conn->query($queryfilm);
while ( $f = $exec->fetch_assoc()) {
$tn = str_replace(" ","-",$f['film_name']) ;
?>
<div class='col l3 m3 s6 itemovie'><div><img src="images/dum.jpg" class="lazy" data-original='http://www.bolehnonton.com/images/logo/<?php echo $f["film_logo"]; ?>' width="214" height="317"><div><div><div><p><b><?php echo $f['film_name']; ?></b></p><p>IMDB Rating</p><p><?php echo $f['film_genre']; ?></p><p class='center-align linkmov'><a class='dpinblock browntex' href='?page=movie&filmname=<?php echo $tn; ?>'>PLAY MOVIE</a></p><p class='center-align linkmov'><a class='dpinblock' href=''>SEE TRAILER</a></p></div></div></div></div></div>
<?php
}
?>
and here is the controller
<?php
session_start();
$a = $_GET['data'];
$p = $_GET['page'];
$g = $_GET['genre'];
$_SESSION['a'] = $a;
$_SESSION['p'] = $p;
$_SESSION['g'] = $g;
?>
My question is why every time I click button that binded to the hehe2() function (4-5 times, which requested a lot of images) the page get heavier as I click incrementally(laggy, slow to scroll), is there a way to make it lighter, or is there a way to not store image cache on page or clear every time I click the button that binded to hehe2() function?
I am not sure that my advice will be helpful, I will just share my experience.
First of all you should check your binding. Do you bind click trigger only once?
Sometimes function binds multiple times and it can slow down the page.
You can put code below inside function and check the console
console.log("Function called");
If everything is fine from that point and function fires only once - I would recommend you to change flow a little bit. Is it possible to avoid many clicks in a row? If it is not big deal - you can disable button on click, show loader and enable button when AJAX request is completed. This approach will prevent from making multiple requests at once at page will be faster.
Related
I am creating a kind of messaging system with php and jQUERY, when you click on users profile and hit the messaging button it take us to the message page, it takes about 2sec to load previous message, so I added a code to scroll to bottom of the div class containing all message item once the ajax is loaded, to show latest messages , but the problem I am having is when I try to scroll up back I am having issues , the moment i try to scroll up due to the code i added it goes down on its own, any solution would be well appreciated.
Here is my JQ code - if there is anything else I can provide to help me solve this issue, I would do so quickly.
$(document).ready(function(){
/*post message via ajax*/
//get message
var c_id = $("#conversation_id").val();
//get new message every 2 second
setInterval(function(){
$(".display-message").load("get-message-ajax.php?c_id="+c_id , stateChange);
}, 2000);
});
function stateChange() {
var newstate = true;
if(newstate = true){
$(".conversation_history.clearfix").animate({
scrollTop: $('.conversation_history.clearfix')[0].scrollHeight - $('.conversation_history.clearfix')[0].clientHeight
}, 1000)} else {
$(".conversation_history.clearfix").end();
var newstate = false;
}
}
Code from get_message-ajax.php
<?php
include 'db.php';
include 'function.php';
/*Get Message*/
if(isset($_GET['c_id'])){
$conversation_id = base64_decode($_GET['c_id']);
$querynew = "SELECT * FROM `messages` WHERE conversation_id='$conversation_id'";
$mysqli_q_new = mysqli_query($connection, $querynew);
confirmQuery($mysqli_q_new);
if (mysqli_num_rows($mysqli_q_new) > 0 ){
while($user_real_info = mysqli_fetch_assoc($mysqli_q_new)){
$trap_user_from = $user_real_info['user_from'];
$trap_user_to = $user_real_info['user_to'];
$trap_user_message = $user_real_info['message'];
$querynew2 = "SELECT profile_image,firstname FROM `users` WHERE id='$trap_user_from'";
$mysqli_q_new2 = mysqli_query($connection, $querynew2);
confirmQuery($mysqli_q_new2);
$user_fetch = mysqli_fetch_assoc($mysqli_q_new2);
$user_form_username = $user_fetch['firstname'];
$user_form_img = $user_fetch['profile_image'];
?>
<div class='conversation_history_inner clearfix'>
<span><?php echo $user_form_username; ?> </span>
<div class='converstion_history_image img-is-responsive pull-left'>
<?php echo getUserImage($user_form_img) ?>
</div>
<div class='converstion_history_chat'>
<p><?php echo $trap_user_message; ?></p>
</div>
</div>
<?php
}
}
} else {
echo 'nth found';
}
?>
I'm assuming you only want to scroll down when it gets the first message. If so, I would suggest changing the stateChange function into this:
var scrolled = false;
function stateChange() {
if(!scrolled){
$(".conversation_history.clearfix").animate({scrollTop: $('.conversation_history.clearfix')[0].scrollHeight - $('.conversation_history.clearfix')[0].clientHeight}, 1000);
scrolled = true;
}
}
This will make it only scroll down the first time it gets a new message instead of every time like it currently does.
The content is scrolling to bottom automatically because you have used setInterval function which will trigger at a constant interval of time. Use setTimeOut instead it will call only once after the specified time. Look here for more details
I have undercome a problem when implementing a "Show more button"
The page will initially display 5 rows of data, then on click the button will make a call to a php function through ajax and load more results, ultimately displaying them on the page. It does this very well.
The problem is that each of the divs are clickable in their own right to allow for user interaction. Before clicking the button the first 5 are clickable and work correctly, however after loading the first 10, the first 5 become unclickable and the rest work as expected.
See my code here:
HTML:
<div class="col-sm-12 col-xs-12 text-center pushDown">
<div id="initDisplay">
<?php
// Display all subjects
echo displaySubjects($limit);
?>
</div>
<div id="show_result"></div>
<button id="show_more" class="text-center pushDown btn btn-success">Show More</button>
</div>
On click of the button the following is happening:
JQuery:
<script>
$("#show_more").on("click", function() {
$("#initDisplay").fadeOut();
});
/* This bit is irrelevant for this question
$("#addBtn").on("click", function(){
addSubject();
});
*/
var stag = 5;
$("#show_more").on("click", function(){
stag+=5;
console.log(stag);
$.ajax({
dataType: "HTML",
type: "GET",
url: "../ajax/admin/loadSubjects.php?show="+stag,
success: function(result){
$("#show_result").html(result);
$("#show_result").slideDown();
}
});
var totalUsers = "<?php echo $total; ?>";
if(stag > totalUsers) {
$("#show_more").fadeOut();
}
});
</script>
My PHP page and functions are here:
<?php
include_once '../../functions/linkAll.inc.php';
$limit = filter_input(INPUT_GET, "show");
if (isset($limit)) {
echo displayUsers($limit);
} else {
header("Location: ../../dashboard");
}
function displaySubjects($limit) {
$connect = db();
$stmt = $connect->prepare("SELECT * FROM Courses LIMIT $limit");
$result = "";
if ($stmt->execute()) {
$results = $stmt->get_result();
while($row = $results->fetch_assoc()){
$id = $row['ID'];
$name = $row['Name'];
$image = $row['image'];
if($image === ""){
$image = "subjectPlaceholder.png"; // fail safe for older accounts with no images
}
$result .=
"
<div class='img-container' id='editSubject-$id'>
<img class='miniProfileImage' src='../images/subjects/$image'>
<div class='middle' id='editSubject-$id'><p class='middleText'>$name</p></div>
</div>
";
$result .= "<script>editSubjectRequest($id)</script>";
}
}
$stmt->close();
return $result;
}
The script being called through this is:
function editSubjectRequest(id) {
$("#editSubject-"+id).click(function(e) {
e.preventDefault(); // Prevent HREF
console.log("You clicked on " + id);
$("#spinner").show(); // Show spinner
$(".dashContent").html(""); // Empty content container
setTimeout(function() {
$.ajax({ // Perform Ajax function
url: "../ajax/admin/editSubjects.php?subjectID="+id,
dataType: "HTML",
type: "POST",
success: function (result) {
$("#spinner").hide();
$(".dashContent").html(result);
}
});
}, 1500); // Delay this for 1.5secs
});
}
This will then take the user to a specific page depending on the subject which they clicked on.
Your problem is duplicate ids. First five items are present on the page always. But when you load more, you are loading not new items, but all, including first five. As they are already present on the page, their duplicates are not clickable. The original items are however clickable, but they are hidden.
Here is what you need:
$("#show_more").on("click", function(){
$("#initDisplay").html("");
});
Don't just fadeOut make sure to actually delete that content.
This is the easiest way to solve your issue with minimum changes. But better option would be to rewrite your php, so it would load only new items (using WHERE id > $idOfLastItem condition).
Also you don't need that script to be attached to every div. Use common handler for all divs at once.
$("body").on("click", "div.img-container", function() {
var id = $(this).attr("id").split("-")[1];
});
When you are updating a DOM dynamically you need to bind the click event on dynamically added elements. To achieve this change your script from
$("#editSubject-"+id).click(function(e) {
To
$(document).on("click","#editSubject-"+id,function(e) {
This will bind click event on each and every div including dynamically added div.
I got function that collects and display's all posts, and for each have upvote/downvote buttons.
On button click I call function called upvotePost and downvotePost.
It all works fine, but it refreshes page, I want to understand how to make it not-refresh page.
I know it's done by ajax/jquery, but don't understand how to make it.
My button example:
<a href="fun.php?upvote-btn=true?action=select&image_id=<?php echo $post['id'];?>">
Function calling:
if(isset($_GET['upvote-btn'])){
$fun->upvotePost();
}
And my function:
public function upvotePost(){
try
{
if(isset($_SESSION['user_session'])){
$user_id = $_SESSION['user_session'];
$stmt = $this->runQuery("SELECT * FROM users WHERE id=:id");
$stmt->execute(array(":id"=>$user_id));
$myRow=$stmt->fetch(PDO::FETCH_ASSOC);
}else{
$_SESSION["error"]='Sorry, You have to login in you account!';
}
$id = $_GET['image_id'];
$user_id = $myRow['id'];
$stmt2 = $this->conn->prepare("SELECT count(*) FROM fun_post_upvotes WHERE image_id=('$id') AND user_id=('$user_id')");
$stmt2->execute();
$result2 = $stmt2->fetchColumn();
if($result2 == 0){
$stmt3 = $this->conn->prepare("INSERT INTO fun_post_upvotes (image_id,user_id) VALUES(:image_id,:user_id)");
$stmt3->bindparam(":image_id", $id);
$stmt3->bindparam(":user_id", $user_id);
$stmt3->execute();
$stmt4 = $this->conn->prepare("SELECT * FROM fun_posts WHERE id=('$id')");
$stmt4->execute();
$result4 = $stmt4->fetchAll();
foreach($result4 as $post){
$newUpvotes = $post['upvotes']+1;
$stmt5 = $this->conn->prepare("UPDATE fun_posts SET upvotes=$newUpvotes WHERE id=('$id')");
$stmt5->execute();
$_SESSION["result"]='You have succesfully liked this post!';
}
}else{
$_SESSION["error"]='You have already liked this post!';
}
$stmt6 = $this->conn->prepare("SELECT count(*) FROM fun_post_downvotes WHERE image_id=('$id') AND user_id=('$user_id')");
$stmt6->execute();
$result6 = $stmt6->fetchColumn();
if($result6 > 0){
$stmt7 = $this->conn->prepare("DELETE FROM fun_post_downvotes WHERE image_id=('$id') AND user_id=('$user_id')");
$stmt7->execute();
$stmt8 = $this->conn->prepare("SELECT * FROM fun_posts WHERE id=('$id')");
$stmt8->execute();
$result8 = $stmt8->fetchAll();
foreach($result8 as $post){
$newDownvotes = $post['downvotes'] - 1;
$stmt9 = $this->conn->prepare("UPDATE fun_posts SET downvotes=$newDownvotes WHERE id=('$id')");
$stmt9->execute();
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
Ajax is the perfect answer for your question. Please check out this. you may need to alter this snippet according to your requirement.
before doing this you should import jquery.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
your upvote button should be like this,
<button id="upvote"> upvote </button>
add below snippet in your javascript section.
$(function(){
$("#upvote").click(function(){
$.ajax(
{ url: "fun.php?upvote-btn=true?action=select&image_id=<?php echo $post['id'];?>",
type: "get",
success: function(result){
// todo something you need to perform after ajax call
}
});
});
});
Basically you have to create a php file which will route the call(let's call it a controller) to the intended function. Then create an ajax function which will hit that controller. Have a look at
Ajax Intro
Or look at the Jquery Implementation
I am currently working on a multi-user privat chat-system (pretty similar to the Facebook chat). There is a sidebar with all users and when I click on a user a chat window gets dynamically generated by JavaScript.
The chat window contains a .chat-container with all messages between the selcted user and the logged in user.
The .chat-container has to get updated like every 3 seconds with AJAX, but for some reason I am unable to make it work!
My current try is the following:
Every user-element in the sidebar has a hidden form .chat-ident-form inside it. The form has two inputs "to_user" and "from_user", which values get populated with PHP:
<div class="sidebar-name">
<form class="chat-ident-form" action="./src/assets/widgets/chat-widget/get-messages.php" method="post" onclick="submit_ident_form_via_ajax();">
<a href="javascript:register_popup('<?php echo $member['username'] ?>', '<?php echo $member['username'] ?>');">
<img class="img-circle chat-sidebar-user-avatar" src="<?php echo $member["avatar"]; ?>" />
<span><?php echo $member['username'] ?></span>
</a>
<input type="hidden" name="to_user" value="<?php echo $member['username'] ?>">
<input type="hidden" name="from_user" value="<?php echo $_SESSION['username'] ?>">
</form>
</div>
When the user clicks on a user-element in the sidebar a chat window opens up (which is working!) and then the trouble begins!
I then want to submit the hidden .chat-ident-form to a PHP-Script (at ./src/assets/widgets/chat-widget/get-messages.php) via AJAX. I currently trigger the AJAX with onclick, when the user clicks on the user-element in the sidebar.
The PHP-Script then gathers the massages between the users from the database and echos them as HTML-Code, which I then want to retrieve again via AJAX to display it in the .chat-container.
First things first, the PHP-Script is working. When it gets the neccessary $_POST-Variables it produces the HTML for the messages:
if (isset($_POST["from_user"]) && isset($_POST["to_user"])) {
try {
$from_user = $_POST["chat_user"];
$to_user = $_POST["chat_target_user"];
$query = "SELECT * FROM chat WHERE from_user = :from_user AND to_user = :to_user";
$statement = $db->prepare($query);
$statement->execute(array(':from_user' => $from_user, ':to_user' => $to_user));
$to_messages = $statement->fetchAll(PDO::FETCH_ASSOC);
$from_user = $_POST["chat_target_user"];
$to_user = $_POST["chat_user"];
$query = "SELECT * FROM chat WHERE from_user = :from_user AND to_user = :to_user";
$statement = $db->prepare($query);
$statement->execute(array(':from_user' => $from_user, ':to_user' => $to_user));
$from_messages = $statement->fetchAll(PDO::FETCH_ASSOC);
$all_messages = array_merge($to_messages, $from_messages);
usort($all_messages, "sortFunction");
$html_messages = "";
foreach ($all_messages AS $message) {
if ($message["from_user"] == $to_user) {
$html_messages .= "<div class='chat-massage-container'><div class='chat-massage-a'>". $message["message"] ."</div></div>";
} else {
$html_messages .= "<div class='chat-massage-container'><div class='chat-massage-b'>". $message["message"] ."</div></div>";
}
}
echo $html_messages;
} catch (PDOException $ex) {
echo "An error occured!";
}
}
Sadly the PHP-Skript does not receive the neccessary $_POST-Variables. So there has to be something wrong with the AJAX submitting the .chat-ident-form. It looks like this:
function submit_ident_form_via_ajax () {
$(this).ajaxSubmit(function() {
getMessages();
});
setTimeout(submit_ident_form_via_ajax, 3000);
}
function getMessages () {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
document.getElementsByClassName('.chat-container').innerHTML = request.responseText;
}
};
request.open('GET', './src/assets/widgets/chat-widget/get-messages.php', true);
request.send();
}
Notice that I am using the jQuery Form Plugin for the AJAX. When the submission returns success the getMessages() function is called, which retrieves the HTML from the PHP-Script and displays it in the .chat-container. Well at least in theory it does. In reality, nothing happens. So the form is not submitted by the AJAX and the HTML is neither retrieved from the PHP-Script nor displayed in the .chat-container.
I am pretty new to AJAX and I am completely lost here! What would be the right AJAX to send the .chat-ident-form to the PHP-Script? (Can be with JS, jQuery or jQuery Form Plugin... idc) How should I trigger the submission of the .chat-ident-form? Via onclick - as I currently do - or is there a better way?
And then there is also the question: How do I retrieve the HTML echoed by the PHP-Script and display it in the dynamically generated .chat-container? What is the correct AJAX to do that? When does this happen? Does it happen with the submission or does it happen seperatly? How does it get triggered?
So I need to know two things from you guys:
The right AJAX to send the hidden .chat-ident-form and how to trigger it.
The right AJAX to get the HTML echoed in the PHP-Skript and display it in the dynamically generated .chat-container and also when to do this.
Overall I am just confused and my brain hurts after several hours of thinking about it!!! Maybe there is a much easier way, but I dont see it right now. Or maybe my whole thought process is flawed... =/
Anyways, I tried to explain my problems as well as I could. If anything is missing feel free to ask and please have some mercy (this is my first ever question at StackOverflow).
I would be really happy, if anyone has a solution. =)
I have this ajax_update script that updates file.php every 60 seconds..
Now file.php outputs this after updated a table:
<div id='message' style="display: none;">
<span>Hey, <b><? echo $userid; ?></b>, You've got +1 points, you now have <u>
<? echo $n["points"]; ?></u></span>
X
</div>
<script>
$("#message").fadeIn("slow");
</script>
Why will this only work in FF, i mean appear, but not in IE..
What I am trying to do is that after file.php have updated a field in the database(points), there will come up a message like stackoverflow at the top(just like when you earn a badge) saying that you have received 1 point.
This works perfectly in FF but in IE, the message is not showing at all?
Maybe another way to do this? Or a fix, solution?
I tried to put the little JS script in the index.php and remove the ajax update thing, and it works fine in IE.
function addpoints() {
var userid = document.getElementById('user_id_points');
var postFile = 'addpoints.php?userid='+ userid.value;
$.post(postFile, function(data){
$("#message").fadeIn("slow");
$("#points").html(data);
setTimeout(addpoints, 62000);
});
}
function closeNotice() {
$("#message").fadeOut("slow");
}
my ajax script^
<?php
include "tilslut.php";
$userid = $_GET["userid"];
$s = mysql_query("SELECT points, lastpoint FROM member_profile WHERE user_id = '".$userid."'");
$n = mysql_fetch_array($s);
$tid = time();
mysql_query("UPDATE member_profile set points = points+1, lastpoint=$tid WHERE lastpoint<=$tid-60 AND user_id = '".$userid."'");
if(isset($userid)) {
$e = mysql_query("SELECT points FROM member_profile WHERE user_id = '".$userid."'");
$f = mysql_fetch_array($e);
echo $n["points"];
}elseif (mysql_affected_rows() == 1) {
$s = mysql_query("SELECT points FROM member_profile WHERE user_id = '".$userid."'");
$n = mysql_fetch_array($s);
?>
If you receive this text, no problem with php
<div id="message" onclick="closeNotice()">this works
</div>
<?
}else{
?>
This doesnt work at all
<?
}
?>
my php coding, with the
In your ajax update script, call this after the results are in:
$("#message").fadeIn("slow");
Scripts coming back as part of the request are unreliable, putting the logic in your ajax result function is a better approach in this case.
Try this for your ajax call:
function addpoints() {
var postFile = 'addpoints.php?userid='+ $('#user_id_points').val();
$.post(postFile, function(data){
$("#points").html(data).find("#message").fadeIn("slow")
setTimeout(addpoints, 62000);
});
}
Solved this by adding a
header('Content-type: text/html; charset=utf-8');
in the top in addpoints.php