Cannot modify header information even after using the ob_start? [duplicate] - php

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 8 years ago.
I get a warning from my php file on the server not sure what is wrong. I am making an ajax call from my javascript function to the server and it just does not receive any response in xmlhttp.readyState == 4 && xmlhttp.status == 200.
I tried to make the same call to the php file/mysql database located on my local computer it works but it would not work for a remote host. Also, i have a similar php file on the server with just the select clause different and it works there not sure what is wrong here ?
.
Warning: Cannot modify header information - headers already sent by
(output started at
/home2/marshell/public_html/cfv/getuserpostbybusnumber.php:2) in
/home2/marshell/public_html/cfv/getuserpostbybusnumber.php on line 4
.
<?php
ob_start();
header("Access-Control-Allow-Origin: *");
$q = intval($_GET['q']);
$con=mysqli_connect("localhost","ma","Ad","mars","3306");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM cfv_viewbusupdate WHERE BusNumber = ".$q." ORDER BY DatePosted DESC");
while($row = mysqli_fetch_array($result))
{
echo "<P>";
echo "<B><font color=\"3300CC\">#" . $row['DatePosted'] . "</font></B> --";
echo "" . $row['username'] . " posted </br>";
echo "<B>Bus Number . </B>";
echo "<font color=\"CC0033\">" . $row['BusNumber'] . "</font></br><B> Going towards </B>";
echo "<font color=\"CC0033\">" . $row['Direction'] . "</font></br> <B>Stop Name: </B>";
echo "<font color=\"CC0033\">" . $row['StopNames'] ."</font></br><B> Time </B><font color=\"CC0033\">".$row['time']." </font></br><B> Status </B>";
echo "<font color=\"CC0033\">" . $row['Status'] . "</font> ";
echo "</br> <B> Comment's </B>: <font color=\"CC0033\">" . $row['comments'] . "</font>";
echo "</P>";
echo "<hr> ";
}
mysqli_close($con);
?>
.
function updateUserPost(str) {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState < 4) {
showModal();
}
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// $('#select-choice-direction-foruserpost').html(xmlhttp.responseText).selectmenu( "refresh");
hideModal();
document.getElementById("result").innerHTML = xmlhttp.responseText;
//alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "http://www.xyz.uni.me/cfv/getuserpostbybusnumber.php?q="+str, true);
xmlhttp.send();
}

This issue happens when there is white space, Most of the time its before the <?php or <? tag, some time its in one of the include files, mostly at the end of file. make sure you dont have those spaces. Error message shown will point you to that location.
I think it has to do some thing with encoding. I have experienced this issue, while development environment is Windows based most of the time WAMP (Works fine), where as production environment is linux based (Issue occurs). People usually suggest using file encoding as "UTF-8 without BOM" Notepad++ have this option. Some time encoding is changed by FTP client, also check that settings.
I have noticed that WAMP instance has following configuration in php.ini file which ignores the header already send error by buffering the output.
output_buffering = On
if you change it to off on your local environment you might see the header already sent error.
output_buffering = Off

Related

Update HTML table every 5 seconds with mySQL, and PHP?

I have a simple PHP page that sends a query to a mySQL database and displays the data onto a HTML table.
How can I get it to do this every 5 seconds? Currently it does this upon the page loading. The database will have changing data, so am trying to get the code to refresh every 5 seconds to keep the table updated.
How might I go upon doing this?
You need to use a client-side scripting language such as JavaScript to have a webpage do something after it has been served to a client.
Specifically, you will want to use timers and AJAX calls. You may also find the jQuery library useful for abstracting AJAX calls however it is not a requirement.
You need to use javascript ajax. For example ,
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText; // your div
}
}
xmlhttp.open("GET","getdatabase.php",true); //your php file
xmlhttp.send();
}
window.setInterval(function(){
loadXMLDoc();
}, 5000);
</script>
Then in html , you must have a div with specified ID(myDiv) Fpr example:
<body>
<div id="myDiv"></div>
</body>
Then in getdatabase.php you must fetch the value from the database and echo it out. For example,
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Hope it works , see more at www.w3schools.com/
Use javascript timers. From there-on u can periodically run the SQL command to read the databases.
If this problem still arises, I can post some example code.

File upload input from AJAX retrieved file not being detected

I made a dynamically changing HTML form where I can change the type of input of the form between a file upload or a drop down box that is populated from a remote database. The function that calls which input type to be displayed is in AJAX. When I submit the form using the drop down box, the form submits without any problems and performs the update to the database that I programmed it to do. However, when I try to submit the form while trying to upload the file, my error checking script (which are simple if... statements) tells me that it BOTH doesn't detect any file being uploaded and the file already exists on the database. However, when the "already exists on database" error appears, it doesn't return the name of the file that I'm trying to upload like I programmed it to do, so I suspect that my file isn't being submitted properly.
Can someone tell me what I did wrong?
Here's the script I have so far:
File 1: test.php
<html>
<body>
<head>
<script>
function getInput(value)
{
var xmlhttp;
if (value=="")
{
document.getElementById("display").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("display").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","grabtest.php?q="+value,true);
xmlhttp.send();
}
</script>
<?php
// connect to database on server
$con=mysqli_connect("localhost","username","password","database name");
// if there was an error in connecting to the database, display the error
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
</head>
<form enctype="multipart/form-data" action="test2.php" method="POST">
<select id='SelectInput' onchange='getInput(this.value)'>
<option selected value=''>Select</option>
<option value='N'>New File</option>
<option value='E'>Existing File</option>
</select>
<div id="display"></div><br>
<input type="submit" value="Submit">
</form>
<?php
if (!empty($_POST)){
if ($_FILES["file"]["error"] == 0){
$target = 'PathName/TargetFolder/';
$target = $target . basename($FILES['file']['name']);
if (file_exists('PathName/TargetFolder/' . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists on server. ";
}
else{
$upload = $_FILES["file"]["name"];
$select = mysqli_query($con, "Select Files from DB_Table where Files = '$upload'");
if (mysqli_num_rows($select) > 0){
echo $_FILES["file"]["name"] . " already exists in database. ";
}
else{
//script for moving the uploaded file to the proper storage location on the server and adding it to the database
move_uploaded_file($_FILES["file"]["tmp_name"], $target . $_FILES["file"]["name"]);
echo "Stored in: " . $target . $_FILES["file"]["name"] . "<br>";
$insert="INSERT INTO DB_Table (Files) VALUES ('$upload')";
if (!mysqli_query($con,$insert)){
die('Error: ' . mysqli_error($con));
}
echo "Your data has been added to the database";
}
}
if ($_POST['recipe']=="" and !file_exists($_FILES['file']['tmp_name']) and !is_uploaded_file($_FILES['file']['tmp_name'])){
exit("Please select or add the file.");
}
}
mysqli_close($con);
?>
File 2: grabtest.php
<?php
//connect to database on server
$con=mysqli_connect("localhost","username","password","database name");
//if there was an error in connecting to the database, display the error
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$q=$_GET["q"];
if ($q==""){
echo "";
}
elseif ($q=="N"){
echo "Select recipe to upload: <input type='file' name='newfile'>";
}
elseif ($q=="E"){
//creates a dropdown box where you can select desired field
$list = mysqli_query($con, "select * from DB_Table");
echo 'Files: <select name = "Files">';
while ($row = mysqli_fetch_array($list))
{
echo '<option value = "' . $row["ID"] . '">' . $row["Files"] . '</option>';
}
echo '</select><br>';
echo '</form>';
}
//after script is executed, close connection to database
//this improves security by ensuring the connection to the database does not remain open when there is no activity being done to change the data
mysqli_close($con);
?>

AJAX, PHP, MYSQL - innerHTML not working & Neither any Alternatives

I am a noob and i am trying to get this script working. It works perfectly in all browsers except IE. I have tried most of the solutions here on stackoverflow but none of them works for me. I am doing some kiddish mistake somewhere which I am unable to spot. Would request your help.
Also just to let you know the DOM Objects format of using appendchild might not work 100% correctly for me since this script basically passes values from a drop down which shows say numbers from 1 to 10 and based on those numbers it pulls up corresponding charts. So if I am viewing chart 1 then i can go ahead and select the drop down to view chart 3 as well. But if we use the appendchild property, it only allows me to see one of the charts by selecting 1 to 10 and it doesn't work unless I refresh the page. So unless deletechild is used I think it would not work, just my guess. Hence, I have commented that section out and I am using the good old method of innerhtml.
This is my JS function.
function showUser(str) {
debugger;
var xmlhttp = GetXmlHttpObject("Browser does not support HTTP Request");
if (str=="") {
document.getElementById("pairname").innerHTML="";
return;
}
/* <-- I HAVE ALREADY COMMENTED THIS OUT & am using a more robust function for this.
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
*/
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("pairname").innerHTML=xmlhttp.responseText;
//AS YOU CAN SEE THE ALTERNATIVE SOLUTION OF USING DOM OBJECTS HAS BEEN COMMENTED OUT.. SINCE THIS IS ALSO NOT WORKING IN IE FOR ME.
//var wrappingElement = document.createElement("div");
//wrappingElement.innerHTML = xmlhttp.responseText;
//document.getElementById('pairname').appendChild(wrappingElement);
}
}
xmlhttp.open("GET","getimgdetails.php?q="+str,true);
xmlhttp.send();
}
function GetXmlHttpObject(errorMessage) {
var r = false;
try { r = new XMLHttpRequest(); }// Opera 8.0+, Firefox, Safari
catch(e) {
// Internet Explorer Browsers
try { r = new ActiveXObject("Msxml2.XMLHTTP"); }// older IE
catch(e) {
try { r = new ActiveXObject("Microsoft.XMLHTTP"); }// IE 5+
catch(e) {// AJAX not possible
if(errorMessage) { alert(errorMessage); }
}
}
}
return r;
}
AND THIS IS WHERE I AM SHOWING IT
<div id="pairname"><b>Charts will be shown here.</b></div>*
AND this is the Script which receives and sends back the info. SO basically it shows 5 charts for each number 1 to 10.
$q=$_GET["q"];
Echo "<img src=mqluploads/".$q."15.gif?".time()."></img>";
Echo "<br>";
Echo "---------------------------------------------------------";
Echo "<br>";
Echo "<img src=mqluploads/".$q."60.gif?".time()."></img>";
Echo "<br>";
Echo "---------------------------------------------------------";
Echo "<br>";
Echo "<img src=mqluploads/".$q."240.gif?".time()."></img>";
Echo "<br>";
Echo "---------------------------------------------------------";
Echo "<br>";
Echo "<img src=mqluploads/".$q."1440.gif?".time()."></img>";
Echo "<br>";
Echo "---------------------------------------------------------";
Echo "<br>";
Echo "<img src=mqluploads/".$q."10080.gif?".time()."></img>";
Echo "<br>";
Echo "---------------------------------------------------------";
Echo "<br>";
Echo "<img src=mqluploads/".$q."43200.gif?".time()."></img>";
Echo "<br>";
Echo "---------------------------------------------------------";
Echo "<br>";
?>
Many many thanks in advance for your help and for reading this far. I have been struggling with this for the past one week and now finally decided to seek some help. Looking forward to your advice.
Have you checked that your php script is returning some data. Try to access getimgdetails.php?q=str (replace str with correct paremeter) directly in browser.
Also place an alert(xmlhttp.responseText) before this line:
document.getElementById("pairname").innerHTML=xmlhttp.responseText;
This will help you to debug.

AJAX XMLHttpRequest 'bouncing back' when sending vars to PHP

I apologize if I don't articulate my problem correctly, but I'll give it my best shot. I've been looking all over the net for info which can help me with this issue, to no avail.
Just a bit of background. I'm an experienced web coder, though haven't done webwork in a few years prior to this, I have done a fair bit of work in PHP and javascript before and these days I work with C++, so I'm fairly experienced with programming principles.
I'm building some blog software, and inb4wordpress and jQuery, I simply don't care. So spare it please... I'm loading some blog entries into an element through a simple AJAX request function. This function is detailed below: ( It's been changed to a 3 function example I found on the net while I was trying to debug this issue, no one's 'simple' code seems to work. )
The problem is detailed beneath the code.
var httpObject = null;
function getHTTPObject(){
if(window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if(window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}
function setOutput(){
if(httpObject.readyState == 4){
document.getElementById("entries").innerHTML = httpObject.responseText;
}
}
function loadEntries(s) {
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("GET","entries.php?" + s,true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput;
}
}
Simple stuff? I can't seem to see any errors there. This is how the function is called:
<div id='entries'>
<script type="text/javascript">
loadEntries('blog=<?php echo $process['id']; ?>&page=0');
</script>
</div>
also simple.
Here's the PHP code for 'entries.php':
<?php
require_once('inc/bloginc.php');
if(isset($_GET['page'])) {
$page = intval($_GET['page']);
} else $page = 0;
$entries = 3;
$init = $page * $entries;
$limit = $entries + $init;
if(!isset($_GET['blog'])) die("WTF DIE");
else $blog = mysql_real_escape_string($_GET['blog']);
$tag = '';
if(isset($_GET['tag'])) {
$tag = mysql_real_escape_string($_GET['tag']);
echo "<span class='blogEntryBody'>viewing entries tagged with: '" . $tag . "' / <a href='' onclick=\"";
echo "loadEntries('blog=" . $blog . "')";
echo "\">clear?</a></span></br>";
echo "<hr>";
}
$numposts = nResults($blog, $tag);
buildEntries(getEntries($blog, $tag, $init, $limit));
if($numposts > $entries) {
echo "</br><span class='blogEntryBody'>";
if($page > 0) {
echo "<a href='' onClick=\"";
echo "loadEntries('blog=" . $blog;
if(isset($_GET['tag'])) echo "&tag=" . $tag;
echo "&page=" . (--$page) . "')";
echo "\">Previous Entries</a>";
echo " / ";
}
echo "<a href='' onClick=\"";
echo "loadEntries('blog=" . $blog;
if(isset($_GET['tag'])) echo "&tag=" . $tag;
echo "&page=" . (++$page) . "')";
echo "\">Next Entries</a>";
echo "<br></span>";
}
?>
okay, now here's where things get tricky:
When sending vars to 'entries.php', such as: entries.php?blog=walk&page=1
They intermittently work, some of these work, but some don't.
I know it's not the PHP code, since loading entries.php up in a new window and manually passing these vars elicits the desired results. What happens is that the HTTP GET request returns 'undefined' in Firefox webdev console, such as this:
[14:47:33.505] GET http://localhost/meg/entries.php?blog=walk&tag=lorem [undefined 2ms]
^ The 'tag' variable usually works, it's normally the 'page' variable that sends everything haywire.
What happens is, after clicking 'next page', you quickly see a blank div, and then it quickly bounces back to the previous state. You see all this loading in the console. It'll return 'undefined' then reload the previous state. Which is just puzzling.
I don't understand why this would be occurring.
I hope I've provided enough information, and set it out in an easy to understand format. I'm new to asking questions. I usually just 'googleit' or RTM. But I think maybe this time someone else will have seen this before.
Oh, and I've tested in chrome, same issue. I'm really puzzled, but open to the possibility that maybe I've overlooked something small and crucial.
Thanks!
Well it happens few times that ajax doesn't works in chrome & explorer so my suggestion to use jquery because in jquery they already include codes for explorer and chrome.
you can use
$.get , $.post or $.ajax methods easily.

Cannot modify header information [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Headers already sent by PHP
I am getting the following error from the following code, and I am not entirely sure why. If you could tell me how to fix it, that would be great. Thanks in advanced.
Warning: Cannot modify header information - headers already sent by (output started at...) on line 45.
<?php
// Initialization
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
mysql_select_db(DB_NAME, $conn);
// Error checking
if(!$conn) {
die('Could not connect ' . mysql_error());
}
// Localize the GET variables
$ref = isset($_GET['ref']) ? $_GET['ref'] : "";
// Protect against sql injections
// Insert the score
$retval = mysql_query("INSERT INTO $table(
site
) VALUES (
'$ref'
)",$conn);
if($retval) {
echo "Successfull";
} else {
echo "Unsuccessfull " . mysql_error();
}
mysql_close($conn);
?>
<?php
$url = $_GET['url'];
$loc = 'Location: '. $url;
header($loc);
exit;
?>
Take out the echo calls, you can't send information to the browser before the headers.
You can try something like this to still show if an error happens:
if(!$retval) {
echo "Unsuccessfull " . mysql_error();
}
If you change the headers you cannot output any text prior to to the header command otherwise the headers will already be sent.
ie.
if($retval) {
echo "Successfull";
} else {
echo "Unsuccessfull " . mysql_error();
}
Is outputting text before you change the headers.
Use Output Buffers: http://php.net/manual/en/function.ob-start.php
ob_start();
at the start and
ob_end_flush();
at the end.
What I generally recommend for situations like this, is save all output to the end, as gmadd mentioned, you can do the ob_start, but I prefer to store the data in a string without having to add the extra code (I know you can also designate this in the .htaccess file, I would go that route over adding the actual ob_start items).
What I would do:
$display = ""; // initiate the display string
// etc doe here
if($retval) {
$display .= "Successfull";
} else {
$display .= "Unsuccessfull " . mysql_error();
}
// end of the script right before ?>
echo $display;
?>
The ob_start method works and if you want to go that route, you can add this in the .htaccess file (given that allowoverride is set in your apache setup):
php_value output_buffering On
Again I still recommend the $display storage method, but that is my personal opinion.
Use:
<meta http-equiv="Refresh" content="0;url=http://www.example.com" />

Categories