Why does this code work fine in the unit test, but not in the page? I have Firebug and FirePHP in place and can see the variable pass just fine if I hard code it, the operation is passing an int just fine in the unit test, but I've tried parseInt, Math.floor, and many other wacky methods and the value for statementCount simply won't post.
The ajax:
//polling code
var statementCount = 0;
(function poll(){
setTimeout(function(){
$.ajax({ url: "RROO_update.php",
type: "POST",
data: {'meetID': 2176, 'statementCount': statementCount},
success: function(data){
if(data.length > 0){
var statements = JSON.parse(data);
//reset the statement count
statementCount = statementCount + statements.length;
$(this).actplug_RROO('formatReturns', statements, userID);
poll();
}
},
error: function(){
poll();
},
});
}, 5000);
})();
and the php:
<?php
include("../inc/variables.php");
error_reporting (E_ALL ^ E_NOTICE);
require_once('../FirePHPCore/FirePHP.class.php');
require_once('../FirePHPCore/fb.php');
$firephp = FirePHP::getInstance(true);
ob_start();
$MeetingID = $_POST['meetID'];
$StatementCount = (int)$_POST['statementCount'];
$firephp-> log($StatementCount, 'Statement count passed in' );
$Finished = FALSE;
while($Finished == FALSE){
$MeetingStats = mysql_query("SELECT RROO_UPDATE.*, MEMBER.UserName, MEMBER.UserImage FROM RROO_UPDATE JOIN MEMBER ON RROO_UPDATE.MemberID = MEMBER.MemberID WHERE MeetingID = $MeetingID ORDER BY TimeStamp DESC", $DB_Connection);
$MyNum = mysql_num_rows($MeetingStats);
$firephp->log($MyNum, 'Row Query');
if($MyNum > $StatementCount){
$Returns = array();
while($Return = mysql_fetch_array($MeetingStats)){
array_push($Returns, $Return);
}
$NewReturns = array();
$NewStats = $MyNum - $StatementCount;
$firephp->log($NewStats, 'heres the new stats count');
for($i = 0; $i < $NewStats; $i++){
array_push($NewReturns, $Returns[$i]);
}
$Here = count($NewReturns);
$firephp->log($Here, 'The length of the new returns array');
$Finished = TRUE;
echo json_encode($NewReturns);
}
else{
sleep(3);
}
}
?>
Like I said, it comes back fine on the unit test which is the same in all the aspects I can see (I actually copy pasted it into the page) the only difference being that the postback is routed differently on the page (to the plugin) but I've messed around with callback to no avail. Is there some reason the statementCount won't reset and Post in this code?
I don't think that statementCount is defined inside the callback, only in the function which executes the ajax call.
Here is a question and answer which should help you do what you want.
Related
I am having trouble getting the success call to fire in my ajax request. I know the communication is working fine, but the last call in my PHP script, which is a return json_encode($array); will fire as if it is a part of the onprogress object. I would like to "break" the onprogress call and run the success function on the last data sent via return json_encode when the PHP script has terminated...
Here is my AJAX call:
$( document ).ready(function(e) {
var jsonResponse = '', lastResponseLen = false;
$("#btn_search").click(function(e){
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
$.ajax({
type: "POST",
url: 'search.php',
data: $('#search_fields').serialize(),
dataType: "json",
xhrFields: {
onprogress: function(e) {
var thisResponse, response = e.currentTarget.response;
if(lastResponseLen === false) {
thisResponse = response;
lastResponseLen = response.length;
} else {
thisResponse = response.substring(lastResponseLen);
lastResponseLen = response.length;
}
jsonResponse = JSON.parse(thisResponse);
document.getElementById('progress').innerHTML = 'Progress: '+jsonResponse.msg;
}
},
success: function(data) {
console.log('done!');
document.getElementById('progress').innerHTML = 'Complete!';
document.getElementById('results').innerHTML = data;
}
});
e.preventDefault();
});
});
And here is the basic PHP server script:
<?php
function progress_msg($progress, $message){
echo json_encode(array('progress' => $progress, 'msg' => $message));
flush();
ob_flush();
}
$array = array('msg' => 'hello world');
$count = 0;
while($count < 100){
progress_message($count, "working....");
$count += 10;
sleep(2);
}
return json_encode($array);
?>
I made your code work, there were 2 errors. First, in your while loop, your function name is incorrect, try this:
progress_msg($count, "working... ." . $count . "%");
Secondly, the very last line outputs nothing, so technically you don't get a "successful" json return. Change the last line of your server script from:
return json_encode($array);
to:
echo json_encode($array);
UPDATE: Full working code with hacky solution:
Ajax:
$( document ).ready(function(e) {
var jsonResponse = '', lastResponseLen = false;
$("#btn_search").click(function(e){
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
$.ajax({
type: "POST",
url: 'search.php',
data: $('#search_fields').serialize(),
xhrFields: {
onprogress: function(e) {
var thisResponse, response = e.currentTarget.response;
if(lastResponseLen === false) {
thisResponse = response;
lastResponseLen = response.length;
} else {
thisResponse = response.substring(lastResponseLen);
lastResponseLen = response.length;
}
jsonResponse = JSON.parse(thisResponse);
document.getElementById('progress').innerHTML = 'Progress: '+jsonResponse.msg;
}
},
success: function(data) {
console.log('done!');
dataObjects = data.split("{");
finalResult = "{" + dataObjects[dataObjects.length - 1];
jsonResponse = JSON.parse(finalResult);
document.getElementById('progress').innerHTML = 'Complete!';
document.getElementById('results').innerHTML = jsonResponse.msg;
}
});
e.preventDefault();
});
Search.php:
<?php
function progress_msg($progress, $message){
echo json_encode(array('progress' => $progress, 'msg' => $message));
flush();
ob_flush();
}
$array = array('msg' => 'hello world');
$count = 0;
while($count <= 100){
progress_msg($count, "working... " . $count . "%");
$count += 10;
sleep(1);
}
ob_flush();
flush();
ob_end_clean();
echo json_encode($array);
?>
The problem with the "success" method of the ajax call was that it couldn't interpret the returning data as JSON, since the full return was:
{"progress":0,"msg":"working... 0%"}{"progress":10,"msg":"working... 10%"}{"progress":20,"msg":"working... 20%"}{"progress":30,"msg":"working... 30%"}{"progress":40,"msg":"working... 40%"}{"progress":50,"msg":"working... 50%"}{"progress":60,"msg":"working... 60%"}{"progress":70,"msg":"working... 70%"}{"progress":80,"msg":"working... 80%"}{"progress":90,"msg":"working... 90%"}{"progress":100,"msg":"working... 100%"}{"msg":"hello world"}
Which is not a valid JSON object, but multipje JSON objects one after another.
I tried removing all previous output with ob_end_clean(); , but for some reason I can't figure out, it didn't work on my setup. So instead, the hacky solution I came up with was to not treat the return as JSON (by removing the dataType parameter from the AJAX call), and simply split out the final Json element with string operations...
There has got to be a simpler solution to this, but without the use of a third party jQuery library for XHR and Ajax, I couldn't find any.
I've built a notification system, and its almost working. I just have one niggly bit that I can't seem to get my head around.
When a new update comes in from a friend it prints out the number of new notifications as expected, only if a user posts twice num_rows 2 pops up.. but if a user posts again it updates and replaces the 2 new notifications number back to 1 in the div because I'm using html in the ajax to replace.
So my question is, how can I update the div to get the total amount of results so it goes 1,2,3,4 etc instead of 2,1,1,1,1.
I don't want to replace the num of new rows with only the (1) update in the div, just add to the amount of new updates already inside it.
A bit like when facebook shows amount of notifications. say I have two and a friends posts on my wall I then will have 3.. but at the moment its adding the last new num row and going back to 1.
AJAX
<script type="text/javascript">
function loadIt() {
var notification_id="<?php echo $notification_id['notification_id'] ;?>"
var notification_id= window.localStorage.getItem ('lastId');
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id,
dataType:"json",
cache: false,
success: function(response){
if(response){
dataHandler;
if(response.num){
window.localStorage.setItem('lastId', response.notification_id);
var dataHandler = function(response){
var isDuplicate = false, storedData = window.localStorage.getItem ('lastId');
for (var i = 0; i < storedData.length; i++) {
if(storedData[i].indexOf(response) > -1){
isDuplicate = true;
}
}
if(!isDuplicate){
storedData.push(response);
}
};
if(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text">'+response['notification_content']+' <br />'+response['notification_time']+'</div></nr>');
$("#mes").html(''+ response.num + '');
}
};
}
}
}
});
}
setInterval(loadIt, 10000);
PHP
$json = array();
$com=mysqli_query($mysqli,"select notification_id,notification_content,notification_time from notifications where notification_id > '$id' AND notification_status=1 ");
echo mysqli_error($mysqli);
$num = mysqli_num_rows($com);
if($num!=1){
$json['num'] = $num;
}else{
$json['num'] = 0;
}
$resultArr = mysqli_fetch_array($com);
$json['notification_id'] = $resultArr['notification_id'];
$json['notification_content'] = $resultArr['notification_content'];
mysqli_free_result($com);
header('Content-Type: application/json');
echo json_encode($json);
}
The number of notifications on client-side is storedData.length.
So i would replace the counter
$("#mes").html(''+ response.num + '');
with
$("#mes").html(storedData.length);
I'm trying to implement a long polling system on my intranetwork, most of the users use IE and some use mobile too, that's why I'm trying to do it with long polling and not with websockets.
I followed this video http://www.screenr.com/SNH and I edited some code to work with my database. (Firebird)
It all seems ok, but it just doesn't break the loop. Maybe it's a kid mistake but I cannot see it, that is why I need your help!
Here's the code:
jQuery + Ajax:
var timestamp = null;
function waitForMsg(){
$.ajax({
type: "GET",
url: "getData.php?timestamp=" + timestamp,
async: true,
cache: false,
success: function(data){
alert('It Works');
var json = eval('(' + data + ')');
timestamp = json['timestamp'];
setTimeout('waitForMsg()',15000);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("A - " + XMLHttpRequest + " - error: " + textStatus + " (" + errorThrown + ")");
setTimeout('waitForMsg()',15000);
}
});
}
$(document).ready(function(){
waitForMsg();
});
</script>
getData.php ('DATAHORA' is timestamp field)
<?php
set_time_limit(0);
#ini_set("memory_limit",'64M');
require_once('../classes/conexao.php');
$banco = Conexao :: getConexao();
$sql = "SELECT FIRST 1 DATAHORA FROM AGENDAMENTOSBBM ORDER BY DATAHORA DESC";
$res = $banco->execute($sql);
$dados = $banco->fetch($res);
if($dados)
$currentmodif = $dados['DATAHORA']);
else
$currentmodif = 0;
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
while( $currentmodif <= $lastmodif ){
usleep(10000);
$sql = "SELECT FIRST 1 DATAHORA FROM AGENDAMENTOSBBM ORDER BY DATAHORA DESC";
$res = $banco->execute($sql);
$dados = $banco->fetch($res);
if($dados)
$currentmodif = $dados['DATAHORA']);
else
$currentmodif = 0;
}
$response = array();
$response['timestamp'] = $currentmodif;
echo json_encode($response);
?>
When I insert, update, or delete some data, the timestamp field are updated with the current timestamp.
I can see that the page enters the loop, but I don't know why it never ends.
Am I doing something wrong?
Thank you
I finaly found the solution.
And it was so simple. My code was not closing the connection with ibase_close
What i did was change it to close when finish the query process.
Then inside the loop, i need to reconnect the server again.
OMG how could i forgot that.
Thanks everyone.
Try replacing $currentmodif = $dados['DATAHORA']); with $currentmodif = $dados['HORA']); inside the while loop.
You're asking for an array key that doesn't exist, which will always be null, so your loop will run forever if $lastmodif is not null.
Change $currentmodif = $dados['DATAHORA']);, look:
<?php
set_time_limit(0);
#ini_set("memory_limit",'64M');
require_once('../classes/conexao.php');
$banco = Conexao :: getConexao();
$sql = "SELECT FIRST 1 DATAHORA FROM AGENDAMENTOSBBM ORDER BY DATAHORA DESC";
$res = $banco->execute($sql);
$dados = $banco->fetch($res);
if($dados)
$currentmodif = $dados['DATAHORA']);
else
$currentmodif = 0;
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
while( $currentmodif <= $lastmodif ){
usleep(10000);
$sql = "SELECT FIRST 1 DATA, HORA FROM AGENDAMENTOSBBM ORDER BY DATA DESC,HORA DESC";
$res = $banco->execute($sql);
$dados = $banco->fetch($res);
if($dados)
$currentmodif = $dados['DATA'].$dados['HORA']; // Before : $dados['DATAHORA']);
else
$currentmodif = 0;
}
$response = array();
$response['timestamp'] = $currentmodif;
echo json_encode($response);
?>
I don't know how look of your database design so, i suggest to you to change by yourself
Maybe your mistakes are on that lines. But i can't decide, because i have no time to fix it, i must do my project.
If i'm wrong, I'm sorry. Good luck
After rewriting the code in MySQL and scratching my head over why it seemed to be working just fine, I found the problem:
You need to set your initial var timestamp to 0, not null. If you set it to null, jQuery will send it as the string "null" (?timestamp=null). In PHP, it will compare this string "null" to whatever number $currentmodif is, so in the end you will never get into your while loop.
Try to eval your queries and see what they return, so you can validate the returned data and ensure the array $dados has the needed data and the keys to access any data of the array $dados.
var longpollError = false;
function longPoll(){
$.ajax({
url: "socialPolling",
type: 'GET',
dataType: 'json',
data: {param1: 'value1'},
timeout: 30000 // timeout every 10 sec
}).done(function(dataJson) {
//Success code goes here
})
.fail(function(data) {
longpollError = true; //mark this to true if there is an error
}).always(function(data) {
if(longpollError==false){ //if there is no error request it again
setTimeout(function() {
longPoll();
}, 3000);
}
})
}
I'm trying to write a script in javascript/jquery that will send values to a php file that will then update the database. The problem is that the values aren't being read in by the PHP file, and I have no idea why. I hard-coded in values and that worked fine. Any ideas?
Here's the javascript:
var hours = document.getElementById("hours");
var i = 1;
while(i < numberofMembers) {
var memberID = document.getElementById("member"+i);
if(memberID && memberID.checked) {
var memberID = document.getElementById("member"+i).value;
$.ajax({
type : 'post',
datatype: 'json',
url : 'subtract.php',
data : {hours : hours.value, memberID : memberID.value},
success: function(response) {
if(response == 'success') {
alert('Hours subtracted!');
} else {
alert('Error!');
}
}
});
}
i++;
}
}
subtract.php:
if(!empty($_POST['hours']) AND !empty($_POST['memberID'])) {
$hoursToSubtract = (int)$_POST['hours'];
$studentIDString = (int)$_POST['memberID'];
}
$query = mysql_query("SELECT * FROM `user_trials` WHERE `studentid` = '$studentIDString' LIMIT 1");
Edit: Updated code following #Daedal's code. I'm still not able to get the data in the PHP, tried running FirePHP but all I got was "profile still running" and then nothing.
This might help you:
function subtractHours(numberofMembers) {
var hours = document.getElementById('hours');
var i = 1;
while(i < numberofMembers) {
// Put the element in var
var memberID = document.getElementById(i);
// Check if exists and if it's checked
if(memberID && memberID.checked) {
// Use hours.value and memberID.value in your $.POST data
// {hours : hours.value, memberID : memberID.value}
console.log(hours.value + ' - ' + memberID.value);
// $ajax is kinda longer version of $.post api.jquery.com/jQuery.ajax/
$.ajax({
type : 'post',
dataType : 'json', // http://en.wikipedia.org/wiki/JSON
url : 'subtract.php',
data : { hours : hours.value, memberID : memberID.value},
success: function(response) {
if( response.type == 'success' ) {
alert('Bravo! ' + response.result);
} else {
alert('Error!');
};
}
});
}
i++;
}
}
and PHP part:
$result = array();
// Assuming we are dealing with numbers
if ( ! empty( $_POST['hours'] ) AND ! empty( $_POST['memberID'] ) ) {
$result['type'] = "success";
$result['result'] = (int) $_POST['hours'] . ' and ' . (int) $_POST['memberID'];
} else {
$result['type'] = "error";
}
// http://php.net/manual/en/function.json-encode.php
$result = json_encode( $result );
echo $result;
die();
Also you probably don't want to CSS #ID start with a number or to consist only from numbers. CSS Tricks explained it well http://css-tricks.com/ids-cannot-start-with-a-number/
You can simple fix that by putting some string in front:
var memberID = document.getElementById('some_string_' + i);
This is not ideal solution but it might help you to solve this error.
Cheers!
UPDATE:
First thing that came to my mind is that #ID with a number but as it seems JS don't care about that (at least not in a way CSS does) but it is a good practice not to use all numbers. So whole error was because document.getElementById() only accepts string.
Reference: https://developer.mozilla.org/en-US/docs/DOM/document.getElementById id is a case-sensitive string representing the unique ID of the element being sought.
Few of the members already mentioned converting var i to string and that was the key to your solution. So var memberID = document.getElementById(i); converts reference to a string. Similar thing could
be accomplished I think in your original code if you defined wright bellow the loop while(i < numberofMembers) { var i to string i = i.toString(); but I think our present solution is better.
Try removing the '' fx:
$.post (
"subtract.php",
{hours : hours, memberID : memberID}
try this
$.ajax({type: "POST",
url:"subtract.php",
data: '&hours='+hours+'&memberID='+memberID,
success: function(data){
}
});
Also you could try something like this to check
$(":checkbox").change(function(){
var thisId = $(this).attr('id');
console.log('Id - '+thisId);
});
$studentID = $_GET['memberID'];
$hoursToSubtract = $_GET['hours'];
Try this:
$.post("subtract.php", { hours: hours, memberID : memberID })
.done(function(data) {
document.body.style.cursor = "auto";
});
Try n use this...
$.post("subtract.php", { hours: hours, memberID : memberID })
.done(function(data) {
$(body).css({ 'cursor' : 'auto' });
});
I'm using jquery's ajax function to fetch data from an external php file. The data that is returned from the php file will be used for the autocomplete function. But, instead of the autocomplete function suggesting each particular value from the array in the php file, it returns ALL of them. My jquery looks like this.
jQuery('input[name=past_team]:radio').click(function(){
$('#shadow').fadeIn('slow');
$('#year').fadeIn('slow');
var year = $('#year').val();
$('#year').change(function () {
$('#shadow').val('');
$.ajax({
type: "POST",
url: "links.php",
data: ({
year: year,
type: "past_team"
}),
success: function(data)
{
var data = [data];
$("#shadow").autocomplete({
source: data
});
}
});
});
});
The link.php file looks like this:
<?php
session_start();
require_once("functions.php");
connect();
$type = $_POST['type'];
$year = $_POST['year'];
if($type == "past_team")
{
$funk = mysql_query("SELECT * FROM past_season_team_articles WHERE year = '".$year."'")or die(mysql_error());
$count = mysql_num_rows($funk);
$i = 0;
while($row = mysql_fetch_assoc($funk))
{
$name[$i] = $row['team'];
$i++;
}
$data = "";
for($i=0;$i<$count;$i++)
{
if($i != ($count-1))
{
$data .= '"'.$name[$i].'", ';
} else
{
$data .= '"'.$name[$i].'"';
}
}
echo $data;
}
?>
The autocomplete works. But, it's just that when I begin to enter something in the input field, the suggestion that are loaded is the entire array. I'll get "Chicago Cubs", "Boston Red Sox", "Atlanta Braves", .....
Use i.e. Json to render your output in the php script.
ATM it's not parsed by javascript only concaternated with "," to a single array element. I do not think that's what you want. Also pay attention to the required datastructure of data.
For a working example (on the Client Side see the Remote JSONP example http://jqueryui.com/demos/autocomplete/#remote-jsonp )