PHP laravel query database every 1 mintue - javascript

I want to query a mysql table in my project in every 1 minute. I used javascript setInterval method for timing and ajax for sending request and receives output as html. but there is many problems with it:
1- whole website goes very slow only for performing this action.
2- with this I can't query something else from database.
my code is :
function ajaxGetAllOrders(){
$.ajax('<?php echo url()?>/admin/getAllOrders',{
dataType:'json',
async: true,
success:function(data){
$('#page-content').html(data.content);
}
});
}
and interval method:
$(function(){
setInterval('ajaxGetAllOrders();',60000);
ajaxGetAllOrders();
});
I tried to create another connection to database for this but it wont help anyway.
and the php getAllOrders method:
public function getAllOrders(){
if (!$this->isAdmin()){
return;
}
$fields = DB::connection('mysql2')->table('z_orders')->orderBy('id','desc')->get();
$nFields = DB::connection('mysql2')->table('z_food_orders')->orderBy('id','desc')->get();
$count=0;
$i=1;
if (count($fields)>0){
foreach($fields as $field){
$userid = DB::connection('mysql2')->table('z_users')->whereId($field->user_id)->first();
$data['username']=$userid->name;
$data['address'] = $userid->address;
$orderId = DB::connection('mysql2')->table('z_food_orders')->whereOrderId($field->id)->first();
$foodId = DB::connection('mysql2')->table('z_foods')->whereId($orderId->food_id)->first();
$data['foodname'] =$foodId->title;
$data['foodcount'] = $orderId->foodcount;
$foodPrice = $foodId->price;
$count += $foodPrice * $orderId->foodcount;
$i++;
}
$cid = DB::connection('mysql2')->table('z_users')->whereId($userid->id)->first();
$data['customer_id'] = $cid->cctt;
$data['price']=$count;
$data['fields']=$nFields;
}
return response()->json(['content'=>view('admin.orders',$data)->render()]);
}
the whole idea behind this is user orders something.then in admin panel in orders section admin can see all orders. so i want to able that admin won't reload page and in every minute the list of orders show new orders.

Related

Update query hangs my website when i want to update rows in database

I'm facing an issue in updating rows in mysql table. I'm currently working on social media website. There's a notification table where we've all users notification.
For example
"John liked your post, Sara commented on your post" Just like this
Table structure is given below.
As you can see i have a column "IsRead". If the user click on "Mark all as read button"
a query executes.
UPDATE notification SET isRead = 1 WHERE toUser = $id
When i execute this query it takes about 2 minutes or above and at the end it says connection to server has been lost. Error snap is attached below
Please suggest me what's the right way to create a table for notification. My created table structure is given above.
This is my javascript code:
function markAsRead(){
$('.notifications-area').html('<li><center>Noting to display</center></li>');
$('.list-notification').html('<li><center>Noting to display</center></li>');
$('#countNotifications').html(0);
$('#countNotifications1').html(0);
$.ajax({
type: 'ajax',
method:'POST',
url: "<?php echo site_url()?>/Main/markAsRead",
datatype:"JSON",
success:function(responce)
{
},
error:function(e)
{
console.log(e);
}
});
}
My Controller:
public function markAsRead(){
$data=$this->m->markAsRead();
echo json_encode($data);
}
Model:
public function markAsRead(){
$userid = $this->session->userdata('userid');
$query = $this->db->query("UPDATE notification SET isRead = 1 WHERE toUser = $userid and isRead = 0");
return $query;
}

php created dynamic links not working in jquery mobile

I have a jqm app I'm working on. I am querying a mysql db to create links, they aren't working . I have read and learned that you cant use location.search in jq mobile, so I have added an attribute data-link in my .
I have a cookie set with the userid, when the user goes to look up recipes, it reads his cookie gets his userid then does a query for all the recipes with the corresponding userid, then displays them.
I would like to be able to click on one of the created links, go to a different page, then do a query with that link id and pull up the actual recipe.
Here is the js I am using to pull up the php file.
$(document).on("pageshow","#retrieve",function(){
var uid1 = $.cookie('recuid');
var uid = uid1.substr(7);
var data;
var response = '';
$.ajax({ type: "GET",
url: "retrieve_recipes.php?userid=" + uid,
dataType: "html",
async: false,
success : function(response)
{
$("#show_recipe").html(response);
}
});
});
Here is the php code used to create the link list.
<?php
include_once('../recipe_holder/connect.php');
$uid = $_GET['userid'];
$sql = "SELECT * FROM recipes WHERE userid = '$uid'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<a href='#showRecipe' class='ui-btn' data-link='".$row['uid']."'>".$row['title']."</a> ";
}
} else {}
?>
Here is the jquery/js code I am using to get the uid of the particular recipe to query the db and display the data. I have this simplified, simply with an alert to display the uid, I figure if I can get that much to work, I can get the rest to work.
$('[data-link]').click(function(){
var uid = $(this).attr('data-link');
alert(uid);
});
any ideas would be much appreciated.
thanks.

Trying to print onto an html page via PHP

I'm making a custom WYSIWYG editor with a save function, and through the save function I have run some code to get everything within a certain div, save it into a data table or overwrite it. But right now, I'm trying to load the page back.
The process is as follows: you press the save button, and it runs a PHP script called save.php, which is seen below.
My issue is that I want it to load or echo the contents within a certain div on the original html page. How would I go about doing that? I need it to work like Javascript's innerHTML function, basically.
Below are the files I use, at least the relevant parts.
test.html:
<form method="post" name="blog-post" id="blog-post">
<input type="hidden" name="postID" value="1"><!--Get the post's id-->
<div class="blog-editor-bar">
<a href="#" data-command='save'
onclick="submitForm('save.php');">
<i class='fa fa-save'></i>
</a>
</div>
<div id="blog-textarea" contenteditable>
</div>
<textarea style="display:none;" id="blog-post-cont" name="post-content"></textarea>
</form>
test.js:
function submitForm(action){
var theForm = document.getElementById("blog-post");
theForm.elements("post-content").value = document.getElementById("blog-textarea").innerHTML;
theForm.action = action;
theForm.submit();
}
save.php:
$conn = mysqli_connect('localhost', 'root', '', '');
if (mysqli_connect_errno()){
echo "<p>Connection Failed:".mysqli_connect_error()."</p>\n";
}
//store stuff in database
//Get Variables
$postid = $_POST['postID'] ? $_POST['postID'] : null;
$post = $_POST['post-content'] ? $_POST['post-content'] : null;
//if exists, overwrite
if($postid != null || $postid != ""){
$sqlSave = "SELECT * FROM wysiwyg.post WHERE idpost = $postid";
$rSave = mysqli_query($conn, $sqlSave) or die(mysqli_error($conn));
if(mysqli_num_rows($rSave)){
$sqlOverwrite = "INSERT INTO wysiwyg.post(post) VALUES(?) WHERE idpost = ?";
$stmt = mysqli_prepare($conn, $sqlOverwrite);
mysqli_stmt_bind_param($stmt, "sd", $post, $postid);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($conn);
} else {
newSave();
}
loadSave();
}
function newSave(){
$sqlNewSave = "INSERT INTO wysiwyg.post(post) VALUES(?)";
$stmt = mysqli_prepare($conn, $sqlNewSave);
mysqli_stmt_bind_param($stmt, "s", $post);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
function loadSave(){
$sqlLoad = "SELECT * FROM wysiwyg.post WHERE idpost = $postid";
$rLoad = mysqli_query($conn, $sqlLoad) or die(mysqli_error($conn));
//This is the part I'm stuck on
}
Thank you all in advance for helping me out! I've been stuck on it for at least a few hours!
EDIT: Before people comment on SQL Injections, I have taken it into consideration. This is me getting the code working on my localhost before I run it through a ton of anti-sql injection methods that I have already done in the past. The code i provide is only important to the functionality at this point.
EDIT #2: The anti-injection code already exists. I guess i seem to have forgotten to provide that information. I repeat, the code I have provided here is only code relating to functionality. I have escaped the strings, trimmed, etc. and more, but that code is not necessary to provide for people to get an understanding of what it is i am trying to do.
You can use an AJAX request to communicate with the server, send data and receive a response. There are many good tutorials out there, but since I first learned it in W3Schools website I am going to refer you there.
JavaScript tutorial.
jQuery tutorial.
You can use an AJAX request which is written like this:
<script>
$(document).ready(function(){
$.ajax({ //start an AJAX call
type: 'GET', //Action: GET or POST
data: {VariableName: 'GETvalue'}, //Separate each line with a comma
url: 'Destination.php', //save.php in your case
success: function(data)){ //if values send do this
//do whatever
}
}); //end ajax request
});
</script>
This allows you to send information to your php page without refreshing
So in my example you can do this on the PHP side
<?php
echo $_GET['VariableName'];
?>
Will echo out "GETvalue as specified in the data section of the Ajax call"
EDIT************
In the AJAX call you can add dataType if you want json
$.ajax({
type: 'GET',
data: {VariableName: 'GETvalue'},
dataType: 'json' // Allows Json values or you can change it to whatever you want
url: 'Destination.php',

Error updating webpage elements in real time with JavaScript

I am working on a webpage that shows the amount of online players on a game server that I am running, that is updated in real time.
The problem is that I can get the amount of players online in the game server to display, but it never updates and always shows the amount of players that were on the server when the page was loaded although people leave and join the server every second.
This is the PHP code that shows the numbers (it's simple, just for testing):
<?php
echo "<a id='a1' href='#' class='online'>Loading...</a>";
?>
What I am doing is to update 'a1' every second with the new amount of online players using javascript, which calls a php function called getplayers():
<script language="JavaScript">
setInterval(function(){
document.getElementById("a1").innerHTML = '<?php echo getplayers()?>';
}, 1000);
</script>
The function getplayers() it's exactly this:
<?php
include "Status.php";
function getplayers() {
$serverb = new Status("mc.spainpvp.com", '25565');
return $serverb->online_players;
}
?>
Lastly, Status.php is a script that gets the amount of players online and more things about the server, which I am sure that works:
<html>
<?php
class Status {
public $server;
public $online, $motd, $online_players, $max_players;
public $error = "OK";
function __construct($url, $port = '25565') {
$this->server = array(
"url" => $url,
"port" => $port
);
if ( $sock = #stream_socket_client('tcp://'.$url.':'.$port, $errno, $errstr, 1) ) {
$this->online = true;
fwrite($sock, "\xfe");
$h = fread($sock, 2048);
$h = str_replace("\x00", '', $h);
$h = substr($h, 2);
$data = explode("\xa7", $h);
unset($h);
fclose($sock);
if (sizeof($data) == 3) {
$this->motd = $data[0];
$this->online_players = (int) $data[1];
$this->max_players = (int) $data[2];
}
else {
$this->error = "Cannot retrieve server info.";
}
}
else {
$this->online = false;
$this->error = "Cannot connect to server.";
}
}
}
?>
</html>
So my question is if someone knows why it always updates with the first number of players instead of putting the new number of players?
You can not call PHP functions by Javascript. PHP is processed on a server in time of request. No piece of PHP code will be visible in response, because it's already processed.
So your javascript code will actually look like:
<script language="JavaScript">
setInterval(function(){
document.getElementById("a1").innerHTML = 'XXXXX';
}, 1000);
</script>
where XXXXX is amount of players in the time of request.
So your code will every second replace elements innerHTML with the static content.
If you want to get new amount of players every second, you need to use Ajax.
You can create request on your own using XMLHttpRequest or you may use some library like jQuery and it's $.ajax method.
You also need a PHP code on a server that will provide such information.

Ajax call posting duplicates in DB

I am using to Fullcalendar jquery with php for event management. I using ajax call for adding events. The call works fine for the first event entry after refresh. But for the following event entries duplicate events are created for each entry. Not sure what causing this.
This is the error:
This is the jquery call:
Jquery
$('#evesav').bind('click',function(){
$('#evesav').attr('disabled','disabled');
var title = $('#evename').val();
var edes = $('#evedes').val();
var everegion = $('#everegion').val();
var eveserv = $('#eveserv').val();
$.ajax({
url: 'add_events.php',
data: 'title='+ title+'&start='+ start +'&end='+ end +'&edes='+ edes +'&everegion='+ everegion +'&eveserv='+ eveserv,
type: "POST",
success: function(json) {
$('#myModal').modal('hide');
$('#alertcon').html(json);
$('#alert').modal('show');
$('#evename').val("");
$('#evedes').val("");
$('#evesav').removeAttr('disabled');
$('#calendar').fullCalendar( 'refetchEvents' );
}
});
$('#calendar').fullCalendar( 'rerenderEvents' );
});
This is the PHP Code:
PHP
<?php
if(($_POST['title'] && $_POST['start'] && $_POST['end'] && $_POST['edes'] && $_POST['everegion'] && $_POST['eveserv'])!= NULL)
{
// Values received via ajax
$title = $_POST['title'];
$start = $_POST['start'];
$end = $_POST['end'];
$edes = $_POST['edes'];
$region = $_POST['everegion'];
$server = $_POST['eveserv'];
//echo $title."".$start."".$end."".$edes."".$region."".$server;
// connection to the database
include('includes/db.php');
// insert the records
$sql = "INSERT INTO evenement (title, start, end, edes, region, server) VALUES (:title, :start, :end, :edes, :region, :server)";
$q = $bdd->prepare($sql);
$q->execute(array(':title'=>$title, ':start'=>$start, ':end'=>$end, ':edes'=>$edes, ':region'=>$region, ':server'=>$server));
if($q->execute(array(':title'=>$title, ':start'=>$start, ':end'=>$end, ':edes'=>$edes, ':region'=>$region, ':server'=>$server))){
var_dump($q->execute(array(':title'=>$title, ':start'=>$start, ':end'=>$end, ':edes'=>$edes, ':region'=>$region, ':server'=>$server)));
}
$eveid=$bdd->lastInsertId();
// Get array of all source files
$files = scandir("uploads/");
// Identify directories
$source = "uploads/";
$destination = "evedata/".$eveid."/";
mkdir("evedata/".$eveid);
// Cycle through all source files
foreach ($files as $file) {
if (in_array($file, array(".",".."))) continue;
// If we copied this successfully, mark it for deletion
if (copy($source.$file, $destination.$file)) {
$delete[] = $source.$file;
}
}
// Delete all successfully-copied files
foreach ($delete as $file) {
unlink($file);
}
echo "Added Successfully";
}
else {
echo "Please Fill the data";
}
?>
Some one please help me with this.
I'd give each event addition form a control, for instance a dynamic GUID, which then can be used to save to DB. This way you have a GUID to work with in dealing with CalDAV protocol, if you ever choose to do as such with your calendar, as well as have a way to make certain nothing is duplicated by chance in your database.
Now, do keep in mind this is simply a patch, not a fix. Therefore, you'll do yourself a lot of good to find a way to stop the multiple attempts to add an event to your DB. Regardless of your success in finding your bug, using a control mechanism or unique identifier is a good idea.

Categories