Updating (refreshing) PHP variable without refreshing website - php

I am trying to make updating variable called $online without refreshing site.
Theres is my try:
data.php
<?php
include("steam.php");
$data = $online;// obtain current value of data from somewhere
echo $data; // should be an integer
?>
refresh.js
$(document).ready( function () {
var data = []; // data is empty
var graph = Morris.Bar({
element: 'graph',
data: data
labels: ['random label']
});
function update () {
$.getJSON( "data.php", function (newv) {
data.push( { x: newv, y: "Today" } ); // store new value
graph.setData( data ); // update the graph
});
}
update();
setInterval( update, 1000 );
});

I just ran this through so I know it works. My previous comment will do the job. I know $.getJSON is similar so I don't know what conflicts you will have there, but the below will update your php variable.
<script>
$.post( "data.php", { online: "UpdatedData" } );
</script>
data.php
$online = $_POST['online'];

Related

Count number of jQuery $.get success responses

I have a jQuery function that loads a PHP file (which gets a JSON response from an application) every 100ms. What I am trying to do is have two different counters, one which will increment every time a request is sent and another counter which will increment as soon as it gets a JSON response. At the moment I have the following which is not working, they are both just counting the number of requests being sent:-
JQUERY
$(function() {
var MAXNUM = 9;
var count = 0;
var countSuccess = 0;
function newAsyncRequest() {
setTimeout(function() {
newAsyncRequest();
count++;
$(".request").html(count);
$.get('test.php', function(data) {
countSuccess++;
$( ".log" ).html(countSuccess);
});
}, 100);
}
newAsyncRequest();
});
PHP
require_once('scripts/php/controllers/curl.controller.php');
$postcode = 'LE11 5';
$postcode = rawurlencode($postcode);
$uri = 'http://192.168.1.110:8290/?pc='.$postcode; // Home
$response = CurlController::request($uri);
So my question is basically, how can I count the number of successful responses I am getting from .$get command?
Need to print count to .request, you were using countSuccess in both the statements
$(function() {
var MAXNUM = 9;
var count = 0;
var countSuccess = 0;
function newAsyncRequest() {
setTimeout(function() {
newAsyncRequest();
count++;
$(".request").html(count);
//need to print here
$.get('test.php', function(data) {
countSuccess++;
$( ".log" ).html(countSuccess);
});
}, 100);
}
newAsyncRequest();
});
You can use $.ajax's success parameter. The function passed to this parameter will only run if an ajax request is successful.
$.ajax({
url:"",
type: "get",
beforeSend: function(){ requestCounter++ },
success: function(){ successCounter++ }
});
What are you defijning as a success?
The .get 'success' is that the server responded which it hopefully always will do.
If you are definign success as somthign working in the PHP script then in the PHP then in the jquery success function check what was returned in 'data' to see if it was succesful.
I generally return a Json encoded array with an element called 'result' that is either set to ture or false by the PHP and the jquery can simple act on that record.

Jquery .post then use .show and .hide

So I'm learning JQuery and I'm stuck on this:
I have a page that displays a HTML table and inside that table I want to have a cell that can be updated via a dropdown menu, so you click on edit, the current value disappears and dropdown menu appears, and when the value is changed the database is updated and the new value is displayed. (with the menu disappearing)
The problem seem to be putting the .text and .show inside the data callback function - if I alert the data it is returning the correct data from the PHP file, and if I comment out the .post line and replace the (data) with ("test_text") it replaces the menu as I want it to.
Hopefully my question is well enough written to make sense, thanks.
Here's the code
$('.cat_color_hide_rep').hide();
$('.act_status_dropD').click(function () {
var record_id = $(this).parents('tr').find('.record_id').text()
$(this).parents('tr').find('.cat_color_hide_rep').show();
$(this).parents('tr').find('.cat_color_show_rep').hide();
});
$('.cat_color_hide_rep').change(function () {
var record_id = $(this).parents('tr').find('.record_id').text()
$(this).parents('tr').find('.cat_color_hide_rep').hide();
$.post('TEST_ajax_rep_list_status.php', {
ID: record_id
}, function (data) {
$(this).parents('tr').find('.cat_color_show_rep').text(data);
$(this).parents('tr').find('.cat_color_show_rep').show();
alert(data); // for testing
});
});
You can not access the $(this) inside the $.post function.
You can do this before the $.post:
var that = this;
And inside the post, do this:
$(that).parents('tr').find('.cat_color_show_rep').text(data);
$(that).parents('tr').find('.cat_color_show_rep').show();
This would be your resulting code:
$('.cat_color_hide_rep').hide();
$('.act_status_dropD').click(function () {
var record_id = $(this).parents('tr').find('.record_id').text()
$(this).parents('tr').find('.cat_color_hide_rep').show();
$(this).parents('tr').find('.cat_color_show_rep').hide();
});
$('.cat_color_hide_rep').change(function () {
var record_id = $(this).parents('tr').find('.record_id').text()
$(this).parents('tr').find('.cat_color_hide_rep').hide();
/** ADDED LINE **/
var that = this;
$.post('TEST_ajax_rep_list_status.php', {
ID: record_id
}, function (data) {
/** CHANGED LINES **/
$(that).parents('tr').find('.cat_color_show_rep').text(data);
$(that).parents('tr').find('.cat_color_show_rep').show();
alert(data); // for testing
});
});
In the callback function, this has been changed to refer to the XHR Object, you need to backup an reference of this from outside the function if you want to access it from the callback
var $this = $(this);
$.post('TEST_ajax_rep_list_status.php', {
ID: record_id
}, function (data) {
$this.parents('tr').find('.cat_color_show_rep').text(data);
$this.parents('tr').find('.cat_color_show_rep').show();
alert(data); // for testing
});
//Cache your selectors!
var catColorHide = $('.cat_color_hide_rep');
catColorHide.hide();
$('.act_status_dropD').on('click', function () { //Use the .on() method and save a function call. The .click() simply calls the .on() and passes in the callback.
var this = $(this), //If you use a selection more than once, you should cache it.
record_id = this.parents('tr').find('.record_id').text();
this.parents('tr').find('.cat_color_hide_rep').show();
this.parents('tr').find('.cat_color_show_rep').hide();
});
catColorHide.on('change', function () {
var this = $(this),
record_id = this.parents('tr').find('.record_id').text();
this.parents('tr').find('.cat_color_hide_rep').hide();
$.post('TEST_ajax_rep_list_status.php', {
ID: record_id
}, function (data) {
// I don't do the 'var this = $(this)' in here to fix your problem. The 'this' you see me using here refers to the element from the callback.
this.parents('tr').find('.cat_color_show_rep').text(data);
this.parents('tr').find('.cat_color_show_rep').show();
console.log(data); // Use this for testing instead.
});
});

Processing PHP variable in javascript and returning back to PHP

I am working on an application where I fetch data from database and process it using javascript/jquery like this:
$sqlEdit = "select revisionContent from tbl_revision where revisionId='".$_SESSION['contentId']."'"; //Query to fetch the result
$rsEdit = $dbObj->tep_db_query($sqlEdit);
$resEdit = $dbObj->getRecord($rsEdit);
$IdLessContent = $resEdit['revisionContent'];
<script language="javascript">
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
console.log(trimmedCont);
var test = $('<div class="addId">');
test.append(trimmedCont);
//console.log(test.html());
test.children().each(function(index, value) {
$(this).attr('id', "com-"+randomString());
});
//console.log(test.html());
viewContent = test.html();
I get the required data in viewContent.I want to display it on the page in this section
<div id="mainWrap" onClick="fnDestroyEditable();">
<?php echo $resEdit['revisionContent']; ?> //THis is the unprocessed data displayed directly from database.I want to display the processed data here
</div>
I know we cannot get javascript variables to PHP as both are different (one server side and other client). But then how can I achieve this in my scenario?
EDIT I would like to add that the returned data is HTML stored in the database.So,I get the html->process it(add id attribute)->want to return back after processing
you can put the viewContent inside #mainWrap using javascript.
just make sure the DOM is loaded wrapping your js code with $(document).ready()
and add:
$('#mainWrap').html(viewContent);
at the end of your function.
$(document).ready(function () {
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
console.log(trimmedCont);
var test = $('<div class="addId">');
test.append(trimmedCont);
//console.log(test.html());
test.children().each(function(index, value) {
$(this).attr('id', "com-"+randomString());
});
//console.log(test.html());
viewContent = test.html();
// put viewContent in the innerHtml of your wrapper
$('#mainWrap').html(viewContent);
});
if you need to send back info to the server you have to do it with ajax.
I added a javascript function addId() that will be invoked on click on one of the elements.
the new code is:
$(document).ready(function () {
var getSavedContent = '<?php echo json_encode($IdLessContent); ?>';
var trimmedCont=($.trim(getSavedContent).slice(1));
//console.log(trimmedCont);
var lengthCont= trimmedCont.length;
var trimmedCont=$.trim(trimmedCont.slice(0,lengthCont-1));
console.log(trimmedCont);
var test = $('<div class="addId">');
test.append(trimmedCont);
//console.log(test.html());
test.children().each(function(index, value) {
$(this).attr('id', "com-"+randomString());
});
//console.log(test.html());
viewContent = test.html();
// put viewContent in the innerHtml of your wrapper
$('#mainWrap').html(viewContent);
$('#mainWrap .addId').children().click(function({
addId(this);
}));
}
addId = function(elem){
// elem is the child element you clicked on
// $(elem).attr('id') should be "com-[randomString]"
$.ajax({
type: "POST",
url: "path/to/php/script", // update id PHP script
data: data, // whatever you need in json format
dataType: "json",
error: function() {
// error function you want to implement
errorFunction();
},
success: function(resp) {
// do whatever you need with the response from you PHP action
}
});
};
if you need to to call server with out human interaction just substitute
$('#mainWrap .addId').children().click(function({
addId(this);
}));
with:
$('#mainWrap .addId').children().each(function({
addId(this);
}));
if I undesrstand you, you shold only add in the end of your js code this line:
$('#mainWrap').html(viewContent);
If you want to send JS data to PHP, you should use ajax request.

Retrieving data from server using jquery $.get function

I am creating a real-time graph with flot library and using jquery $.get function.
I want the graph to be updated every 5 seconds retrieving the recorded data.
The X axis is in time mode. I have been trying to retrieve the necessary data but i can't get it yet. The .php file is fine because it connects to the postgresql database and writes the data into the requested variable.
I think that my problem is in the $.get function.
Can you please help me to find if my Javascript code is fine?
Thanks in advance
<script type="text/javascript">
$(function () {
var data=[];
var data_inicial = [];
var data_actual = [];
var x;
var y;
function data_init()
{
$.get("param_pozos_linea1.php", function(data1) { x= data1; });
data_inicial.push([x]);
return data_inicial;
}
function actualiza_data()
{
$.get("param_pozos_linea2.php", function(data2) { y= data2; });
data_actual.push(y);
return data_actual;
}
// control de velocidad
var updateInterval = 500;
$("#updateInterval").val(updateInterval).change(function () {
var v = $(this).val();
if (v && !isNaN(+v)) {
updateInterval = +v;
if (updateInterval < 1)
updateInterval = 1;
$(this).val("" + updateInterval);
}
});
// setup plot
var options = {
series: { shadowSize: 0 }, // drawing is faster without shadows
yaxis: { min: 0, max: 100 },
xaxis: { mode: "time",tickLength: 5, timeformat: "%d/%m - %h:%M %p"}
};
var plot = $.plot($("#placeholder"), data_init() , options);
function update() {
plot.setData([ actualiza_data() ]);
plot.draw();
setTimeout(update, updateInterval);
}
update();
});
</script>
The retrieved data from "param_pozos_linea1.php" file loooks like this:
[1355767803000,0],[1355767502000,0],[1355767202000,0],[1355766902000,0],[1355766602000,0],[1355766302000,0],[1355766002000,0],[1355765702000,0],[1355765402000,0],[1355765103000,2570.17],[1355764803000,2569.63]
And the retrieved data from "param_pozos_linea2.php" looks like this:
[1355767803000,0]
The get request is asynchronous, it is impossible for it to work in a synchronous manner like you think it does.
function data_init()
{
$.get("param_pozos_linea1.php", function(data1) { x= data1; }); <-- calls the server asynchronously
data_inicial.push([x]); <-- is called before code is set on server, so it is setting it with what ever the last value was
return data_inicial; <-- returns something you do not want
}
what you want to do is call the function that set the data
function data_init()
{
$.get("param_pozos_linea1.php",
function(data1) {
data_inicial.push([data1]);
callYourPlotFunction(data_inicial);
}
);
}

Showing and hiding buttons per ajax request in jquery

I've coded up a sort of inventory managing system and I'm adding a shipping cart so to speak to it. I'm trying to make the interface easier to use and navigate through jquery. The 'cart' is stored via sessions in php. I have a page that outputs all the inventory and I am adding buttons that allow the user to add or remove each specific item from the 'cart', but only one button should be shown based on cart status (i.e. if the item is in cart, show the remove button).
Ive got a mess of jquery code as I'm trying all sorts of approaches
heres some php:
if(isset($_SESSION['cart'][$row['bbn']])) {
echo "REMOVE FROM CART\n";
echo "ADD TO CART\n";
} else {
echo "ADD TO CART\n";
echo "REMOVE FROM CART\n";
}
here's some jquery:
$(".addtocart").each(function (i) {
if($(this).hasClass('active')){
$(this).siblings('.removefromcart').hide();
}
});
$(".removefromcart").each(function (i) {
if($(this).hasClass('active')){
$(this).siblings('.addtocart').hide();
}
});
// View_inventory add button
$(".addtocart").click(function(){
var $bbn = $(this).parent().attr("id");
var $object = this;
$.ajax({
url: "queue.php?action=add",
data: { bbn: $bbn },
type: 'GET',
success: function(){
$($object).hide();
$($object).siblings('.removefromcart').show('highlight');
}
});
});
$(".removefromcart").click(function(){
var $bbn = $(this).parent().attr("id");
var $object = this;
$.ajax({
url: "queue.php?action=remove",
data: { bbn: $bbn },
type: 'GET',
success: function(){
$($object).hide();
$($object).siblings('.addtocart').show('highlight');
}
});
});
Any suggestions as to how I should make this simpler? Ive got it working now.
first in php:
$cart = '';
$noCart = '';
if ( ! isset($_SESSION['cart'][$row['bbn']]) ) $cart = 'inactive';
else $noCart = 'inactive';
echo 'REMOVE FROM CART\n';
echo 'ADD TO CART\n';
now I present two method, the first one will execute slightly faster as it only switch classes in css, but you don't get your fancy effect. you get it in the second method.
first method
add to your css:
.inactive {display: none;}
and in js:
$(".addtocart, .removefromcart").click(function(){
var $object = $(this);
var bbn = $object.parent().attr("id");
var action = $object.find('.addtocart').length ? 'add' : 'remove';
$.get("queue.php", {"action": action, "bbn": bbn}, function (data) {
$object.addClass('inactive').siblings().removeClass('inactive');
});
});
Second method, no need for a CSS entry.
$(function () { // equivalent to $(document).ready(function () {
$('.inactive').hide();
$(".addtocart, removefromcart").click(function(){
var $object = $(this);
var bbn = $object.parent().attr("id");
var action = $object.find('.addtocart').length ? 'add' : 'remove';
var params = {action: action, bbn: bbn};
// $('#someSpinnigLoadingImage').show();
$.get("queue.php", params, function (data) {
// $('#someSpinnigLoadingImage').hide();
$object.hide().siblings().show('highlight');
});
});
});
hope this help. note: I didn't test the code, some nasty typo might have slipped through.
Additionnal note, you might want some visual effect right before the ajax call (like in the comment in version 2, or hide $object, so that the user can't multiclick it.
$object.hide()
$.get("queue.php", params, function (data) {
$object.siblings().show('highlight');
});

Categories