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
Related
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;
}
I know that using php inside js is a bad practice, but unfortunately for now my skill is not enough to come up with something else.
$(document).ready(function() {
$("#type").change(function() {
var val = $(this).val();
valSize = "<?php $sql = "SELECT model FROM cars WHERE brand = 'val'";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)){
echo '<option>'.$row['model'].'</option>';
}
?>";
$("#size").html(valSize);
});
});
Is there any way how I could add val variable inside php code?
Your best bet would be to use a JavaScript AJAX call to send a request to another php file on your server.
First, create a separate PHP file on your server, I'll label it query.php (ONLY for the purposes of this explanation, I'd recommend choosing something more meaningful to your application).
<?php
if ($_POST['brand']) {
// Be sure to set up your SQL $conn variable here
$conn = ...;
$sql = "SELECT model FROM cars WHERE brand = '" . $_POST['brand'] . "'";
$result = mysqli_query($conn, $sql);
$data = []; // Save the data into an arbitrary array.
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
echo json_encode($data); // This will encode the data into a variable that JavaScript can decode.
}
Then in your JavaScript, perform the AJAX request:
$(document).ready(function() {
$("#type").change(function() {
var val = $(this).val();
$.post('query.php', {'brand' : val}, function(data){
var jsonData = JSON.parse(data); // turn the data string into JSON
var newHtml = ""; // Initialize the var outside of the .each function
$.each(jsonData, function(item) {
newHtml += "<option>" + item['model'] + "</option>";
})
$("#size").html(newHtml);
});
});
});
You can't execute the php code once the page has loaded. You're going to have to make a ajax call to a php file, that queries the data you need and echos that back to the original file. I would also recommend encoding it using echo json_encode($queryResults); Then you can JSON.parse($data);the return data in the success function of the ajax call.
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.
I'm stuck here for about 4 hours do alot of research and cannot fin the answer.
I want to repopulate the table after updating the contents using jquery ajax and php so here is my code.
PHP script:
if(isset($_POST['myinputval']))
{
$uinput = $_POST['myinputval'];
$uinput = $mysqli->real_escape_string($uinput);
$query = ('INSERT INTO tbltest values (" ","'.$uinput.'") ');
if($mysqli->query($query))
{
} else
echo 'fail'. $mysqli->error;
}
$result= $mysqli->query("Select *from tbltest");
if($result->num_rows>0)
{
while($row=$result->fetch_assoc())
{
$sendtojq[]=$row;
}
echo json_encode($sendtojq);
}
mysqli_close($mysqli);
Here is my script
<script type="text/javascript">
function ajaxsubmit()
{
var myinputval = $("#input1").val();
$.ajax({url:'myphp.php', type:'post', data:{
myinputval:myinputval
},
success: function(data)
{
alert(data);
}
});
}
</script>
This is the output when submitted
[{"ID":"1","NAME":".$newinput."},{"ID":"2","NAME":".$newinput."},{"ID":"3","NAME":".$newinput."},{"ID":"4","NAME":".$newinput."},{"ID":"5","NAME":".$newinput."},{"ID":"6","NAME":".$newinput."},{"ID":"7","NAME":"$newinput"},{"ID":"8","NAME":"twst"},{"ID":"9","NAME":"twst"},{"ID":"10","NAME":"testtt"},{"ID":"11","NAME":"testtt"},{"ID":"12","NAME":"thisssss"},{"ID":"13","NAME":"thisssss"},{"ID":"14","NAME":"tstet"},{"ID":"15","NAME":"Last"},{"ID":"16","NAME":""},{"ID":"17","NAME":"dddddddd"},{"ID":"18","NAME":"aaaaaaaaaaa"},{"ID":"19","NAME":"gggggggggggggggggggggg"},
Now what I want to do is get every single element of the array which is stored in the variable 'data' and use is at as the value of my table. Any suggestions? Thanks in advance.
So, i've a working js script that calls a php script that executes a mysql query.
The bad part is when i try to pass the coordinates back to the js script because they are unformatted.
Example:
the array i would like to have is {xx.xxxxxxx, yy.yyyyyyy...}
instead i get {xx.xxxxxxxyy.yyyyyyy and so on}.
here is the php query code UPDATED:
<?php
include('config.php'); //richiama lo script per la connessione al database
$org_name=$_POST['valor']; //riceve il nome dell'organizzazione terroristica desiderata
$return = array();
$query=mysql_query("SELECT longitude, latitude FROM gtdb WHERE `gname` LIKE '$org_name%' and longitude!=''"); //esegue una query al database
while($row=mysql_fetch_assoc($query)&&$row2=mysql_fetch_assoc($query)){
$return[] = array($row['longitude'], $row2['latitude']);
}
header('Content-type: application/json');
echo json_encode($return);
?>
here is the javascript code that triggers the query, when it gets back the datas from the query calls the dataadder function (see the next section of js code):
var Datas = [new google.maps.LatLng(32.7603282, 46.343451)];
$(document).ready(function() {
$('#gnome').change(function() {
var inpval=$(this).val();
$.ajax({
url: 'php/query.php',
type: 'post',
data: {valor : inpval},
success: function(data) {
while(Datas.length > 0) {
Datas.pop();
}
alert(data);
Datas = dataadder(data);
initialize(); //reinitialize gmap with the new datas
alert(Datas);
}
});
});
});
dataadder code
function dataadder(array){
var arr2 = [];
var i=0;
var j=1;
while(j<=array.length){
arr2.push("new google.maps.LatLng("+array[i]+")");
i+=2;
j+=2;
}
alert(arr2);
return(arr2);
}
Any help?
You should probably try with json_encode, something like this :
$query=mysql_query("SELECT longitude, latitude FROM gtdb WHERE `gname` LIKE '$org_name%' and longitude!=''"); //esegue una query al database
$return = array();
while($row=mysql_fetch_assoc($query)){
$return[] = array($row['longitude'], $row['latitude']);
//or $return[] = ''. $row['longitude'] . '.' . $row['latitude'];
//if you want one 'xxx.yyy' string per row of the output
}
echo json_encode($return);
this will output something like [['xxx','yyyy'], ['xxx','yyyy']]. you then need to call that php with $.getJSON(...) instead of $.ajax(). also you'll have to adapt dataadder accordingly.
and as said in comments, add application/json as your content-type