Optimize jQuery triggered MySQL-Query - javascript

Hello to this great community!
I've already learned a lot by reading many of the questions and answers here. So here is my current problem:
I'm currently creating a simple code which includes PHP, MySQL and jQuery for a simple news ticker. The aim is to check the database for changes without the need of reloading the whole webpage. If there is a change in the database a javascript is executed to reload the whole webpage. With this I want to avoid, that the user has to reload the webpage manually.
This works nicely!
But there is one problem: When too many users are on the webpage a "Too many connections"-Mysql-error occurs. I think this happens because of the many parallel running updates()-functions.
Do you have an idea how to optimize this code?
<script>
function updates(){
$('#updates').load('updates.php');
}
setInterval("updates()", 1000);
</script>
<div id="updates"></div>
updates.php
<?php
// Get latest value the database
$result = mysql_query("SELECT update FROM updates_db");
$row = mysql_fetch_object($result);
// Compare the value from the database with the current value which is saved in a session
if($_SESSION['update'] != $row->update) {
// If the values do not match, update the session and reload the whole webpage
$_SESSION['update'] = $row->update;
echo '<script>
location.reload();
</script>'
}

Try something like this instead of refreshing the whole page.
PHP
<?php
header('Content-type: application/json');
$result = mysql_query("SELECT update FROM updates_db");
$row = mysql_fetch_object($result);
if (($update = $_SESSION['update']) != $row->update) {
$_SESSION['update'] = $row->update;
echo json_encode(['update' => null]);
exit;
}
echo json_encode(['update' => $update]);
Javascript
$.post('updates.php')
.done(function( data ){
if( data.update){
//update DOM with new update
}
});
And increase your timeout interval. One request/1000ms is very frequent.

Related

how to use a php variable in javascript value in mysql query? [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
Actually, I have a javascript variable I pass this to PHP variable and use this variable as a MySQL query when I submit the query the page gets reloaded and value of the javascript variable is finished and therefore query doesn't work
I just want a modification in my code or there is another relevant solution regarding my problem then kindly please help me.
Everything works fine when echo the PHP variable it shows me the variable only problem is in the query of my SQL that in the query the PHP variable which has javascript variable is not working.
<script>
var buttontext="esteem";
<?php
$ff ="<script>document.write(buttontext);</script>";
?>
</script>
<?php
$servername="localhost";
$username="root";
$password="";
$dbname="beelist";
$conn=mysqli_connect($servername,$username,$password,$dbname);
error_reporting(0);
$connDB= mysqli_select_db($conn,'beelist');
if($_POST['sub'])
{
echo $ff;
$code=$_POST['Bid'];
if($code!=""){
$query="SELECT beaconid FROM `customer` WHERE `beaconid` = '$code' && name = '$ff'";
$data = mysqli_query($conn,$query);
$res1=mysqli_fetch_array($data);
if ($res1) {
echo '<script> alert("Beacon found")</script>';
echo '<script> showp();</script>';
}
else {
echo '<script> alert("Beacon ID is wrong!")</script>';}
}else{
echo '<script> alert("Beacon ID is required")</script>';
}
}
?>
As I said in the comments
Where do I start, Client and Server (JS and PHP) are separate. One runs on the server one runs on the clients computer. PHP goes first and as such only PHP can affect JS (as that is part of the output of the PHP) the JS's state cannot be known in PHP as it's on a entirely different computer. Basically you are left with making a request, either from a page reload (such as form submission) or AJAX where you can pass that data back to the server so it can work on it.
Basically what you have now is $ff literally is this text:
$ff ="<script>document.write(buttontext);</script>";
And because you don't echo it, it's actually never passed to the Client as part of the source.
Your query is like this:
$query="SELECT beaconid FROM `customer` WHERE `beaconid` = '$code' && name = '<script>document.write(buttontext);</script>'";
It's too broad of a topic for me to really give you a working answer, and there are plenty of tutorials out there that can do it better justice them me. But hopefully, you understand what is going on now.
PS. you can test this easily by doing echo $query; right after the query. Also be aware you should not put PHP variables directly in SQL, or you risk SQLInjection type attacks against your site. For example if $_POST['Bid']="' OR 1 -- your query would be this:
$query="SELECT beaconid FROM `customer` WHERE `beaconid` = '' OR 1 --' && name = '<script>document.write(buttontext);</script>'";
Where -- is the start of a comment in MySQL. So now I just selected your entire table by injecting SQL commands into your Query, which is a very bad thing.
Cheers!

PHP, Javascript, mysql, and selection lists

I'm working on a piece of some software that will grab information from a mysql database and throw it onto our form dynamically. I'm running into a couple problems, though. I'll give a quick rundown of some functionality.
When the form loads, we have a ton of selection lists. These are all populated through arrays with various keys/values in php. When I select an option from one list, we'll call it a "customers" list, on-click I need to check if that customer has a special flag (stored in the database), and update another selection list based on that data.
How I understand the core of my solution is I need to have a javascript trigger on-click, which I have. The function that is called references a php page that handles the database query through a class and it's function.
<script>
function setService()
{ // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.get('thePage.php?key=setService?customer='+customer);
}
</script>
This function then talks to my php. The CustomerProvider class works 100%. I have tested that thoroughly on other pages. The problem arises when I try to actually get my selection list to change.
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
if ($s != '')
{ ?> <script>var element = document.getElementById('ticket_service');
element.value = 'Contracted Hours';</script> <? }
else return;
}
?>
I'm coding in javascript literally for the first time ever and they kinda just threw me on this project. I know that my portion isn't being read as html or output as I intend. I know that every other part of the php and the first bit of javascript seems to be executing okay. Any help would be incredibly appreciated.
You seem to be on the right track but just for your own sanity here are a couple pointers. You shouldn't be returning Javascript from PHP for a situation like this. Instead you should be relying on Javascript promises to wait for a response containing just the data and continue the execution of your client code once you have your values returned. Take a look at this:
<script>
function setService() { // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.get('thePage.php?key=setService?customer=' + customer, function(data) {
console.log(data + ' was returned from your php script!');
if(data.hasContract=='1')
$('#ticket_service').val('Contracted Hours');
else
$('#ticket_service').val('No Contracted Hours');
});
}
</script>
And then your PHP script will just look like this:
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
if ($s != ''){
$hasContract = 1;
}
else
$hasContract = 0;
echo json_encode(array('hasContract' => $hasContract));
}
?>
Therefore returning only the data needed for the client app to continue... not application logic
Your code isn't doing anything with the output of the PHP script. If you want the output to be inserted somewhere in the DOM, you should use .load() rather than $.get.
$("#someelement").load('thePage.php?key=setService?customer='+customer);
This will put the output into <div id="someelement">. If the output contains <script>, the script will be executed.
If you know the result is just a script, you could use $.getScript() instead of $.get. Then the output should just be the Javascript, not enclosed in HTML tags like <script>.
The problem here is that you are not using the result from the server. Your JavaScript may indeed be correct, but the browser never sees or runs it. From the docs:
Request the test.php page, but ignore the return results.
$.get( "test.php" );
Try this code, which utilizes the $.getJSON() shortcut function. I've written two versions, which you can see commented in the code. One moves the logic for determining contract status into the JS. Either should work.
PHP
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
// Default output
$output = array('hasContract' => false);
// Customer has contract
if ($s != '')
$output['hasContract'] = true;
echo json_encode($output)
// Alternative: PHP just returns getHasContract, JS determines action
// (this would replace $ouput, conditional, and echo)
// echo json_encode(array("hasContract" => $s));
}
?>
JavaScript
function setService()
{ // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.getJSON('thePage.php?key=setService?customer='+customer, function(result) {
// Alternative
// if (result.hasContract != "")
if (result.hasContract)
{
var element = document.getElementById('ticket_service');
element.value = 'Contracted Hours';
}
});
}
As others wrote, your code doesn't do a thing with the GET variables.
the element "ticket_service" doesn't exists on page and even if it was, the code has no impact on the page that sent the request, you should print/echo the result you want to display/return and then manipulate it with JS/Jquery.
since I'm against GET and pro POST which is safer method, here's an example with POST:
JS:
function postSomthing(customerID){
$.post(
'thePage.php',
{key:'setService',customer:customerID},
function(data){
if(data!='x'){
$('#ticket_service').val(data)
}
else{alert('no ticket');/*whatever you want to do*/}
});
}
PHP(thePage.php) :
if(isset($_POST['key']) && $_POST['key'] == 'setService'){
$customer = intval($_POST['customer']);
$s = CustomerProvider::getHasContract($customer);
if ($s != ''){echo 'x';/* false, or whatever you want*/}
else{echo 'Contracted Hours';}
}
notes:
you should create an element with the id "ticket_service" in the viewed page and not in the backstage one.

How to make changes to HTML document permanent using Javascript?

I have a simple like counter code, but the changes made disappear
after the page is refreshed.
Why does this happen, should this be done using PHP ?
How can this code be written much more efficiently, just for the knowledge anyway this is not the main question.
var like=document.getElementById("like__image");
addEventListener("click",function(){
var likeBox=document.getElementById("like__box");
var likeAdd=Number(likeBox.textContent)+1;
likeBox.textContent=likeAdd;
});
According to my understanding, you need this count to be global and to be available to all the users who access your page. Javascript is a client side script and the only file you can create using this is a cookie. In this case, you can't use cookies as it is created separately for each user.
For persistent result use a database or if you are not using a database for your application/website you can use a file (like .txt or .xml) to save your count and next time you can read from that file to display it again. But generally using database is recommended over a file system.
Using file system:
For main file we have a small php code to get the existing like count and an ajax function requesting like.php file when a user clicks on the like button.
HTML body:
<?php
$likeFile = 'like.txt';
/* check if the like file exists*/
if(file_exists($likeFile)) {
/* read the only the first file of the file as we don't intend to have more */
$file = fopen($likeFile, 'r');
$like = fgets($file);
fclose($file);
if($like) {
/* if we get the line split the string "likes=number" and get the existing count */
$likeCount = end(explode('=', $like));
}
} else {
$likeCount = 0;
}
?>
Like <span id="count"><?php echo $likeCount ?></span>
Javascript:
<script type="text/javascript">
function like(){
$.ajax({
type:"POST",
data: {like:true},
url: "like.php",
success: function(result){
$('#count').text(result);
}
});
}
</script>
In the like.php, we are checking for the post variable "like" just to be sure that we don't simply increment the like on direct access to this file. Here we are checking if the like.txt file exists or not. If true, it gets the first line like=1, get the count, increment the count and return it back to the ajax request. If false, it simply creates the file like.txt with like=1 for the first and only time.
<?php
if(isset($_POST['like']) && $_POST['like'] == true)
{
$likeFile = 'like.txt';
/* check if the like file exists*/
if(file_exists($likeFile)) {
/* read the only the first file of the file as we don't intend to have more */
$file = fopen($likeFile, 'r');
$like = fgets($file);
fclose($file);
if($like) {
/* if we get the line split the string "likes=number" and get the existing count */
$likeCount = end(explode('=', $like));
$likeCount++; /* increment the count by one */
file_put_contents($likeFile, 'likes=' . $likeCount); /* write the new count the same file and save it */
echo $likeCount; /* return the like count to the ajax request */
}
} else {
/* if file does not exist create it for the first time with count 1 */
file_put_contents($likeFile, 'likes=1');
echo '1';
}
} else {
return 'Something Wrong!';
}
Hope this is clear enough and helpful for you.
I suggest looking to cookies if you want to keep track of information across page reloads in a simple way. If you want the information to be available to anybody other than the user who created it, you'll likely need some form of server-side persistence such as a database.
The javascript is reloaded when the page is reloaded, so it's natural that the changes are lost as well.
You can, however, store them permanently, either in a web service, or preferrably in localStorage. Then you can retrieve from localStorage on page load.
Using PHP probably wouldn't help without storing it somewhere.
I don't think your code could be written that much more efficient.

Count and display button click on page [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am looking for a very simple solution to tracking and displaying the number of clicks of a button on a webpage. I searched Google and all the solutions I found were far more complicated than what I am looking for.
Basically all I need it to do is track every time a single button is clicked, store the value of total clicks in a database and then display that value on the same page. I'm guessing I will need to use PHP/MySQL to accomplish this, can anyone point me in the right direction?
Thank you!
This can be done with PHP/MySQL/jQuery. I haven't tested any of this code and it won't be very effective at tracking bursts of fast clicks, but it should get you started:
Include jQuery in the footer of your webpage
Include click.js (below) beneath the jquery call
Set up an SQL table called click_log that contains user_id (INT) and time (DATETIME)
Include this code at the bottom of your document. It feeds the increment script a user ID (assuming you have a user's ID handy as variable):
<script>
$(function () {
// Event handler for the click
$(document).click(function(e){
// Feed the increment function the user's ID
increment(<?= $user_id ?>);
});
})
</script>
Include a counter div wherever you want the total count displayed, and include get_count.php in it:
<div id="counter">
<?php include("get_count.php?user_id=".$user_id); ?>
</div>
click.js - jQuery function to call the increment script below via AJAX
$(function () {
// Define an increment function to accept a user_id
function increment(user_id){
// Create a data object
data = {
user_id = user_id
}
// Deliver the payload
$.ajax({
type: "POST",
url: "increment.php",
dataType:"JSON",
data: data,
success:function(response){
$("#counter").empty().load("get_count.php?user_id="+user_id);
}
});
}
}
increment.php - PHP script to register a click in database from an AJAX request
<?php
// Set the header to accept JSON
header("Content-type: application/json");
// Insert your database connection here (should probably use mysqli)
$host = "localhost"; // or IP or whatever
$db_user = "admin";
$db_pass = "password";
$db_name = "your_db";
mysql_connect($servername, $db_user, $db_pass) or mysql_error();
mysql_select_db($db_name) or db_name();
// Grab user id from post data
$user_id = $_POST["user_id"];
// Write the query
$sql = "INSERT INTO click_log (user_id, time) VALUES ('".$user_id."', CURRENT_DATE());"
// Encode a JSON response if the query is successful
if(mysql_query($sql)){
echo json_encode("Success");
}
?>
get_count.php - File to load in your counter div that displays total clicks by user
<?php
// Get the user id from the URL ($_GET)
$user_id = $_GET["user_id"];
// Write the SQL to count the number of rows ('clicks') with that user
$sql = "SELECT count(*) FROM click_log WHERE user_id = '".$user_id."';";
// Run the query
$result = mysql_query($count_sql);
// Format the result and set it a variable
$total_clicks = mysql_result($result, 0);
// Print the total clicks by that user
echo $total_clicks;
?>
Hope this helps get you started! :)
Here is about as simple as it gets for saving a number on the server. http://www.w3schools.com/php/php_ajax_poll.asp Or in other words its not that simple. Try out some code and then ask a more specific question.
Note w3schools isn't the best html resource but it does give
I found a text document solution which fits my needs perfectly. I've implemented it, but the problem is that the action remains in the URL after the button is initially clicked so all you need to do to increase the count is to refresh the page. What would be the easiest way to prevent this?
PHP:
if ( ! file_exists('./count.txt'))
{
file_put_contents('./count.txt','0');
}
if (trim($_GET['action']) == 'increment')
{
counter('increment');
}
function counter($action)
{
if ($action == 'count')
{
return file_get_contents('./count.txt');
}
else
{
file_put_contents('./count.txt', (string) (((int) file_get_contents('./count.txt')) + 1));
}
return true;
}
?>
HTML:
<span id="button">Click Here</span>

how could I automatically update a query php or javascript

I am making a php mysql query, what I want is that actualize automatically each time you enter a data and not have to do it for the browser
this is the query in php:
<?php
include "conexion.php";
$consulta ="SELECT subject,tid,username FROM mybb_threads ORDER BY tid DESC LIMIT 15";
$resultado = mysql_query($consulta)
echo "<table border='0'><td>";
while($fila = mysql_fetch_array($resultado)){
echo " <div >
<a target='_parent' href='showthread.php?tid=".$fila['tid']."'> " . $fila["subject"] ."</a></td><tr><td>Por: " .$fila["username"]."</div><br>";
}
echo '</td></table>';
mysql_close($enlace);
?>
How could I do that automatically actualize?
regards
excuse is that I speak Spanish almost do not understand the English
if you update data automatically
If I understand you correctly, you want the query to be executed automatically each time there is new data in your table or database. Meaning, if you get new information in the table "mybb_threads", you want the user to see this new data without updating the browser.
To achieve this you need to work with Javascript, and something called Ajax. Bascally what you do is that every minute or whatever, you force the browser to call a php file.
You can read more here about the jQuery .ajax() function which is a great place to start:
http://api.jquery.com/jQuery.ajax/
You can also check out the Wiki that explain the method quite good:
http://en.wikipedia.org/wiki/Ajax_(programming)

Categories

Resources