Auto Refresh JS Array if content changes? - php

I have this javascript function which serves an AJAX request to an external PHP Script, I want this to auto update a HTML <div> if the new check is different from the old check.
<script>
window.setInterval(function()
{
$(function ()
{
$.ajax({
url: 'api.php', data: "", dataType: 'json', success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var vname = row[1];
var Password = row[2]
$('#output').append("<hr />").append("<b>id: </b>"+id+"<b> name: </b>"+vname+" <b>Password: </b>"+Password);
}
}
});
});
}, 5000);
</script>
This currently sucessfully returns and updates the div with the content from the array, the problem is, since adding the window.setInterval(function() line, it will server the connection every 5 seconds and update the <div> with duplicate data.. when all I want, it for it to echo the new data (if there is a ny)
Here is my other PHP script:
$STD = new mysqli ("localhost", "root", "hidden", "ajaxrequests");
$array = array();
$Query = $STD->prepare ("SELECT * FROM ajaxdata");
$Query->execute();
$Query->bind_result($ID, $Name, $Password);
while ($Query->fetch())
{
$array[] = array ( $ID, $Name, $Password);
}
echo json_encode($array);

Just add a call to empty() before your loop.
<script>
window.setInterval(function()
{
$(function ()
{
$.ajax({
url: 'api.php', data: "", dataType: 'json', success: function(rows)
{
$('#output').empty();
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var vname = row[1];
var Password = row[2]
$('#output').append("<hr />").append("<b>id: </b>"+id+"<b> name: </b>"+vname+" <b>Password: </b>"+Password);
}
}
});
});
}, 5000);
</script>
Of course if your data size is large, this would not be very optimal. I would actually suggest having the PHP server send a timestamp value with it's response. You could then pass this back in subsequent AJAX requests and have the server determine if there are actually updates to deliver since that last timestamp. You could then have the server only send those updated records, which you could append/update similar to how you are already doing it.

Related

Content fetch in main page from another page from database through ajax

I have written this code but it didn't work. I have searched so much but those code are not properly work. what should I do? I want to fetch data without refreshing whole page.
I have looked at this other question.
$(document).ready(function() {
$("#pair_form").submit(function(e) {
e.preventDefault();
var devicename = $("#devicename").val();
var id = $("#id").val();
var latitude = $("#latitude").val();
var longitude = $("#longitude").val();
var ignition = $("#ignition").val();
var Arming = $("#Arming").val();
function showData() {
$.ajax({
url: 'http://example.com/ddd/cfg.php',
method: 'get',
dataType: 'text',
success: function(response) {
$('#result').html(response)
}
});
}
});
});

how to return an array in AJAX call in php

I have a form that has a select option , So I am trying to update the form/table with some content from database when I select a type in the select option ,
SO for that I did an ajax call something like this.
$("#selectPlantilla").on("change",function(){
var descripcion = $(this).val();
//alert(descripcion);
var url="http://index.php";
var posting = $.post(url, {
im_descripcion: descripcion,
}).done(function (data) {
alert(data);
});
});
And then I validated the call in php on the same inde.php page like this
if(isset($_POST['im_descripcion']))
{
$db = new dataBase();
$result = $db->execute("SELECT * FROM `tableNmae` WHERE `descripcion` = '".trim($_POST['im_descripcion'])."'");
$result = mysql_fetch_array($result);
print_r($result);
}
The problem I am facing is in the alert window it return the whole page instead of just the $result that I have printed , So can any one help me out how I can channelize it properly , I have use the values from the array $result to update in the form using JQuery .
Thanks in Advance
For returning PHP array data in Ajax, JSON will make your life the simplest.
$result = mysql_fetch_array($result);
echo(json_encode($result));
This will return the array in a format that is easily usable by JavaScript. Try this to see its content:
alert(JSON.stringify(data));
With JSON, you should be able to fetch data or iterate through it in JavaScript
Try this
In Javascript
<script type="text/javascript">
var $ =jQuery.noConflict();
$(document).ready(function(){
$('.dropdown_class').on('change', function() {
var m_val = this.value;
var datastring = "im_descripcion="+m_val;
$.ajax({
type: "POST",
url: "lunchbox_planner.php",
data: datastring,
cache: false,
success: function(result) {
var v = $.parseJSON(result);
var l = v.length;
for(var i=0;i<l;i++){
var sh_d = "<div class='coco3'>"+v[i]+"</div>";
$('.mon_tea').append(sh_d);
}
}
});
});
});
</script>
<div class="mon_tea">
In PHP
<?php
if(isset($_POST['im_descripcion'])) {
$db = new dataBase();
$result = $db->execute("SELECT * FROM `tableNmae` WHERE `descripcion` = '".trim($_POST['im_descripcion'])."'");
while($row_sh = mysql_fetch_array($result)){
$all_incr[] = $row_sh['col_name'];
}
echo json_encode($all_incr);
}
?>

ajax post success parse json

sorry for the long question. I am trying to ajax post to collect a contacts position history and then add the markers to the map.
The ajax post returns the positions data json encoded like:
[{"name":"Chris","data":{"user":"447967048843","data":[{"timestamp":1332840872,"longitude":-1.549517,"latitude":53.973174},{"timestamp":1332841510,"longitude":-1.444133,"latitude":53.997148}]},"contacts":null},{"name":"Jason","data":{"user":"447879896697","data":[{"timestamp":1332839836,"longitude":-1.566667,"latitude":53.978533},{"timestamp":1332840447,"longitude":-1.567654,"latitude":53.977927}]},"contacts":null}]
Here is the getHistory function which is called on form submit after the contact has been selected.
function getHistory() {
var contact = $("#contact").val()
var days = $("#days").val()
$.ajax({
type: 'post',
url: 'temp_history.php',
data: {contact: contact, days: days},
context: document.body,
beforeSend: function() {
},
success: function(succ){
var obj = jQuery.parseJSON(succ);
var divs="",tabs="",counts=0;
jQuery("#gMap").gmap3({
action: 'clear'});
jQuery(".marker").remove();
jQuery.each(obj,function(i,item){
tabs +=item.contacts;
if(item.data.latitude != null && item.data.longitude!=null)
{
addMarker(item.name, item.data.timestamp,item.data.latitude,item.data.longitude,item.data.user_id);
}
});
}
});
}
I think the problem is i need to nest the jQuery.each function but not sure how?
The addMarker function is:
function addMarker(name, timestamp, lati, longi, user_id) {
jQuery("#gMap").gmap3({
action: 'addMarkers',
markers:[
{lat:lati, lng:longi, data:name}
]
});
}
Thank you
You're right - your traversal of your JSON was incorrect, try this in your success handler:
success: function(data){
var json = jQuery.parseJSON(data); // If you're returing json, this shouldn't be required
var divs = "", tabs = "", counts = 0;
jQuery("#gMap").gmap3({ action: 'clear' });
jQuery(".marker").remove();
jQuery.each(json, function(i, item) {
var name = item.name;
var userId = item.data.user;
jQuery.each(item.data.data, function(i, nav) {
var ts = nav.timestamp;
var lat = nav.latitude;
var long = nav.longitude;
if (lat != null && long != null) {
addMarker(name, ts, lat, long, userId);
}
});
})
}
Also, it would be worth making the object names in your JSON more semantic, especially as you have data listed in multiple levels.

Execute function from another script in a script

I have two scripts running in the body of my page. When "a" is pressed on the keyboard, another script runs. How can I add some delay and then trigger the first script again? I have tried with the code below, it does not work. Prefferably, I would like to cancel the first timeout in the beginning of the second script as well.
<script id="source" language="javascript" type="text/javascript">
$(function (){
function reloading(){
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
_id = id;
var vname = data[1];
var message = data[2];
var timestamp = data[3];
var field1 = data[4];
_field1 = field1;
var val2 = parseInt(field1, 10) ;
_val2 = val2;
$('#output').hide().html( message ).fadeIn("slow");
$('#username').hide().html( vname +":" ).fadeIn("slow");
setTimeout(function(){
reloading();
}, 60000);
}
});
}
reloading();
});
</script>
<script>
$(document).jkey('a',function() {
$.post("update.php", { "id": _id} )
$('#output').hide().html( "<i>Message</i><br> <br>" +_val2 +" additional." ).fadeIn("slow");
$('#username').fadeOut("fast");
$('#valg1').fadeOut("fast");
$('#valg2').fadeOut("fast");
});
setTimeout("reloading()",1000);
</script>
You have to put reloaded() in global scope to access it from another script. Right now it is inside an anonymous function (a bit of a hack to mitigate global scope pollution), but for your case if it isn't feasible to merge the two scripts into one, you are going to have to pollute global scope.
If it is a one-off function, give it a unique prefix or something:
myApp_reloaded();
If you have a bunch of functions that need to be in the global scope, create a wrapper object. There are a bunch of different patterns you can use, I prefer this...
function MyApp() {
}
MyApp.prototype.reloaded = function () {
// reload func body here
}
var myApp = new MyApp();
now you can access the methods globally:
myApp.reloaded();
Quick hack until someone comes with a more elegant one that does not pollute the global scope
<script id="source" language="javascript" type="text/javascript">
var tId;
function reloading(){
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data) {
var id = data[0];
_id = id;
var vname = data[1];
var message = data[2];
var timestamp = data[3];
var field1 = data[4];
_field1 = field1;
var val2 = parseInt(field1, 10) ;
_val2 = val2;
$('#output').hide().html( message ).fadeIn("slow");
$('#username').hide().html( vname +":" ).fadeIn("slow");
clearTimeout(tId);
tId=setTimeout(function(){ reloading();}, 60000);
}
});
}
$(function (){
reloading();
});
$(document).jkey('a',function() {
$.post("update.php", { "id": _id} )
$('#output').hide().html( "<i>Message</i><br> <br>" +_val2 +" additional." ).fadeIn("slow");
$('#username').fadeOut("fast");
$('#valg1').fadeOut("fast");
$('#valg2').fadeOut("fast");
clearTimeout(tId);
tId = setTimeout(function() { reloading()},1000);
});
</script>

jQuery AJAX referencing $(this) within success function

I have a voting system which sends an id of the clicked item to a PHP script, the PHP updates the database and echos back the new vote counts via an JSON encoded array.
This is the jQuery:
$(".vote_up").click(function(){
var id = this.id;
var vote = $(this).attr("class");
var data = "id=" + id + "&vote=" + vote;
$.ajax
({
type: "POST",
url: "vote.php",
data: data,
cache: false,
success: function(data)
{
for(var x in data) {
$(".votes_up").find(id).html(data[x].vote_up);
$(".votes_down").find(id).html(data[x].vote_down);
}
}
});
});
So when i construct the item in the first place, i take the record ID in the database and set it as the items ID. So what i'm trying to do is reference the exact item that was clicked and set it's HTML to the data thats coming back from the PHP. I've checked in Firebug and I'm getting correct data back but the count of votes isnt changing. Any ideas?
This is the PHP for reference:
$query = "SELECT vote_up, vote_down FROM posts WHERE id = '".$id."'";
$result1 = mysql_query($query);
$output = Array();
while ($row = mysql_fetch_array($result1)){
$output[] = Array(
"vote_up" => $row['vote_up'],
"vote_down" => $row['vote_down'],
);
}
echo json_encode($output);
If you just want this in the success: callback to refer to the element that was clicked, just set the context: property for the AJAX request.
$.ajax({
context: this, // set the context of the callbacks
type: "POST",
url: "vote.php",
data: data,
cache: false,
success: function(data) {
// now "this" refers to the element that was clicked
}
You can test it by doing something a little more generic, like:
$(this).html("yep, it works");
... then if that works, consider that it doesn't really make sense to do .html() on the same element in a loop, because each time .html() overwrites the entire content.
Use .append() instead if you're appending data from the loop:
for(var x in data) {
$(this).append(data[x].vote_up);
$(this).append(data[x].vote_down);
}
Wouldn't:
$(".votes_up").find(id).html(...);
Really just need to be:
$('#' + id).html(..);
If you define a variable within the click() method callback, you'll be able to reference it within your ajax success callback. Something similar to this should do you:
$(".vote_up").click(function(){
// Assign the clicked element to a scoped variable...
var target = $(this);
var id = this.id;
var vote = $(this).attr("class");
var data = "id=" + id + "&vote=" + vote;
$.ajax
({
type: "POST",
url: "vote.php",
data: data,
cache: false,
success: function(data)
{
for(var x in data) {
// Then refer to it within your callback
target.html(data[x].vote_up);
target.html(data[x].vote_down);
}
}
});
});

Categories