Ask db information every tot seconds - javascript

I'm trying to refresh data on my web page according to the data stored in the database, so every 2 seconds I call with an ajax request a php file. The called php script is this:
session_start();
.....Connection to the db.......
$prova = pg_query($connect, "SELECT * FROM maxdistance");
$prova2 = "";
while ($row = pg_fetch_row($prova)) {
$prova2 = $prova2.$row[0].$row[1].$row[2];
}
$_SESSION['prova'] = $prova2;
And this is the code in javascript:
var intervalId = window.setInterval(function(){
newPositions();
}, 2000);
function newPositions(){
$(document).ready(function(){
$.ajax({
type: "POST",
url: "realTimePosition.php",
success: function(msg){
provaaa = <?php echo ($_SESSION[prova]); ?>;
}
})
});
The problem is that, when I refresh the page the code run and in the variable provaaa is stored the value 20 (the actual value in the db) but if I modify the value in the db, the value of the variable is the same, why is this happening?

you cant mix JS and PHP like this
problem part
provaaa = <?php echo ($_SESSION[prova]); ?>;
solution
your PHP script have to send back REPLY with "echo"
echo json_encode([ 'data' => $prova2]);
then y have to catch server response inside your "success" callback dunction where param is RESPONSE from server so
success: function(res){
provaaa = JSON.parse(res).data;
}

Related

How to pass JavaScript values to PHP within the Ajax

Here is the situation.
I'm trying to pass from some Javascript values to various PHP functions within my ajax so it can properly be displayed on the page.
Here is my code:
$("[data-department-id]").click(function() {
id = $(this).attr('data-department-id');
document.getElementById('department'+id).innerHTML = '';
$.ajax({
url:"/desk/template/fetchtickets.php",
type: 'POST',
dataType: 'json',
data : {
'id' : id
},
success: function (res) {
$('#department'+id).append('<ul>');
for (var key in res) {
var ticketId = res[key].id;
var clientId = res[key].clientid;
var clientName = res[key].name;
var clientColor = res[key].hexColor;
<?php $ticketId = '"+ticketId+"'; ?>
<?php $clientId = '"+clientId+"'; ?>
<?php $clientName = '"+clientName+"'; ?>
<?php $clientColor = 'clientColor'; ?>
$('#department'+id).append('<li class="list-group-item list-group-item-light" data-date-2="<?php echo Ticket::lastReplyStamp($ticketId); ?>"> <span class="text-width">'+res[key].ticket+' '+res[key].subject+'</span><div class="tools" ><span class="client-listing"> <?php clientBadge($clientId,$clientName,$clientColor); ?> <?php // echo "<scipt>document.writeln(test)</script>"; ?> '+test+' </div></div></li>');
}
$('#department'+id).append('</ul>');
}
});
})
When I do a console.log();
It shows the proper value, however, when I do an echo $ticketId, it shows +ticketId+ .
Now I did do a document.write and document.writeln and it still doesn't work.
Is there a proper solution to resolve my problem?
You can not add php code here.You can use JQuery to change value in the Dom or set some hidden inputs value, but you can not set php variable in JS. PHP runs on the server side. When the php code is running, your js code is waiting to be run on the client's computer.
These line are always going to be interpreted as string assign from server side.
<?php $ticketId = '"+ticketId+"'; ?>
<?php $clientId = '"+clientId+"'; ?>
<?php $clientName = '"+clientName+"'; ?>
<?php $clientColor = 'clientColor'; ?>
The order of your code processing is something like this :
PHP code get processed
PHP returns HTML
User clicks an element (in your case data-department-id)
JQuery sends ajax request
Server processes the request and sends response back to the frontend
Ajax success function receives the response and now has the response in javascript variable res which is passed as argument of success(res) function
All the code inside success is executed
Alternatively if the server throws an error response, no 6. and 7. would trigger the error callback
But the main part it, the PHP code in your success() function will NOT run as you are thinking, which is after the Ajax receives response. At this point all you can do is use javascript to manipulate the variables.
So in short, change below part and use javascript or jQuery if you have it to change DOM elements based on response.
<?php $ticketId = '"+ticketId+"'; ?>
...
...
For example, let's say you have an H1 tag which shows ticket id. You would do
// jQuery
$('#ticketIdElement').text(res.id);

PHP echoing into JavaScript value "0" even when value is not "0" after POSTing with AJAX

I have button that is using AJAX post method to post value into PHP.
When I echo that value back in JavaScript it's always echoing 0, even when I am 100% sure that value in PHP is not 0.
Here is JavaScript:
function slanje(br){
$.ajax({
type: 'POST',
dataType: 'html',
data: {
'broj' : br,
}
});
}
function otvaranje(id, broj){
slanje(broj);
var testNumber = <?php echo $br; ?> + "";
And PHP (I do file write to check if PHP received correct value):
if(isset($_POST['broj'])){
$br = $_POST['broj'];
$file = fopen($br . "broj.txt", "w");
fclose($file);
}
Here is what value I get back in Javascript:
And here is value in PHP:
Edit 2: I want to post variable in PHP, than get value of element of PHP array with index I passed with ajax. And that without reloading page. I didn't include array part because while I was testing around I couldn't even make it echo back variable I'm passing using AJAX.
If you want to do it using AJAX, then let your PHP script return the POSTed value and grab it in the success handler of the AJAX request.
For the success handler to be able to change the value of testNumber, the variable has to be declared outside of function otvaranje.
Here are the necessary modifications (also take note of the comments I added):
PHP
if(isset($_POST['broj'])){
$br = $_POST['broj'];
$file = fopen($br . "broj.txt", "w");
fclose($file);
// Just output the value and exit
// If there is business logic doing something with
// $br, then move this after that code.
// But remember to only do this if the script was
// called with POST, otherwise the initial request
// wouldn't work anymore.
print $br;
exit;
}
JavaScript
var testNumber = "<?php echo $br; ?>";
function slanje(br){
$.ajax({
type: 'POST',
dataType: 'html',
data: {
'broj' : br,
},
success: function(data) {
// called when the request succeeded
testNumber = data;
}
});
}
function otvaranje(id, broj){
slanje(broj);
// move outside: var testNumber = <?php echo $br; ?> + "";
// rest of function content
}

converting Javascript variable to PHP variable in two different php file

Can some body help me get the current value from this option tag
to account.php as a session variable or anything ..
// loadsubcat.php This code is for dependent dropdown
$query = mysql_query("SELECT * FROM table_cmsjob WHERE VesselID= {$parent_cat}");
while($row = mysql_fetch_array($query))
{
echo "<option value='$row[jobName]'>$row[jobName]</option>";
}
var javascriptVariable = $('#sub_cat').val();
I know this can be solve using ajax but I don't know how.
I will use the javascript variable as a reference for a couple of checkboxes under it but first must be passed as a php variable.
you ajax will look like this,
$.ajax({
type: 'POST',
url: "account.php",// path to ajax file
data: {javascriptVariable:javascriptVariable},// you can pass values here in key value pairs.
success: function(data) {
alert(data);
}
});
You can send n number of key => value pairs.
like
parent_cat:100
Next:
echo $_POST['javascriptVariable']; // <--- grabbing ajax data here
$query = mysql_query("SELECT * FROM table_cmsjob WHERE VesselID= {$parent_cat}");
while($row = mysql_fetch_array($query))
{
echo "<option value='$row[jobName]'>$row[jobName]</option>";
}
what ever echoed in php file will come in ajax success data,
alert(data) will alert what you had echoed in php. you can use that in your html file.

Array json between ajax and php

I'm developing a simple guestbook and I want to update the table with all messages without refreshing the page because if someone it's writing a comment and the page refreshes the comment will be lost.
So I began writing some code with ajax to update the table but I don't know how to send an array (with comment, username, date ecc) from php to ajax.
In the database I have a column named "wrote" and it can be 0 (unread) or 1 (read). 1 it's when the messages it's already on the table.
This is what I've done since now, maybe it's wrong
getGuest.php
<?php
include("Database.php");
$Database = new Database( "localhost", "root", "1234");
$Database->connectToServer();
$Database->connectToDatabase("test");
$result = $Database->unreadMessages();
$rows=mysql_fetch_array($result);
echo json_encode($rows);
?>
Script.js
window.onload = function(){
interval = window.setInterval('updateGuest()',5000);
}
function updateGuest() {
$.ajax({
url: 'getGuest.php',
method: 'get',
success: on_getGuest_success,
error: on_error
});
}
function on_getGuest_success(data) {
for(var i=0; i<data.length;i++) {
// HERE I WANT TO ADD A ROW WITH ALL MESSAGE UNREAD BUT I DONT KNOW WHAT I HAVE TO DO
}
}
function on_error() {
//do something
}
Make sure the JSON contains an array
Add headers
use getJSON
Like this:
PHP
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
header("content-type: application/json");
echo json_encode($data);
JS:
$(function() { // when page has loaded
var tId = setInterval(function() { // save the tId to allow to clearTimeout if needed
$.getJSON("getGuest.php",function(data) { // call the server using jQuery's JSON access
$('.guestbook').empty(); // empty the container
var rows = []; // create an array to hold the rows
$.each(data,function(_,item) { // loop over the returned data adding rows to array
rows.push('<tr><td class="name" width="10%">' + item.name + '</td></tr>');
});
$('.guestbook').html(rows.join()); // insert the array as a string
});
},5000); // every 5 secs
});
I would personally only return what was new since last time

How to get the variables in php page sent from previous page via ajax call

I am making an ajax call from one php page to second.in which i m sending three variables.
But i m not able to get it in next php page where i m sending them ...
please check.
Index.php
function loadMoreData(offset){
var part1= "<?php echo ($part1);?>";
var part2="<?php echo ($part2);?>";
$.ajax({
type: 'get',
async:false,
url: 'getMoreData.php',
data:{offset:offset,part1:part1,part2:part2},
success: function(data){
$(data).appendTo("#product");
},
error: function(data){
alert("ajax error occured…"+data);
}
}).done(function(){
$(window).bind("scroll",function(){
scrollMore();
});
});
}
});
getMoredata.php
<?php
include('connection.php');
$offset = (isset($_REQUEST['offset']) && $_REQUEST['offset']!='') ? $_REQUEST['offset'] : '';
$limit = 10;
$var1 = (isset($_REQUEST['part1']) && $_REQUEST['part1']!='') ? $_REQUEST['part1'] : '';
$var2 = (isset($_REQUEST['part2']) && $_REQUEST['part2']!='') ? $_REQUEST['part2'] : '';
$qry1 = mysql_query('select * from xml WHERE PNAME LIKE \'%$var2\' AND CATEGORY like \'%$var1\' limit ".$offset.", ".$limit."');
print $qry1;
?>
I m able to send the three variables from index.php page but i m not able to get them in getMoreData.php,due to which i m not able to run the sql command...
Please verify guys....
Use $_GET instead of $_REQUEST.
Also you are not sending the rows properly, use-
print_r(mysql_fetch_array($qry1));
Then try to check the response in browser's console with - console.log(data) and then manipulate it accordingly.
Try with this for all variables
$offset = isset($_GET['offset']) ? $_GET['offset'] : $_POST['offset'];

Categories

Resources