Update php query limit whit js when load more - php

Hi I'm working on a reverse infinite scroll for a private message module.
The think is everything is working okay, my only problem is that I am not being able to update the limit of the query I am using.
The thing is a create the max and limit in php:
$max = mysql_num_rows($q_mensajes_contador_cargar);
$limit = $max-5;
Then when I use the infinite scroll I send the max and limit this way
$.ajax({
url: "formularios/cargar_mensajes.php?id=<? echo $id_receptor;?>&limite=<? echo $limit;?>",
success: function (html) {
if (html) {
$("#profile-feed-1").prepend(html);
$('div#loadmoreajaxloader').hide();
} else {
$('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
}
}
});
The thing is when I get this values in cargar_mensajes.php it just works once cause it is continually updating the same thing over and over, I want it to detect when it printed the next messages and update the query to show more or not show more depending in how many times it updates.
Sorry for my english...
Any advice, my js level is basic and I am sure that the way I am thinking this must not be the correct, just would like to know how can I achieve this.
Thank you!

You're setting the limit using PhP, so it never changes.
What you could do is :
var limit = <?php echo $limit; ?>
...
url: "formularios/cargar_mensajes.php?id=<? echo $id_receptor;?>&limite=" + limit,
success: function(html)
{
limit = limit + 5; // (Or -5, or whatever you need.)
Tell me if you need a more detailled code.

Related

pass complex text to JQuery

I have ran into a strange behavior of passing JSON from PHP to jQuery.
I have some articles (Drupal CMS articles) and I need to push them into the environment.
First solution worked, while the articles was pushed directly by PHP on page load. But as my work works with more than one CMS, it takes too much time to load them all, so I need to use ajax to load one specific project at time.
now, jquery looks like this:
function doLoadArticles() {
for (var i = 0; i< projectdata[1].length; i++){
$.ajax({
data: {ip:projectdata[0]["ip"], login:projectdata[0]["login"], pass:projectdata[0]["pass"], db:projectdata[0]["db"], datatype:projectdata[1][i], aj:"aj", fc:"doLoadArticles"},
type: "post",
url: "dataFunnel.php",
success: function(data){
console.log(data);
//console.log(jQuery.parseJSON( data )) ;
}
});
}
}
Then, on PHP side is this code:
function doLoadArticles(){
$projdata;
$conn = new mysqli($_POST['ip'], $_POST['login'], $_POST['pass'], $_POST['db']);
// Check connection
if ($conn->connect_error) {
die("<div style='position:absolute; top:0;left:0; background:white;'>Connection failed: " . $conn->connect_error." <br><br>Plese try reload the page</div>");
break;
}
else{}
$sql = "Select node_revision.title, node_revision.nid, node.language, field_revision_body.body_value, field_revision_body.bundle, node_revision.timestamp
from field_revision_body
LEFT JOIN node_revision ON field_revision_body.revision_id=node_revision.vid
LEFT JOIN node ON field_revision_body.revision_id=node.vid
where field_revision_body.bundle='".$_POST['datatype']."' AND node_revision.status=1 AND node.language='cs'
ORDER BY field_revision_body.revision_id DESC LIMIT 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// error_log("true");
// output data of each row
$j =0;
while($row_a = $result->fetch_assoc()) {
$projdata[$j]["title"] = $row_a["title"] ;
$projdata[$j]["timestamp"] = $row_a["timestamp"] ;
$projdata[$j]["bundle"] = $row_a["bundle"] ;
$projdata[$j]["body_value"] = $row_a["body_value"];
$projdata[$j]["nid"] = $row_a["nid"];
$projdata[$j]["language"] = $row_a["language"];
$j++;
}
}
echo json_encode($projdata);
}
The problem is, that the data are there, only the passing itself does not work .. (probably because of some buged conversion?)
if I do
echo print_r($projdata);
it will pass the data, but not in usable way (ignore the broken chars, that is another not related problem, the data are thare, that is what matters)
However, as it is clear, I need it in form that I can work with, so I need json.
But if I use
echo json_encode($projdata);
it will pass some "broken nothing"
So is there any my mistake I am not aware of, or it is really some kind of bug in PHP implementation?
(by the way, I run on PHP 5.6 on MS IIS7)
Or any other way possible, how to load data dynamically without the json conversion?
Thanks in advance

Ajax call/response too long

First sorry for my bad english, i'm a new user but i read long ago this site and help me many problem resolve. Thanks all for this. Now unfortunately i dont find resolve for my problem.
I dont know why 2000 ms my all ajax call. All at same what thing the called .php file.
I try a lot of technique to resolve this but not help.
The task is refresh many div content in "real time" with database syncronization.
The site contains some timer. When the timer text equal 00:00:00 i call the update script.
my ajax call:
$(function() {
function update()
{
$.ajax({
type: "GET",
url: "ajax/update.php",
async: true,
success: function() {
update();
}
});
}
update();
});
my update php:
include 'inc/config.php';
include 'inc/conn/connopn.php';
$sDataForSync = "";
$iRowsNum = 0;
$sGetDataQuery = mysql_query("select `AID`, `PN` FROM `my_table1`;");
if (mysql_num_rows($sGetDataQuery ) > 0) {
while ($row = mysql_fetch_array($sGetDataQuery )) {
$iRowsNum++;
if ($iRowsNum == mysql_num_rows($sGetDataQuery )) {
$sDataForSync .= $row['AID'] . "|" . $row['PN'];
} else {
$sDataForSync .= $row['AID'] . "|" . $row['PN'] . PHP_EOL;
}
}
}
file_put_contents("updates.txt",$sDataForSync );
/* for now only write to text file, but later i would like to update in database */
include 'inc/conn/conncls.php';
The table contains max 30-40 rows and i using indexes, but still 2 seconds the response.
I need 200-400 ms, max 500ms responsetime with prospective mysql update query.
firefox results
Please help me decreases the time.
Thanks for all!
SOLVED. 1 sec is my fail. I left the second parameter from mysql_query. mysql_query("select",$dbconn); The another second is my web server fail. Too slowly. The mysql_connect(); is 1 second in localhost but on the remote server the full operation is 50-80 ms. Thanks for all the posts.

Counting clicks changing link href

I asked this question but did not explain it thoroughly. I have a regular link:
Click Me
I want the change the href after the link is clicked 10 times not by the individual use but clicked 10 total times by all users.My jquery is obviously flawed but here is what i have:
var count = 0;
$(document).ready(function(){
$('a').click(function(){
count++;
if(count > 10){
$('a').attr("href","https://www.yahoo.com");
}
});
});
I am new to jQuery but from what ive read cookies and local storage store individual users information not the total websites information. So how could i use ajax with a database to do this? maybe even php?
You have a huge fundamental misunderstanding of how JavaScript works.
Firstly, when someone clicks that link, they're going to be navigated away from your page unless you do something to prevent that (e.preventDefault or return false in jQuery). Once they're navigated away, your counter is lost because is stored locally, in memory, for the life of the page.
Secondly, even if the counter wasn't cleared, or you stored the counter in a cookie, or localStorage, it will only count for a single user. If you want to count the clicks by all users, you're going to have to do that server side. i.e., in PHP.
So... how do we do that? Well, as I said before, when a user clicks that link, they're going to be sent to Google. Your site will have no knowledge of what has occurred.
We have two options to deal with this. We can intercept the click, and use AJAX (more appropriately "XHR") to send a request back to your server, where you can log the click, before forwarding them off to Google.
Or, you re-write the URL to something like /log_click.php?forward=http://google.com. Now when the user clicks the link, they will actually be sent to your log_click.php script, where you can log the click to your database, and then use $_GET['forward'] in combination with header('location: ...') to forward them off to their destination. This is the easiest solution. Through some JavaScript hackery, you can hide the link so that when they mouse over it, they won't even know they're being sent to your site (Google does this).
Once you've accumulated your 10 clicks, you again use PHP to write out a different HTML link the next time someone views that page.
HTML
<a href='http://www.google.com' data-ref='99'>Click Me</a>
Javascript
$("a").click(function() {
var _this = $(this);
var ref = $(this).data('ref');
$.ajax({
url: '/click_url.php',
type: 'POST',
data: {id:ref}
success: function(href) {
if(href != '')
_this.attr("href",href);
}
});
}
PHP (click_url.php)
if($_POST['id'] > 0){
$id = $_POST['id'];
//count increment
$sql = "UPDATE table SET count = count + 1 WHERE id = '$id'";
mysql_query($sql);
//get row count
$sql = "SELECT * FROM table WHERE id = '$id' LIMIT 1";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
//if count > 10 , return new url
if($row['count'] > 10){
die($row['href']);
}
}
While clicking the link you can call an ajax request and increment the count in the server. So that u should remove link from href and call manually by using javascript window.location.href each time. Hope that helps
var count = 0;
$(document).ready(function(){
$('a').click(function(e){
e.preventDefault();
count++;
if(count > 10){
$('a').attr("href","https://www.yahoo.com");
}
});
});
and use ajax like below
//send set state request
$.ajax({
type: "POST",
contentType: "text/xml; charset=utf-8",
datatype: "xml",// you can set json and etc
url:"your php file url",
data: {test:test1},// your data which you want to get and post
beforeSend: function (XMLHttpRequest) {
// your action
},
success: function (data, textStatus, XmlHttpRequest) {
// your action },
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
for more deatils see Ajax
Mark's answer is more useful, even you want to implement for the sake of some constraints then try below with jQuery 1.9
I have implemented for 3 clicks, AFAIU you need to change the URL on every 3rd successive click
var c=0;
$(document).on('click', 'a#ten', function(e){
c++;
alert('clicked ' + c + ' times');
if(c%3 == 0) {
$('a').attr("href","https://www.yahoo.com");
alert('changed');
c = 0;
}
e.preventDefault();
})
working DEMO
You must save no of times that link has been clicked in the database with php. when you render the link(with php) check the no of times it has been called before and decide what link to render.
Click Me
write this javascript in the page wher you place your link
$(function()
{
$('.mylink').click(function()
{
$.ajax({
type: "POST",
url: "listening/end/point", // enter your counting url here
async: false
);
});
});
And in server on the listening end point write php script to store no of times that link has been called.

Real time data updates with comet and PHP?

I'm looking to implement real time notification updates on my social networking website. I have done some research on comet and i'm really fascinated by it.
From what I understand, this is the basic flow of what happens on a comet server.
Webpage:
Sends an ajax request to server when the document is ready.
Server:
Queries the database every x amount of seconds and returns a json string containing results if any are found.
Webpage:
Receives the result of the json string from the server and sends out another ajax request to do the above process again.
By understanding the flow of how comet works, I've written some PHP and Javascript code.
The JavaScript code uses the jQuery library and sends an ajax request out to the server with the current time in a unix timestamp format as a GET parameter.
$(document).ready(function(){
var timestamp = Math.round(new Date().getTime() / 1000);
function comet2(){
$.ajax({
type : 'GET',
url : 'comet.activities.php?timestamp=' + timestamp,
async : true,
cache : false,
success : function(data) {
alert("current timestamp "+timestamp)
var json = JSON.parse(data);
if(json !== null){
alert(data);
}
timestamp = json[0].timestamp;
setTimeout('comet2()', 1000);
},
error : function(XMLHttpRequest, textstatus, error) {
setTimeout('comet2()', 15000);
}
});
}
//call the comet function because the page has loaded.
comet2();
});
The PHP code will query for new activities by searching the database for new rows by using a timestamp paramater (in this case, a unix timestamp in a query). For this example, I have limited the amount of results to 1.
<?php
set_time_limit(0);
include("models/config.php");
global $mysqli,$db_table_prefix;
$last = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$results = null;
$flag=true;
$stmt = $mysqli->prepare("SELECT id,timestamp FROM uc_user_activity WHERE timestamp > ? ORDER BY timestamp DESC LIMIT 0,1");
$stmt->bind_param("i", $last);
$stmt->bind_result($id,$timestamp);
while($flag){
$stmt -> execute();
while ($row = $stmt->fetch()){
$flag = false;
$results[] = array(
"id" => $id,
"timestamp" => $timestamp
);
}
$stmt -> close();
usleep(100000);
clearstatcache();
}
echo json_encode($results);
?>
The code above doesn't actually 'work' The problem is that if a user posts a new comment, it will fail to add to the database when the comet script is running. This means that the comet script will never return any json result because the statement in the sql query is never met (no new activities are added with a newer timestamp). My ajax code for posting new comments is working 100%, so I know that isn't the problem. Simply 'nothing happens', that is - nothing (no errors) are alerted or outputted to the browser console.
Edit number 3:
I'm seriously struggling to explain what I mean by 'nothing is happening', so I have uploaded an image showing that the database insert fails when the comet script is being called from jquery (notice how the textbox is disabled whilst the comment is being posted via ajax).
What can I do about this? I've spent hours searching the internet trying to fix this/find a similar working example with no avail.
If I change the query in my PHP code to be:
$stmt = $mysqli->prepare("SELECT id,timestamp FROM uc_user_activity WHERE timestamp **<** ? ORDER BY timestamp DESC LIMIT 0,1");
instead of:
$stmt = $mysqli->prepare("SELECT id,timestamp FROM uc_user_activity WHERE timestamp > ? ORDER BY timestamp DESC LIMIT 0,1");
results are instantly alerted to the browser window, comments can be posted again and the script is called again and new posts are displayed. This shows that my code 'is working' fine afterall and it looks like the query is causing the problem...
Can anyone see what is going on here? I have edited this question 7 times now and any guidance would be great as I'm just getting nowhere.
Just so this doesn't get closed, here is my question to round up what I have discussed above:
Are there any better ways of implementing a comet server? I'm not the
most experienced guy ever, but I would really like to learn how to do
this. It seems StackOverflow has this functionality and it works
perfectly - how are they doing it?
I can't possibly write my post in any further detail than this and I would REALLY appreciate some guidance from you awesome people. A suggestion as to why my code 'isn't working' or links to any tutorials explaining how to implement this would be amazing! Thanks in advance and apologies for this monster of a question and all of the edits!
My hunch is that the timestamp value which you are passing returns no results. You get the current time through Javascript. The query queries for all posts after this timestamp.
Can you try to print the query and run the same query manually to ensure that it retrieves data from the DB?
So, for the best available tutorial for Comet with PHP is here.
http://www.zeitoun.net/articles/comet_and_php/start
Like it, if it helps :)
For those who want to use the simple chat solution above in the link with jQuery here is the solution.
<script type="text/javascript">
var Comet = {};
Comet.jquery = {
timestamp: 0,
url: './backend.php',
noerror: true,
initialize: function () {
},
connect: function ()
{
this.ajax = $.ajax({
type: "get",
url: this.url,
data: {timestamp: this.timestamp},
success: function (data) {
// handle the server response
var response = JSON.parse(data);
console.log(response);
//alert(response.timestamp);
Comet.jquery.timestamp = response.timestamp;
Comet.jquery.handleResponse(response);
Comet.jquery.noerror = true;
},
complete: function (data) {
// send a new ajax request when this request is finished
if (!Comet.jquery.noerror) {
// if a connection problem occurs, try to reconnect each 5 seconds
setTimeout(function () {
Comet.jquery.connect()
}, 5000);
}
else {
Comet.jquery.connect();
}
Comet.jquery.noerror = false;
}
});
},
disconnect: function ()
{
},
handleResponse: function (response)
{
$('#content').append('<div>' + response.msg + '</div>');
},
doRequest: function (request)
{
$.ajax({
type: "get",
url: this.url,
data: {'msg': request}
});
}
}
</script>

Checking multiple fields from mysql with jquery AJAX in one call

I've got a page that seems to be in full working order, but I'm having major performance issues (think 30 second delay occasionally from these calls) from what I assume is throwing too many individual POST requests to the server.
Am I right in thinking that there's some way of doing it all in one call and that doing so would improve performance, and what's the easiest way of doing it? Perhaps my use of eval() is part of the problem - or maybe my webhost is just shit.
function startCheckAchs(){
//hide the loading alert
$(document).ajaxStop(function(){
$(this).unbind("ajaxStop");
popup('loadingAlert');
});
//load lifeTimeBaked
lifeTimeBaked = loadAch("lifetimebaked");
loadAch("ach_started", "#achStarted", "achstarted");
loadAch("ach_round1", "#achRound1", "achround1");
loadAch("ach_round2", "#achRound2", "achround2");
loadAch("ach_round3", "#achRound3", "achround3");
if( rewards == 1) {
loadAch("ach_baked100", "#achBaked100", "achbaked100");
loadAch("ach_baked500", "#achBaked500", "achbaked500");
loadAch("ach_baked1000", "#achBaked1000", "achbaked1000");
loadAch("ach_nobread", "#achNoBread", "achnobread");
loadAch("ach_nodough", "#achNoDough", "achnodough");
loadAch("ach_noflour", "#achNoFlour", "achnoflour");
loadAch("ach_allach", "#achAllAch", "achallach");
}
}
function loadAch(ach, achDiv, achVar){
$.ajax({
type: "POST",
url: "scripts/loadach.php",
data: {"achievement" : ach},
dataType: "text",
success: function(result){
if ( achDiv && achVar && result == 1){
$(achDiv).show();
eval(achVar + " = 1");
return result;
} else {
return result;
}
}
});
}
Loadach.php:
$achievement=trim($_POST['achievement']);
$user = $_SESSION['userid'];
$query = "SELECT $achievement FROM breadusers WHERE userid='$user'";
$link =#mysql_query($query);
if(!$link){
die('Could not query:' . mysql_error());
}
echo mysql_result($link, 0);
?>
You are currently loading achievements individually, while you should be doing something like:
<?php
$query = "SELECT ach_started, ach_round1 FROM breadusers WHERE userid='$user'";
$link = mysql_query($query);
$results = mysql_fetch_assoc($link);
echo json_encode($results);
?>
Then, in your javascript code, parse the JSON response (setting dataType: "json" should work), loop over the returned object (has keys such as ach_started, ach_round1, etc etc), and show/hide divs as needed.
Unfortunately you are going to have to redesign that.
SQL queries are slow.
Lots of requests make things slow.
See if you can group all of the data for a user in your database. That way you can make one select for all of the data you need.
You could use a multi-dimensional array and fill it with the data needed, send the array with ajax to the php code, and then you could loop through the array in the php code and echo back the desired results.
This way you would only be making 1 ajax call each time but still get the same results. might be faster this way but i have not tested this. =)
Most browsers have a limit on the number of concurrent server requests they can handle.
If you're using sessions, you'll also find that the server can only process a single request for each session at a time, because the session file is locked by each request, and subsequent requests must wait for it to be unlocked either when the first request finishes, or when a session_write_close() is issued by the executing request.

Categories