So I looked into other threads but didnt find a solution that worked for me.
Here is my problem:
I have two php pages:
http://codepad.org/VhblM76K and
http://codepad.org/W9bz8L3E.
The first page is supposed to get information from a form, look for it in a database, store it in a variable $_SESSION['$dataArray'] and send it to the second page.
On the second page I get the information in javascript from php with json_encode, which gives an error:
Uncaught SyntaxError: Unexpected token < result.php:20.
When I look in the source in chrome it says:
var schoolData = <br />
<b>Notice</b>: Undefined index: $dataArray in <b>C:\xampp\htdocs\highschools.bg\result.php</b> on line <b>23</b><br />
null;
How is this an unidentified index, when i can only go to the second page after visiting the first one, where I assing a value to $_SESSION['$dataArray'].
How can I fix this? I have written session_start() in both pages and it didnt work for me.
I need the variable schoolData to show the information on the page.
The reason why you're getting the error is because you're not setting any session data, because you are redirecting directly to the second page from the form.
You need to update the form so it redirects back to the same page the form is on, then replace your PHP code with the following:
if (isset($_POST['submit'])) {
$user = 'root';
$pass = '';
$db = 'highschools';
$con = mysqli_connect('localhost', $user, $pass, $db) or die("Unable to connect");
if (mysqli_connect_errno()) {
echo("Failed to connect to MySQL: " . mysqli_connect_error());
}
$givenCity = $_POST['city'];
$givenClass = $_POST['class'];
$givenName = $_POST['name'];
$result = mysqli_query($con,
"SELECT * FROM highschools WHERE name like '%$givenName%' AND city like '%$givenCity%' AND class like '%$givenClass%'; ") or die(mysqli_error($con));
$row_count = mysqli_num_rows($result);
$_SESSION['dataArray'] = array();
while($row_count > 0) {
$curRow = mysqli_fetch_array($result);
$_SESSION['dataArray'][] = $curRow;
$row_count--;
}
header('location: http://YOUR_SECOND_PAGE_ADDRESS');
Notice, the only line I've added is the last line, hedaer('location: ... ');
Don't forget to change the http://YOUR_SECOND_PAGE_ADDRESS to the actual page address of your second piece of code.
Then in the second page, replace $_SESSION['$dataArray'] with $_SESSION['dataArray']
and it should work.
Your problem is that you are writing the session as $_SESSION['$dataArray']. If you have a variable somewhere called $dataArray then you need to write it $_SESSION[$dataArray].
Alternately, if you don't have a variable named $dataArray, then you need to write it as $_SESSION['dataArray'].
EDIT:
Try print_r($_SESSION) beneath the session_start() at the top of the page and see if you have set that the $_SESSION['dataArray']:
<?php
session_start();
// See if the session contains your $_SESSION['dataArray']
// If not, you can force it to have a default value to avoid errors
print_r($_SESSION);
$_SESSION['dataArray'] = (isset($_SESSION['dataArray']))? $_SESSION['dataArray']:array(); ?>
<!DOCTYPE html>
<html>
<head>
<title>Намерени училища</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="styles/main.css">
</head>
<body>
<div id="contentWrapper" style="height:1000px;">
<header id="pageHeader">
</header>
<section id="schoolsContainer">
<ul id="schoolsList"></ul>
</section>
</div>
<script type="text/javascript" src="handlebars-v2.0.0.js"></script>
<script type="text/javascript" src="navTemplate.js"></script>
<script type="text/javascript">
var schoolData = <?php echo json_encode($_SESSION['dataArray']) ?>;
for (var i = 0; i < schoolData.length; i++) {
console.log(schoolData[i]['name']);
console.log(schoolData[i]['id']);
}
</script>
</body>
</html>
On the other page, this also has to be set before it works:
$_SESSION['dataArray'] = array();
while($row_count > 0) {
$curRow = mysqli_fetch_array($result);
$_SESSION['dataArray'][] = $curRow;
$row_count--;
}
Related
Goodday,
I am facing a problem fetching send POST messages from postman on my local server. When i send an POST message the postman preview function prints my send data. However the webpage itself doesn't see the data and prints an error.
Postmand screenshot
Server screenshot
Here is my PHP script:
<head>
<title>PHP test page</title>
<h1>Number</h><br>
</head>
<body>
<?php
//$i = 0;
$data = $_POST["par"];
//while($data == ""){
//if($i == 0){
// echo "No data available";
//}
//$i = 1;
//}
echo $data;
//$page = $_SERVER['PHP_SELF'];
//$sec = "1";
//header("Refresh: $sec; url=$page");
?>
</body>
I am not experienced with this kind of stuff and am obviously missing something.
Why does the data not appear on the webpage itself?
Greetings
On your webpage, you're probably not sending it as a POST request.
Try debugging:
var_dump($_POST); // Add this. $_POST probably doesn't have an index called "par"
$data = $_POST["par"];
echo $data
You need to POST "par" variable to this page.
I tried to write a script mixing something I found on the internet in order to autosave a form data to the mysql db... Something went wrong cause the script it is able to insert but for some reason not to update so every 20 sec (the time I set up) is generating a new row... Can anyone help me to find and solve the issue?
Here is the code:
<?php
session_start();
unset($_SESSION['article_id']);
require_once('xajax/xajax_core/xajax.inc.php');
$xajax = new xajax();
function savetodb($form) {
$title = $form["title"];
$editor = $form["editor1"];
//$host = 'localhost';
//$username = 'my_user';
//$password = 'my_pass';
//$database = 'test_db';
//$connect = mysql_connect($host, $username, $password);
//mysql_select_db($database, $connect);
if ($_SESSION['article_id']=="") {
$sql = "INSERT INTO draft (`title`, `content`) VALUES ('$title', '$editor')";
$result = mysql_query($sql, $connect);
$idlast = mysql_insert_id($connect);
$_SESSION['article_id'] = $idlast;
} else {
$article_id = $_SESSION['article_id'];
$sql = "UPDATE draft SET `title`='$title',`content`='$editor' WHERE `id`='$article_id'";
$result = mysql_query($sql, $connect);
}
// Instantiate the object xajaxResponse
$objResponse = new xajaxResponse();
$objResponse->assign("autosavemsg","innerHTML", "<br />Record saved to database successfully!");
$objResponse->alert('Done!');
return $objResponse;
}
//$xajax->register(XAJAX_FUNCTION,'savetodb');
$xajax->registerFunction('savetodb');
$xajax->processRequest();
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<?php $xajax->printJavascript('xajax'); ?>
</head>
<body>
<form name="form" id="form" enctype="multipart/form-data">
<?php
echo '<label>Title</label><input type="text" name="title" id="title"><br /><br />';
echo '<textarea name="editor1"></textarea>' ;
?>
<input type="button" name="save" onclick="xajax_savetodb(xajax.getFormValues('form'));" value="Save to Database">
</form>
<div id="autosavemsg"></div>
<script language="Javascript">
//Interval
var AutoSaveTime=20000;
//time object
var AutoSaveTimer;
SetAutoSave();
function SetAutoSave() {
AutoSaveTimer=setInterval("xajax_savetodb(xajax.getFormValues('form'));",AutoSaveTime);
}
</script>
</body>
</html>
Unfortunately is not even give to me the alert "done" or the message that I set..
Probably something wrong with the session??
thanks in advance
I'm not familiar with xajax but referring to my logic, I think you are doing it wrong.
I think you have to have two different files, one is your HTML and javascript and other one is your server-side code which is responsible for inserting or updating the db.
right now as I think you are calling the file itself with ajax and in the third line of the code you have unset($_SESSION['article_id']); which will unset the session variable $_SESSION['article_id'] each time you call the ajax.
so I think you have to make two different files.
file1.php
you have your html and javascript files in it and also have the unset($_SESSION['article_id']); line in it.
files2.php you have your php and db related functions in it and delete the unset($_SESSION['article_id']); line from it.
you also have to set in file1.php that your ajax should call file2.php
I think this will do the trick
I am trying to learn some new stuff and always wanted to learn how to make a website with PHP and mysql...
I found this easy tutorial and sample files to play with
http://css-tricks.com/php-for-beginners-building-your-first-simple-cms/
I'm trying to add another table it works in the database but when I try to display it it don't work. Here is the code I got and using:
<?php
class simpleCMS {
var $host;
var $username;
var $password;
var $table;
public function display_public() {
$q = "SELECT * FROM laptopvoltage ORDER BY created DESC LIMIT 3";
$r = mysql_query($q);
if ( $r !== false && mysql_num_rows($r) > 0 ) {
while ( $a = mysql_fetch_assoc($r) ) {
$lvmodel = stripslashes($a['lvmodel']);
$lvmanuf = stripslashes($a['lvmanuf']);
$lvvolt = stripslashes($a['lvvolt']);
$entry_display .= <<<ENTRY_DISPLAY
<div class="post">
<h2>
$lvmodel
</h2>
<p> !!!!!!this dont show upp!!!!!! - - - - >>>>>
$lvmanuf
</p><----------- WHY?
<p>
$lvvolt
</p>
</div>
ENTRY_DISPLAY;
}
} else {
$entry_display = <<<ENTRY_DISPLAY
<h2> This Page Is Under Construction </h2>
<p>
No entries have been made on this page.
Please check back soon, or click the
link below to add an entry!
</p>
ENTRY_DISPLAY;
}
$entry_display .= <<<ADMIN_OPTION
<p class="admin_link">
Add a New Entry
</p>
ADMIN_OPTION;
return $entry_display;
}
public function display_admin() {
return <<<ADMIN_FORM
<form action="{$_SERVER['PHP_SELF']}" method="post">
<label for="lvmodel">Title:lv model</label><br />
<input name="lvmodel" id="lvmodel" type="text" maxlength="150" />
<div class="clear"></div>
<label for="lvmanuf">Title:lv manu</label><br />
<input name="lvmanuf" id="lvmanuf" type="text" maxlength="150" />
<div class="clear"></div>
<label for="lvvolt">Title:lvvolt</label><br />
<input name="lvvolt" id="lvvolt" type="text" maxlength="150" />
<div class="clear"></div>
<input type="submit" value="Create This Entry!" />
</form>
<br />
Back to Home
ADMIN_FORM;
}
public function write($p) {
if ( $_POST['lvmodel'] )
$lvmodel = mysql_real_escape_string($_POST['lvmodel']);
if ( $_POST['lvmanuf'] )
$lvmanuf = mysql_real_escape_string($_POST['lvvolt']);
if ( $_POST['lvvolt'] )
$lvvolt = mysql_real_escape_string($_POST['lvvolt']);
if ( $lvmodel && $lvmanuf && $lvvolt ) {
$created = time();
$sql = "INSERT INTO laptopvoltage VALUES('$lvmodel','$lvmanuf','$lvvolt','$created')";
return mysql_query($sql);
} else {
return false;
}
}
public function connect() {
mysql_connect($this->host,$this->username,$this->password) or die("Could not connect. " . mysql_error());
mysql_select_db($this->table) or die("Could not select database. " . mysql_error());
return $this->buildDB();
}
private function buildDB() {
$sql = <<<MySQL_QUERY
CREATE TABLE IF NOT EXISTS laptopvoltage (
lvmodel VARCHAR(150),
lvmanuf TEXT,
lvvolt VARCHAR(150),
created VARCHAR(100)
)
MySQL_QUERY;
return mysql_query($sql);
}
}
?>
it just wont show $lvmanuf. Any help on this would be great as the fields are showing up in my database.
this first file only shows results, if your not to familiar with web logic and design then ill try my best to explain, this first file is called index.php, every website and web-application has a file either call index.html or index.php the reason behind this is that the web server looks for a file named either index.html or index.php and dont misunderstand there are more than just these file types and names a server can start off of its just that these are the most common, since that is out of the way now i will explain the code behind the first file.
as you can see we have set up our basic html document inside and added a script, now the script we made will make the files that are loaded inside the id we specified disappear after a set ammount of seconds, next inside the body of the html we put this code,
<span id="messages">
<?php include "constant.php"; ?>
</span>
this code contains to main players for this script first the span tag with the id attribute tells our javascript the id of the text we want to be invisible after the set amount of seconds, next the
<php include "constant.hpp"; ?>
it includes every thing from the constant.php document we make.
file 1
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" /><meta http-equiv="content-language" content="en-US" />
<title>MySQL Connection test</title>
<script type="text/javascript">
window.onload = function()
{
timedHide(document.getElementById('messages'), 10);
}
function timedHide(element, seconds)
{
if (element) {
setTimeout(function() {
element.style.display = 'none';
}, seconds*1000);
}
}
</script>
</head>
<body>
<span id="messages">
<?php include "constant.php"; ?>
</span>
</body>
</html>
this second file im not going to explain to much about it, since it would make this way to long, but this file is the connection file to the mysql database.
the only part you need to fill in on this is the
$database_ip = ""; //database ip adress goes inside quotes
$database_port = ""; //database port goes inside quotes
$database_name = ""; //database name goes inside quotes
$database_admin_user = ""; //admin username goes inside quotes
$database_admin_pass = ""; //admin password goes inside quotes
this will connect your website to the database.
file 2
constant.php
<?php
$database_ip = ""; //database ip adress goes inside quotes
$database_port = ""; //database port goes inside quotes
$database_name = ""; //database name goes inside quotes
$database_admin_user = ""; //admin username goes inside quotes
$database_admin_pass = ""; //admin password goes inside quotes
//do not modify anything past this point unless you know php well.
$database_link = null;
$database_defaults = array("127.0.0.1","3306","MySQL","root","");
$error_defaults = array("error_no_101" => "required field *IP is empty, using default parameters!",
"error_no_102" => "required field *PORT is empty, using default parameters!",
"error_no_103" => "required field *NAME is empty, using default parameters!",
"error_no_104" => "required field *USER is empty, using default parameters!",
"error_no_105" => "required field *PASS is empty, using default parameters!");
if(empty($database_ip)){
$database_ip = $database_defaults[0];
echo $error_defaults["error_no_101"] . "<br/>";
}
if(empty($database_port)){
$database_port = $database_defaults[1];
echo $error_defaults["error_no_102"] . "<br/>";
}
if(empty($database_name)){
$database_name = $database_defaults[2];
echo $error_defaults["error_no_103"] . "<br/>";
}
if(empty($database_admin_user)){
$database_admin_user = $database_defaults[3];
echo $error_defaults["error_no_104"] . "<br/>";
}
if(empty($database_admin_pass)){
$database_admin_pass = $database_defaults[4];
echo $error_defaults["error_no_105"] . "<br/>";
}
$database_link = mysqli_connect($database_ip, $database_admin_user, $database_admin_pass, $database_name);
if (!$database_link) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
} else {
echo 'Success... ' . mysqli_get_host_info($database_link) . "\n";
}
mysqli_close($database_link);
?>
i put this up to help you fix your code, not to teach you the syntax of the language.
to learn the syntax of php i recommend you go here:
this is the official php website documentation that teach you the correct way to code php,
http://www.php.net/manual/en/langref.php
you could also try this place if you have the money for a subscription:
http://www.lynda.com/MySQL-tutorials/PHP-MySQL-Essential-Training/119003-2.html?srchtrk=index:1%0Alinktypeid:2%0Aq:php%0Apage:1%0As:relevance%0Asa:true%0Aproducttypeid:2
for html you could go to:
http://www.w3schools.com/html/default.asp
you could also try this place if you have the money for a subscription:
http://www.lynda.com/HTML-tutorials/HTML-Essential-Training-2012/99326-2.html
I use a comment box in my web page and saved user input comments. Now what I want is to display them using AJAX. I set a javascript timer to get comments one by one. But I don't know how to use AJAX to retrieve data. This is the php file
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("continental_tourism");
$query = "SELECT comment_id from comment";
$result = mysql_query($query);
$counter = 0;
while ($row = mysql_fetch_assoc($result))
{
$counter++;
}
$comment_number = rand(1,$counter);
$query_comment = mysql_query("SELECT * FROM comment WHERE comment_id = '$comment_number'");
if (!$query_comment) {
die('Invalid query: ' . mysql_error());
}
while($result_comment = mysql_fetch_array($query_comment)) {
echo $result_comment['comment'];
}
?>
following is the script part in the main file.
function timeMsg()
{
var t=setTimeout("show_comment()",3000);
}
function show_comment(){
}
How should i write the AJAX code to the?
function show_comment()
If someone can explain the AJAX code line by line, I'll be great full.
You have to move your all php script to another php file say getdata.php and use your ajax function in your file where you want to show the data say it is index.php. (this is for easy to use code). Now your index.php file should look like
<html>
<body>
<div id="comments"></div>
</body>
<script src="include/jquery.js" type="text/javascript"></script>
<script type="text/javascript>
function show_comments() {
$.ajax({
url:getdata.php
success:function(data){
$("#comments").append(data);
}
});
</script>
</html>
I am using jquery.ajax function of jquery. This is some hint how you can do this. I hope it will help you to accomplish your task.
Use jQuery's .get() method using the link to your PHP script as URL. That should call your PHP script and your script should echo the output.
You should consider json_encode-ing your output from php script before echoing it.
And I think, instead of doing this -
$query = "SELECT comment_id from comment";
$result = mysql_query($query);
$counter = 0;
while ($row = mysql_fetch_assoc($result))
{
$counter++;
}
you can query SELECT COUNT(comment_id) from comment and get the count.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP headers already sent
PHP session_start() error?
I'm getting this error:
Warning: session_start() [function.session-start]: Cannot send session
cookie - headers already sent by (output started at
C:\xampp\htdocs\index.php:27) in C:\xampp\htdocs\connect.php on line 2
Warning: session_start() [function.session-start]: Cannot send session
cache limiter - headers already sent (output started at
C:\xampp\htdocs\index.php:27) in C:\xampp\htdocs\connect.php on line 2
I'm don't have a clue what this means or how to handle it!! ANY help will be very appreciated!
Here is my 2 files that "causes" the problem:
connect.php
<?php
session_start();
$server = 'localhost';
$username = 'root';
$password = '';
$database = 'mydatabase';
if(!mysql_connect('localhost', 'root', ''))
{
exit('Error: could not establish database connection');
}
if(!mysql_select_db($database))
{
exit('Error: could not select the database');
}
?>
index.php
<!DOCTYPE HTML>
<head>
<title> ShareLink </title>
<link rel="stylesheet" href="style.css" type="text/css">
<link rel="stylesheet" type="text/css" media="screen,projection" href="css/ui.totop.css" />
<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/easing.js" type="text/javascript"></script>
<script src="js/jquery.ui.totop.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var defaults = {
containerID: 'moccaUItoTop', // fading element id
containerHoverClass: 'moccaUIhover', // fading element hover class
scrollSpeed: 1200,
easingType: 'linear'
};
$().UItoTop({ easingType: 'easeOutQuart' });
});
</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
</head>
<body>
<?php
include 'connect.php';
include 'header.php';
$sql = "SELECT
categories.cat_id,
categories.cat_name,
categories.cat_description,
COUNT(topics.topic_id) AS topics
FROM
categories
LEFT JOIN
topics
ON
topics.topic_id = categories.cat_id
GROUP BY
categories.cat_name, categories.cat_description, categories.cat_id";
$result = mysql_query($sql);
if(!$result)
{
echo 'The categories could not be displayed, please try again later.';
}
else
{
if(mysql_num_rows($result) == 0)
{
echo '<br/>';
echo '<h3>Welcome to ShareLink! Here you can rate and share links with other users.</h3>';
echo '<br/>';
echo 'Please <b>register</b> or <b>log in</b> to start sharing your links...';
echo '<br/><br/>';
}
else
{
//prepare the table
echo '<table border="1">
<tr>
<th>Category</th>
<th>Last topic</th>
</tr>';
while($row = mysql_fetch_assoc($result))
{
echo '<tr>';
echo '<td class="leftpart">';
echo '<h3>' . $row['cat_name'] . '</h3>' . $row['cat_description'];
echo '</td>';
echo '<td class="rightpart">';
//fetch last topic for each cat
$topicsql = "SELECT
topic_id,
topic_subject,
topic_date,
topic_cat
FROM
topics
WHERE
topic_cat = " . $row['cat_id'] . "
ORDER BY
topic_date
DESC
LIMIT
1";
$topicsresult = mysql_query($topicsql);
if(!$topicsresult)
{
echo 'Last topic could not be displayed.';
}
else
{
if(mysql_num_rows($topicsresult) == 0)
{
echo 'no topics';
}
else
{
while($topicrow = mysql_fetch_assoc($topicsresult))
echo '' . $topicrow['topic_subject'] . ' at ' . date('d-m-Y', strtotime($topicrow['topic_date']));
}
}
echo '</td>';
echo '</tr>';
}
}
//rate the link
//echo '<tr><td><b>Rate this link</b></td></tr>';
}
//include 'footer.php';
?>
Like I said, I really need to get this working so your help will mean a lot!
just what the error-message and the documentation* say: you have to call session_start(); before any output is sent to the browser. in your case, include connect.php at the very top of your index.php instead of somewhere in the middle.
alternatively, just add
<?php
session_start();
?>
at the top of index.php and leave out that line in connect.php.
*quoting the documentation:
Note:
To use cookie-based sessions, session_start() must be called before
outputing anything to the browser.
You need to start the session before any output to the browser.
You've already output the document header etc before you include connect.php- you should initialise session_start(); before the line <!DOCTYPE HTML>, see the first usage note under the SESSION reference in the PHP docs.
You NEED to put the session_start() call before any code is sent to the client (at the start of the page).
Just put your include 'connect.php'; right at the start of index.php !
You are not allowed to send output before setting the session. Put the include("connect.php") statement at the beginning of your index.php.
This error occurs because session_start() sends a cookie to the client to be able to identify the user. But cookies can only be sent to the browser if you haven't generated any output yet.
there are outputs in your index page before session_start().
Erase the session_start() from your connect.php and add it on the first line of your index page. it should work. or include your connect.php on the start of index page
Just put ob_start(); above the session_start();. And at the end of the page, before </body>, put ob_end_flush();. I once got this error. By turning on output buffering you can solve this problem.