Using foreach loop, how can we echo data with ob_start() - php

We have designed a Progress bar, using Jquery Ui. we need a program that can deliver data in numeric value.
That code is not working
PHP CODE
<?php
ob_start();
$array = array(10,20,30,40,50,60,70,80,90,100);
foreach($array as $a ){
echo $a;
sleep(1);
ob_end_clean();
}
echo 100 ;
?>
PHP code for echo a single item, it clears the existing data, so that our Ajax program can get the actual numeric data.
Thanks

You need to send a request to your php script with a parameter if you don't have an actual update:
$(function() {
$("#progressbar").progressbar({ value: 0 });
setTimeout(function(){ updateProgress(0); }, 500);
});
function updateProgress(data) {
$.get(url+'?progress='+data, function(data) {
// data contains whatever that page returns
if (data < 100) {
$("#progressbar").progressbar({value: parseInt(data)});
$("#progresstext").html("<p> Loading...<p>");
setTimeout(function(){ updateProgress(data); }, 500);
} else {
$("#progressbar").progressbar({value: 100});
}
});
}
and your PHP script:
<?php
echo (int)$_GET['progress']+10;
?>

Related

Use jQuery to post data to php file

I am making a search engine.I want to post the data from jquery to php.
Here is my code of jQuery
<script>
$(document).keypress(function(e) {
if(e.which == 13 && $('#textfield').val()) {
$.post("search_result.php",
{
wording: $('#textfield').val()
}, function() {
window.location = "search_result.php";
}
);
}
});
</script>
Here is my code of php to get the wording:
<?php include('../include/common_top.php');
$key_word = $_POST["wording"];
var_dump($key_word);
?>
But what I get is a null value.Please help.
You shouldn't redirect to the PHP script. That runs it a second time, but this time with no POST parameters.
The output of the PHP script from the AJAX request will be the argument to the callback function, you can display it from there.
$(document).keypress(function(e) {
if(e.which == 13 && $('#textfield').val()) {
$.post("search_result.php",
{
wording: $('#textfield').val()
}, function(result) {
$("#somediv").text(result);
}
);
}
})

Ajax loop to get data from $.post each second

Here is my code:
$(document).ready(function(){
$("#pbo").hide();
$('.pie_progress').asPieProgress({
namespace: 'pie_progress',
size: 100,
barsize: '4'
});
$("#getit").click(function(){
$.post("process.php",
{
yurl: $("#yurl").val()
},
function(data,status){
if(data > 0 ) {
$('#yurl').hide();
$('#getit').hide();
$("#pbo").show();
$('h1').hide();
$('.pie_progress').asPieProgress('start');
$('.pie_progress').asPieProgress('go',data);
} else {
$('#yurl').show();
$('#getit').show();
$("#pbo").hide();
}
});
});
});
When I click on my #getit button, it executes process.php and gets the returned data which is in turn passed to $('.pie_progress').asPieProgress('go',data);. My progress bar gets updated with that data, but this only seems to happen once. Is there a way to continue making POST requests until the data value is 100?
Note: in the process.php I have an php exec which echos the progress each second.
What about put the ajax call inside a function (for example: processTo100) and recall it everytime?
Something like this:
$(document).ready(function(){
$("#pbo").hide();
$('.pie_progress').asPieProgress({
namespace: 'pie_progress',
size: 100,
barsize: '4'
});
$("#getit").click(function(){
processTo100();
});
function processTo100() {
$.post("process.php",
{
yurl: $("#yurl").val()
},
function(data,status) {
if(data > 0 ) {
$('#yurl').hide();
$('#getit').hide();
$("#pbo").show();
$('h1').hide();
$('.pie_progress').asPieProgress('start');
$('.pie_progress').asPieProgress('go',data);
if( parseInt(data) <= 100) {
processTo100();
}
} else {
$('#yurl').show();
$('#getit').show();
$("#pbo").hide();
}
});
}
});

PHP Page not getting data sent and not echoing

I have a simple setup that takes a hex value from a color picker converts it to RGB and then sends it to a PHP script from the HTML. The recieving file is not echoing and it is not refreshing either. I probably am doing something wrong but wanted to run it by someone just in case.
Java/Jquery
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
$(document).ready(function() {
var picker = $.farbtastic('#picker');
picker.linkTo(function onColorChange(color) {
var finalcolor=hexToRgb(color);
console.log(finalcolor,"helloworld");
$.post("imagedisplay.php", {var_value: finalcolor});
});
});
RECIEVING PHP
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$hex=$_POST['var_value'];
echo '$hex';
}
?>
When you use AJAX, the page is not refreshed automatically (that's generally the reason you use AJAX instead of normal form submission). You need a callback function in $.post to do something with the response from PHP:
$(document).ready(function() {
var picker = $.farbtastic('#picker');
picker.linkTo(function onColorChange(color) {
var finalcolor=hexToRgb(color);
console.log(finalcolor,"helloworld");
$.post("imagedisplay.php", {var_value: finalcolor}, function(response) {
alert('PHP said: ' + response);
});
});
});
In your PHP, $hex is an associative array. You can't echo an array, use:
print_r($hex);

How to use ajax to update label from count from mysql database

I know ajax is probably the best method to do this.
So, i have this php file which returns a count:
<?php
include('globals.php');
$query = mysqli_query($con, "SELECT COUNT(*) as total FROM solicitacoes WHERE visualizada = 0");
$resultado = mysqli_fetch_array ($query);
$sem_visualizar = $resultado['total'];
return $sem_visualizar;
And i have this on my main page:
<?php
if($_SESSION['funcao_corrente']=="adm" || $_SESSION['funcao_corrente']=="analista"){
echo '<label onclick="mudaIframe();" id="visu" ';
if ($sem_visualizar == 0)
echo 'style="background-color: darkgray; color: black;"';
else if ($sem_visualizar<=5)
echo 'style="background-color: green;"';
else if ($sem_visualizar>5 && $sem_visualizar <= 15)
echo 'style="background-color: orangered;"';
else if ($sem_visualizar>15)
echo 'style="background-color: red;"';
echo '>'.$sem_visualizar.'</label>';
}
?>
Basically it just changes color based on value, but the thing is:
I want it to auto refresh it's own value via the PHP file which returns count, but I have absolutely no idea how can i do this.
I found this code in another answer, but it's not working.
<script>
function get_msg_count(){
$.ajax ({
data: {}, // not really needed
type: 'POST',
url: 'contar_sem_visualizar.php', // page to return your msg count
success: function(response)
{
$('#visu').html(response);
}
}
}); // End $.ajax
} // End Function
// and on DOM ready
$(function(){
// check for new messages every 3 seconds(3000ms)
setInterval(get_msg_count(), 3000)
});
</script>
You can just use $.load to achieve that:
HTML
<span id="count"></span>
jQuery
$("#count").load("contar_sem_visualizar.php");
You need an element to set the count and use jQuery to put the answer in there. The return from your PHP will be retrieved from the jQuery request and ever after a set interval the client's browser will send a request asking for this value, which will be added again to the counter.
You could do that:
function get_count(){
while()
{
$("#counter").load("contar_sem_visualizar.php");
setInterval(3000);
}
}
get_count();

I have encountered a really weird thing while Inserting jquery var in mysql table from a php page

I have a php page where i have used a jquery function to get the dynamic value according to the values of checkboxes and radio buttons and text boxes. Whats' happening is i have used two alerts
1.) alert(data);
2.)alert(grand_total);
in the ajax part of my Jquery function just to ensure what value i'm getting in "grand_total". And everything worked fine, alerts were good and data was being inserted in the table properly.
Then i removed the alerts from the function, and after sometime i started testing the whole site again and i found value of grand_total in not being inserted in mysql table.
I again put those alerts to check what went wrong, again everything started working fine. Removed again and problem started again. Any idea folks what went wrong?
here is the code snippet of JQUERY func from "xyz.php":
<script type="text/javascript">
$(document).ready(function() {
var grand_total = 0;
$("input").live("change keyup", function() {
$("#Totalcost").val(function() {
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).val(), 10);
});
var textVal = parseInt($("#min").val(), 10) || 0;
grand_total = total + textVal;
return grand_total;
});
});
$("#next").live('click', function() {
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
},
success: function(data) {
// do something;
}
});
});
});
Corresponding HTML code:
<form method="post" id="logoform3" action="xyz_sql.php">
<input type="text" name="Totalcost" id="Totalcost" disabled/>
<input type="submit" id="Next" name="next"/>
This the code from *"xyz_sql.php"*:
<?php
session_start();
include ("config.php");
$uid = $_SESSION['uid'];
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2 (total,uid)VALUES('$total','$uid');";
if($total > 0){
$res = mysql_query($sql);
}
if($res)
{
echo "<script> window.location.replace('abc.php') </script>";
}
else {
echo "<script> window.location.replace('xyz.php') </script>";
}
?>
And last but not the least: echo " window.location.replace('abc.php') ";
never gets executed no matter data gets inserted in table or not.
First you submit form like form, not like ajax - cause there is no preventDefault action on clicking submit button. That's why it looks like it goes right. But in that form there is no input named "grand_total". So your php script fails.
Second - you bind ajax to element with id "next" - but there is no such element with that id in your html that's why ajax is never called.
Solutions of Роман Савуляк is good but weren't enough.
You should casting your $total variable to integer in php file and also use if and isset() to power your code, so I'll rewrite your php code:
<?php
session_start();
include ("config.php");
if(isset($_SESSION['uid']))
{
$uid = $_SESSION['uid'];
if(isset($_POST['grand_total']))
{
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2(total,uid) VALUES('".$total."','".$uid."')";
if((int)$total > 0)
{
if(mysql_query($sql))
{
echo "your output that will pass to ajax done() function as data";
}
else
{
echo "your output that will pass to ajax done() function as data";
}
}
}
}
and also you can pass outputs after every if statement, and complete js ajax function like:
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
}
}).done(function(data) {
console.log(data); //or everything
});

Categories