Ajax timed update issue - php

Simply I have a menu bar with an animated notification badge made by CSS and implemented by SPAN class on the HTML. this badge should show the count of new messages and disappear if that count is 0. I need to check that every 1 second but with no luck.
my js:
<script type="text/javascript">
function removeAnimation(){
setTimeout(function() {
$('.bubble').removeClass('animating')
}, 200);
}
setInterval(function() {
$.ajax({
type: 'GET',
url: 'models/bubble.php',
data: 'html',
success: function(response){
document.getElementById("bub").innerHTML=response;
document.getElementById("bub").className = "bubble";
}
error: function(response) {
document.getElementById("bub").className = "hidden";
});
}
}, 1000);
</script>
my php (working and tested):
<?php
require_once("db.php");
$receiver = $this_user
$isnew = 1;
$stmt = $mysqli->stmt_init();
if ($stmt->prepare("SELECT * FROM messenger
WHERE receiver = ? AND isnew = ? ORDER BY timestamp")) {
$stmt->bind_param("si", $receiver,$isnew);
$stmt->execute();
$stmt->store_result();
$ttlrows = $stmt->num_rows;
$stmt->close();
}
echo $ttlrows;
?>
any help?

Below works for me. You need to call the function inside success again as setTimeout/setInterval will call the function only once after the delay you mentioned
setTimeout('pullNewMessageCount()', 100);
function pullNewMessageCount() {
var url = 'PHP Url';
$.ajax({
url: url,
dataType: 'html',
data:{
"whatever data you want to send, skip it if not require",
},
type: 'POST',
success: function(latestCount) {
setTimeout('pullNewMessageCount()', 100);// Important comment (this what you need to do)
},
error: function(jqXHR, textStatus, errorThrown) {
}
});
}

Related

Run two ajax calls at the same time?

If I have one ajax call with a long foreach loop where I update a text file, and at the same time I want to read that file and display changed content from the first call by another second call, how can I achieve that?
When the first runs, the second waits until the first one has finished.
I want to run the first and second at the same time. In the second call, every second I want to check the state inside the file created by the first call - something like a progress bar.
function startTimer(){
timer = window.setInterval(refreshProgress, 1000);
}
function refreshProgress(){
$.ajax({
type: "POST",
url: '/index.php?/system/run_progress_checker',
dataType:"json",
success: function(data)
{
console.log(data);
if (data.percent == 100) {
window.clearInterval(timer);
timer = window.setInterval(completed, 1000);
}
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
function completed() {
//$("#message").html("Completed");
window.clearInterval(timer);
}
$(".systemform").submit(function(e) { //run system
$.when(startTimer(),run_system()).then(function(){});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
function run_system(){
$("#leftcontainer").html("");
$("#leftcontainer").show();
$("#chartContainer").hide();
$(".loading").show();
var sysid = $(".sysid:checked").val();
var oddstype = $(".odds_pref").val();
var bettypeodds = $(".bet_type_odds").val();
var bookie = $(".bookie_pref").val();
if (typeof oddstype === "undefined") {
var oddstype = $(".odds_pref_run").val();
var bettypeodds = $(".bet_type_odds_run").val();
var bookie = $(".bookie_pref_run").val();
}
$.ajax({
type: "POST",
url: '/index.php?/system/system_options/left/'+'1X2/'+oddstype+'/'+bettypeodds+'/'+bookie,
data: {
system : sysid,
showpublicbet : showpublicbet }, // serializes the form's elements.
dataType:"json",
success: function(data)
{
console.log(data);
$("#systemlist").load('/index.php?/system/refresh_system/'+sysid,function(e){
systemradiotocheck();
});
$("#resultcontainer").load('/index.php?/system/showresults/'+sysid+'/false');
$("#resultcontainer").show();
$("#leftcontainer").html(data.historic_table);
$("#rightcontainer").html(data.upcoming_table);
var count = 0;
var arr = [];
$("#rightrows > table > tbody > tr").each(function(){
var row = $(this).data('row');
if(typeof row !== 'undefined'){
var rowarr = JSON.parse(JSON.stringify(row));
arr[count] = rowarr;
$(this).find('td').each(function(){
var cell = $(this).data('cell');
if(typeof cell !== 'undefined'){
var cellarr = JSON.parse(JSON.stringify(cell));
arr[count][6] = cellarr[0];
}
});
count ++;
}
});
if(oddstype == "EU" && bookie == "Bet365"){
$('.bet365').show();
$('.pinnacle').hide();
$('.ukodds').hide();
}
if(oddstype == "EU" && bookie == "Pinnacle"){
$('.pinnacle').show();
$('.bet365').hide();
$('.ukodds').hide();
}
if(oddstype == "UK"){
$('.bet365').hide();
$('.pinnacle').hide();
$('.ukodds').show();
}
if(bookie == "Pinnacle"){
$(".pref-uk").hide();
}
else{
$(".pref-uk").show();
}
$(".loading").hide();
runned = true;
var options = {
animationEnabled: true,
toolTip:{
content: "#{x} {b} {a} {c} {y}"
},
axisX:{
title: "Number of Games"
},
axisY:{
title: "Cumulative Profit"
},
data: [
{
name: [],
type: "splineArea", //change it to line, area, column, pie, etc
color: "rgba(54,158,173,.7)",
dataPoints: []
}
]
};
//console.log(data);
var profitstr = 0;
var parsed = $.parseJSON(JSON.stringify(data.export_array.sort(custom_sort)));
var counter = 0;
for (var i in parsed)
{
profitstr = profitstr + parsed[i]['Profit'];
//console.log(profitstr);
var profit = parseFloat(profitstr.toString().replace(',','.'));
//console.log(profit);
var event = parsed[i]['Event'].toString();
var hgoals = parsed[i]['Home Goals'].toString();
var agoals = parsed[i]['Away Goals'].toString();
var result = hgoals + ":" + agoals;
var date = parsed[i]['Date'].toString();
var bettype = parsed[i]['Bet Type'];
var beton = parsed[i]['Bet On'];
var handicap = parsed[i]['Handicap'];
//alert(profitstr);
//alert(profit);
//options.data[0].name.push({event});
counter++;
options.data[0].dataPoints.push({x: counter,y: profit,a:event,b:date,c:result});
}
$("#chartContainer").show();
$("#chartContainer").CanvasJSChart(options);
$(".hidden_data").val(JSON.stringify(data.export_array));
$(".exportsys").removeAttr("disabled");
$(".exportsys").removeAttr("title");
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
Backend part is not so important because it works.
Sounds like a great case for jQuery's $.when $.then. In the first part, the $.when, you'll have the first ajax call, and when that is finished... you can port the data from the first part to the $.then part. For example:
$.when(
//perform first ajax call and pass this data to the 'then'.
$.ajax(
{
type: "POST",
url: "<<insert url>>",
contentType: "application/json; charest=utf-8",
success: function (data) {
//process data
},
error: function (XMLXHttpRequest, textStatus, errorThrown) {
}
})
).then(function (data, textStatus, jqXHR) {
var obj = $.parseJSON(data); // take data from above and use it to perform second ajax call.
var params = '{ "CustomerID": "' + obj[0].CustomerID + '" }';
$.ajax(
{
type: "POST",
url: "<<insert url>>",
data: params,
contentType: "application/json; charest=utf-8",
success: function (data) {
//process data
},
error: function (XMLXHttpRequest, textStatus, errorThrown) {
}
})
});
}
});

Post simple form with ajax and Json

I'm trying to get a form to work with Ajax and json but can't seem to work it out:(
If anyone can help out I'd really appreciate it! Been reading so many different tutorials but not getting it right.
In my index.php I have a form with only a image that works as a button.
Then in another file (allFunctions.php) I have a class. Within that class I have a function called
giveCandy() which is connected to the button.
Then I have a js file that I'm now trying to get working with this. But When I click the button the page still refreshes and I get the value true printed out.
UPDATE: Still problem with the page refreshing...
The index.php file:
<form action="index.php" method="POST">
<input type="hidden" name="candy" />
<input type="image" id="button_candy" class="four columns" src="views/img/candy.png"/>
</form>
Then in my functions file:
function giveCandy ()
{
if ( isset($_POST['candy']))
{
$db = Database::getInstance();
$classUser = new user();
$userId = $classUser->getUserData($_SESSION['id']);
$user = $userId['id'];
$candyPiece = 10;
$query = $db->prepare("SELECT fullness, lastfed FROM userdata WHERE id = ?");
$query->bindValue(1, $user);
$query->execute();
$data = $query->fetch();
$newFullness = $candyPiece + $data['fullness'];
try
{
$query = $db->prepare("UPDATE userdata SET fullness = $newFullness, lastfed = CURRENT_TIMESTAMP WHERE id = ?");
$query->bindValue(1, $user);
$query->execute();
//$this->calculateFullness();
echo json_encode($query);
}
catch (PDOException $e)
{
echo 'Sorry iti could not eat at this time';
}
}
}
Then the js file:
$(document).ready(function () {
$('#button_candy').click(function (event) {
event.preventDefault();
$.ajax({
url: 'index.php',
method: 'POST',
data: $(this).serialize(), // your formdata (this refers to the form element)
dataType: 'json',
success: function (data) { // data is what your allFunctions.php php echos
$('#query').fadeOut(function () {
$('#query').html(data).fadeIn();
});
console.log('Ajax request returned successfully.');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('Ajax request failed: ' + textStatus + ', ' + errorThrown);
},
});
});
});
allFunctions.php:
if ($_POST['candy']) {
allFunctions::giveCandy();
}
class allFunctions {
static function giveCandy ()
{
$db = Database::getInstance();
// ....
Js:
$(document).ready(function () {
$('#button_candy').submit(function (event) {
event.preventDefault();
$.ajax({
url: '../model/allFunctions.php',
method: 'POST',
data: $(this).serialize(), // your formdata (this refers to the form element)
dataType: 'json',
success: function (data) { // data is what your allFunctions.php php echos
$('#result').fadeOut(function () {
$('#result').html(data).fadeIn();
});
console.log('Ajax request returned successfully.');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('Ajax request failed: ' + textStatus + ', ' + errorThrown);
},
});
});
});

How to handle json response from php?

I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);

jQuery Success Function doesn't alert

here is the problem, I have the following function
$(document).ready(function() {
$('#selectTypeDD').change(function() {
var type = $("#selectTypeDD option:selected").text();
changeType(type);
alert(type);
});
});
The alert prints out pub when I choose city of my drop down menu.
changeType is this function
function changeType(type)
{
$.ajax
({
type: 'GET',
url: 'webservice.php',
data: {type: type},
success: function(response, textStatus, XMLHttpRequest)
{
alert("SUCCESS");
}
});
}
I get this result here in Firebug
pub[{"name":"The Master Builder","lon":"-1.34532","lat":"50.9303"},{"name":"Goblets","lon":"-1.40455","lat":"50.9088"},{"name":"Rat and Parrot","lon":"-1.40442","lat":"50.9085"},{"name":"The Victory Inn","lon":"-1.31415","lat":"50.8588"},{"name":"The King and Queen","lon":"-1.31356","lat":"50.8586"}
The list goes on and on, but I think those are the most important ones. The problem is now, that I want to do something with the result and it didn't work, so I tested why it is so, and typed in the alert("SUCCESS") in the success-function. But it doesn't even print out the alert. Why? What am I doing wrong? The werbservice runs without problems. When I open my site localhost/blabla/webservice.php?type=pub it prints out everything. So what could be the problem?
Here is the party of my webservice
else if(isset($_GET['type']))
{
$type = $_GET['type'];
echo $type;
if($result = $mysqli->query("SELECT name, lon, lat FROM pointsofinterest WHERE type = '".$type."'"))
{
$tempArray = array();
while($row = $result->fetch_assoc())
{
$tempArray = $row;
array_push($array, $tempArray);
}
echo json_encode($array);
}
}
change your
success: function(response, textStatus, XMLHttpRequest)
to
success: function(response)

can't get AJAX get call to work even so the code seems correct

Ok fixed jQuery code with help of others on stack overflow
$(document).ready(function() {
$(".note").live('click',function() {
$("#note_utm_con").show();
$("#note_utm_nt").html("<img src='http://www.ajaxload.info/images/exemples/4.gif' />");
$.ajax({
type: "GET",
url: "view.php",
data: "ajax=1&nid=' + parent.attr('id').replace('record-','')",
success: function(html){
$("#note_utm").html(html);
$("#note_utm_nt").html("");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#note_utm_nt").html("<img src='http://www.ajaxload.info/images/exemples/4.gif' /> Error...");
}
});
});
});
The PHP code for view.php
include 'object/db.class.php';
if($_GET['ajax'] == '1') {
#make a call to my sql to fetch some sort of ID
$nid = $_GET['nid'];
$q = mysql_query("SELECT * FROM `notice` WHERE nid = '".$nid."'");
$a = mysql_fetch_array($q);
$nid = stripslashes($a['nid']);
$note = stripslashes($a['note']);
$type = stripslashes($a['type']);
$private = stripslashes($a['private']);
$date = stripslashes($a['date']);
$author = stripslashes($a['author']);
$note_viewer .= <<<NOTE_VIEWER
<h2>By: $author</h2> - <h2>$date</h2>
<br/>
<p>$note</p>
<p>Request: $private</p>
NOTE_VIEWER;
echo $note_viewer;
}
The AJAX seems to be working now as it gives me Error...
concerning the docu of jQuery, you attach an event with the live() method. In your code, you define the click-method of node twice, I think: once with the live-attaching-stuff and once with note.click(). So it is not clear what to do when clicking or better when node is clicked, the click-event is defined :-) You define two different actions when note is clicked... try this one:
$(document).ready(function() {
$(".note").live('click',function() {
$("#note_utm_con").show();
$("#note_utm_nt").html("<img src='http://www.ajaxload.info/images/exemples/4.gif' />");
$.ajax({
type: "GET",
url: "view.php",
data: "ajax=1&nid=' + parent.attr('id').replace('record-',''),
success: function(html){
$("#note_utm").html(html);
$("#note_utm_nt").html("");
}
});
});
});
So what exactly is it doing? and What element is not visible? Your AJAX call isnt even using the response. If I understand your logic correctly, it should be...
$.ajax({
type: "GET",
url: "view.php",
data: "ajax=1&nid=' + parent.attr('id').replace('record-',''),
success: function(html){
$("#note_utm").html(html);
$("#note_utm_nt").html(html);
}
});
the "html" variable in the success function is the response from the php script.

Categories