Notice: Undefined variable: output in C:\xampp\htdocs\tests\ser.php on line 24
i got this problem i don't know why this show ! try everything
any fix !?
this is my code php
the idea of code live search like google
<?php
require_once("conf.php");
if(isset($_POST['SearchValue'])){
$se=$_POST['SearchValue'];
$s=preg_replace("#[^0-9a-z]#i","",$se);
$query=mysql_query("SELECT * FROM search WHERE P_A LIKE '%$s%'");
$connect=mysql_num_rows($query);
if ($connect == 0){
$output="no reset";
}
else {
while ($row = mysql_fetch_array($query)){
$pA = $row ['P_A'];
$pB = $row ['P_B'];
$pC = $row ['P_C'];
$pD = $row ['P_D'];
}
$output .= '<div>' . "" . $pA . "" . $pB . "" . $pC . "" . $pD . '</div>' ;
}
}
echo ($output);
?>
and this is my html code
<html>
<head>
<script src="jquery.min.js"></script>
<script type="text/javascript">
function mysearch(){
var sText =$("input [name='Search']").val();
$.post("ser.php",{SearchValue:sText},function(output){
$("#output").html(output);
}
);
};
</script>
</head>
<body>
<form action="#" method="post">
<input type="text" name="Search" onkeydown="mysearch();" />
<input type="submit" value="search" />
</form>
<div id="output" >
</body>
</html>
Yes, you have not defined $output variable first and joining it like $output .= ....
So, use this at the top of your code:
$output = '';
if $_POST['SearchValue'] is not set the variable $output is never defined. That's the error you see.
Also in your jquery code there is an error finding your text. Change:
var sText =$("input [name='Search']").val();
To:
var sText =$("input[name='Search']").val();
In the first one you are searching an item with name 'Search' inside an input. In my code you search an input with the atribute name = 'Search'
Related
I have an issue with returning the value of a PHP variable in JS. It returns NULL or empty instead of returning the age.
Approach:
Passing PHP variable with data to a JS variable in a separate file. Display JS variable in an alert(). Data was fetched from the database using fetch_assoc() in a while loop. Without using Ajax!
Proposed plan:
Enter a name.
Submit.
PHP fetches the age associated with that name.
age is stored in a PHP variable dbage.
Passed into JS variable to alert user what their age is.
I am trying to pass $dbage from sampletest.php to user in sample.php which will onsubmit display an alert saying: "Your age is blah".
blah is $dbage, which contains the age. This is for testing. Once I understand why this isn't working, I can move on to sending these JS variables to functions that will do calculations and return back to the DB.
What I have tried so far..
Trying to catch echo using ob_start() but that returned NULL as well.
Example:
ob_start();
echo $dbage;
$output = ob_get_contents();
ob_end_clean();
Making $dbage a global variable. Returns empty.
Echo variable outside the while loop but that returned NULL.
Example:
$dbage = '';
while( $row = $result->fetch_assoc()) {
$dbage = $row['age'];
}
echo $dbage;
Any suggestions, corrections are appreciated.
sample.php (index file)
<?php
include 'sampletest.php';
session_start();
?>
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<div id="id03">
<form class="modal-content" action="sampletest.php" method="post" onsubmit="myFunction()">
<div class="container">
<input type="text" id="name" placeholder="Enter name" name="name">
<div class="clearfix">
<button type="submit" class="loggedinbtn" name="load"/>Load
</div>
</div>
</form>
</div>
<script>
function myFunction() {
var user = '<?php echo(json_encode($dbage)); ?>';
alert("This is a php varible " + user);
}
</script>
</body>
</html>
sampletest.php
if(isset($_POST['load'])){
require 'config.php';
$name = $_POST['name'];
$age = $_POST['age'];
if(empty($name)) {
echo "Enter a number";
}elseif(!preg_match('/^[a-z ]+$/i', $name)){
echo "Enter a letter, no numbers";
}else{
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
header("location: sample.php?Connect-database=failed");
exit();
}
$sql = "SELECT name, age FROM results WHERE name= '$name';";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while( $row = $result->fetch_assoc()) {
$dbage = $row['age'];
}
}
else{
echo "0 results";
}
$conn->close();
}
}
your action in the form should be set to sample.php, i think is the first problem. then get rid of the javascript all together.
<form class="modal-content" action="sample.php" method="post">
then change:
<script>
function myFunction() {
var user = '<?php echo(json_encode($dbage)); ?>';
alert("This is a php varible " + user);
}
</script>
to just
<script>
var user = <?php echo $dbage; ?>;
alert("This is a php varible " + user);
</script>
submitting html forms to PHP does not require javascript at all.
From what I can see is that the actual query that you're sending is { name= '$name' }, try { name=' " . $name . " ' }.
I want to pass the output from PHP's file_get_contents() to JavaScript and calculate its length. Everything ok but when passing the variable JavaScript evaluates it as HTML code, so I have to use PHP's json_encode() to keep it "sane" but this way the string length from JavaScript will be different from the one in PHP. Using JS's JSON.parse() doesn't help because again the HTML code gets interpreted. Any idea how can I achieve the same evaluated data length?
EDIT: Basically I need to count all the characters in the page source, that includes tags and special characters. To have the same output computed in JS like the one i get in PHP's strlen($url_data).
EDIT 2: I thought about doing bin2hex() on the $url_data then reconvert in JS and check the length. Would be that reliable?
Here is what I did so far:
<?php
ini_set('display_erros', -1);
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['urlinput']) && !filter_var($_POST['urlinput'], FILTER_VALIDATE_URL) === false) {
$url = filter_var($_POST['urlinput'], FILTER_SANITIZE_URL);
$url_data = #file_get_contents($url);
$js_url_data = json_encode($url_data);
//$url_src = htmlspecialchars($url, ENT_IGNORE);
$url_data_len = mb_strlen($url_data);
$url_src = strip_tags($url_data);
echo '<ul id="resultList">';
echo "<li>The following page contains " . $url_data_len . " characters</li>";
echo "<li>Page URL: " . $_POST['urlinput'] . "</li>";
echo "<li>Page title: " . page_title($url_data) . "</li>";
echo "<li>Protocol: " . parse_url($url, PHP_URL_SCHEME) . "</li>";
echo "<li>Host: " . parse_url($url, PHP_URL_HOST) . "</li>";
echo "</ul>";
//var_dump($url_src);
} else {
$error = "URL is not valid!";
}
}
function page_title($str) {
$matches = array();
if (preg_match('/<title>(.*?)<\/title>/i', $str, $matches)) {
return $matches[1];
}
else {
return null;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>PHP file_get_contents()</title>
</head>
<body>
<div class="url_class">
<form id="getsrc" method="post">
<input style="width: 300px;" type="text" name="urlinput" id="urlinput" placeholder="URL">
<input type="submit" name="submit" value="Get SRC">
</form>
</div>
<textarea rows="20" cols="50">
<?php
if (!empty($url_src)) {
echo $url_src;
}
?>
</textarea>
<?php echo '<br><span style="color:red">' . $error . '<span>'; ?>
<?php
if (!empty($js_url_data)) {
$script = <<<EOT
<script>
var url_data = $js_url_data;
var node = document.createElement("li");
var textnode = document.createTextNode("JavaScript page characters: " + url_data.length);
node.appendChild(textnode);
document.getElementById("resultList").appendChild(node);
</script>
EOT;
echo $script;
}
?>
</body>
</html>
Simply use the value calculated by php, it can be used within EOT block:
...
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['urlinput']) && !filter_var($_POST['urlinput'], FILTER_VALIDATE_URL) === false) {
...
$url_data = #file_get_contents($url);
$fileSize = strlen($url_data);
...
}
....
if (!empty($js_url_data)) {
$script = <<<EOT
<script>
...
var textnode = document.createTextNode("JavaScript page characters: " + $fileSize);
...
</script>
EOT;
echo $script;
Since no good answer, I would post my solution to my problem. The only way I could find was to hex-encode $url_data, pass it to JS, decode it and count the characters. For the pack() function I used the one ported in php.js.
...
$js_url_data = bin2hex($url_data);
...
if (!empty($js_url_data)) {
/* This is a good example when one is forced to use inline JS */
$script = <<<EOT
<script>
var url_data = "$js_url_data";
var url_data_len = pack('H*', url_data).length;
var node = document.createElement("li");
var textnode = document.createTextNode("JavaScript calculation page characters: " + url_data_len);
node.appendChild(textnode);
document.getElementById("resultList").appendChild(node);
</script>
EOT;
echo $script;
...
Study jQuery from online tutorial, find many tutorials, just find one simple maybe good for newbie.
Here is the code for index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>
Autocompletement
</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="suggest.js"></script>
</head>
<body>
<input type="text" name="suggest" placeholder="Type a Country Name..." onkeyup="suggestion()"/>
<div id="autosuggest"></div>
</body>
</html>
Here is the code for suggest.php:
<?php
include "connect.php";
function auto($data){
global $mysqli;
$data = $_GET['data'];
$query = "SELECT code, name_en
FROM countries
WHERE name_en LIKE '%$data%'
OR code LIKE '%$data%'";
$items = '<ul class="suggestion">';
if($result = $mysqli->query($query)){
/* fetch associative array */
while($row = $result->fetch_assoc()){
$items .= '<li>'.$row['name_en'] . ' ' . $row['code'].'</li>';
}
$items .= '</ul>';
}else{
$items = "No results Found...";
}
echo $items;
}
auto();
?>
Here is the code for suggest.js
function suggestion(){
var suggestVal = $('#suggest').val();
if(suggestVal != ''){
$.ajax({
url: 'suggest.php?data='+suggestVal,
success: function(data){
$('#autosuggest').html(data);
}
})
}
}
The result above will only show "No results Found...", it seems that processing file suggest.php is not working, then I test it with a test file test.php:
$mysqli = new mysqli("host","user","pass","database");
//auto();
$data = $_GET['input'];
//$data = "ca";
$query2 = "SELECT code, name_en FROM countries WHERE name_en LIKE '%$data%' OR code LIKE '%$data%'";
echo "<br>" .$query2;
echo "<br>";
if($mysqli){
echo "Yes SQL";echo "<br>";
}else{
echo "No SQL";echo "<br>";
}
$result = $mysqli->query("SELECT code, name_en FROM countries WHERE name_en LIKE '%$data%' OR code LIKE '%$data%'");
if($result->num_rows){
echo "Yes Result";echo "<br>";
}else{
echo "No Result";echo "<br>";
}
The weird thing is that I cannot find anything wrong with my code, checked php.net sample and seems all to be good? But when I check vam_dump($result) then it is "null", any helps will appreciated.
Here is the test.php output:
SELECT code, name_en FROM countries WHERE name_en LIKE '%ch%' OR code LIKE '%ch%'
Yes SQL
No Result
URL: http://IP/project/jquery/auto_diy/test.php?input=ch
You defined your function as having a $data argument
function auto($data){...}
but you are calling it without the argument,
auto();
this will trigger a notice.
The argument is not needed, since you are already using $data=$_GET['data']; inside your function.
Then in your ajax call you should change it like so
$.ajax({
url: 'suggest.php',
type: 'get', // this can be omitted because GET is default
data: 'data='+suggestVal, // or
// data: {data:suggestVal}
success: function(data){
$('#autosuggest').html(data);
}
})
Update:
in test.php output directly the value of $result->num_rows
print "Rows returned: " . $result->num_rows . "<br>";
if you get zero rows, copy the query and run it in phpmyadmin or a mysql console to verify the data.
in suggest.php, update this:
$result = $mysqli->query($query);
if (!$result) {
print 'Could not execute query';
}
else {
while($row = $result->fetch_assoc()){
$items .= '<li>'.$row['name_en'] . ' ' . $row['code'].'</li>';
}
}
$items .= '</ul>';
New to this group. Need tip to ignore empty search box queries. The following code works fine but when I click the search button with nothing in the text field, it gives me all my page links as results. I would want no action for an empty box search...thanks in advance folks!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<form action='./search.php' method='get'>
<input type='text' name='k' size='15' value='<?php echo isset($_GET['k']) ? $_GET['k'] : ""; ?>' placeholder=' ' />
<input type="image" src="images/magnifier.png" width="14" height="14" border="0" >
</form>
<h2>Search Results</h2>
<hr />
<?php
$k = isset($_GET['k']) ? $_GET['k'] : "";
$terms = explode(" ", $k);
$query = "SELECT * FROM search WHERE ";
$i = 0;
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "keywords LIKE '%$each%' ";
else
$query .= "OR keywords LIKE '%$each%' ";
}
// connect to DB
mysql_connect("localhost", "root", "mypwd");
mysql_select_db("busqueda");
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo "<h2><a href='$link'>$title</a></h2>
$description<br /><br />";
//empty query variable before coming back to home page
$k = null;
}
}
else
echo "No results found for \"<b>$k</b>\"";
//empty query variable before coming back to home page
$k = null;
//disconnect from DB
mysql_close();
?>
</body>
</html>
Just don't do anything if you get an empty query
if (empty($_GET['k']) or trim($_GET['k']) == ''){
exit;// or something
}
also you can prevent the form from submitting an empty query with the required attribute
<form action='./search.php' method='get'>
<input type='text' name='k' required size='15' value='<?php echo isset($_GET['k']) ? $_GET['k'] : ""; ?>' placeholder=' ' />
<input type="image" src="images/magnifier.png" width="14" height="14" border="0" >
</form>
before getting to
$terms = explode(" ", $k);
check if $k is not empty
if($k !=''){
// put here your query structure and database stuff
// now we are sure that there is some content in the k field
}
Just wrap the rest of your code after defining $k with and if statement like so:
if($k != ""){
//execute search
}
If required='true' is not enough (at the client-side), as you might want to prevent a submit (codes assumes jQuery usage) and do some stuff:
$(document).ready(function() {
$('form').submit(function() { // replace by form #id selector
if ($(this).find('[name=k]').val().trim() == '') {
return false; // do other stuff, as warn user
}
});
});
My test.php page is as under:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h3>Setting</h3>
<form>
<p>Name:<input type="text" id="updatetherone1"/></p>
<p>Email:<input type="text" id="updateotherone2"/></p>
<p><input id="updateone" type="button" value="Save"/></p>
</form>
<span id="updateotherotherone"></span>
<script src="js/jquery.js"></script>
<script src="js/ajax.js"></script>
</body>
</html>
My ini.php page is as under:
<?php
session_start();
$_SESSION['state'] ='2';
$conn=new mysqli('localhost','root','','people');
?>
My test1.php page is as under:
<?php
include 'ini.php';
if (isset($_POST['name'], $POST['email'])){
$name = mysqli_real_escape_string(htmlentities($POST['name']));
$email = mysqli_real_escape_string(htmlentities($POST['email']));
$update = mysqli_query("UPDATE state SET Name='$name', email='$email' WHERE Id=".$_SESSION['state']);
if($update === true){
echo 'Setting have been updated.';
}else if ($update === false){
echo 'There was an error updating your setting.';
}
}
?>
My ajax.js page is as under:
$('[id=updateone]').click(function(){
var name=$('[id=updateotherone1]').val();
var email=$('[id=updateotherone2]').val();
$('[id=updateotherotherone]').text('Loading...');
$.post('test1.php',{name:name,email:email},function(data){
$('[id=updateotherotherone]').text(data);
});
});
Ultimately code is not working nor do it is displaying any error, I suspect there is something wrong with test1.php page, can anybody guide please:
Take note that the procedural interface of mysqli_query(), the first parameter need the connection.
$update = mysqli_query($conn, "UPDATE state SET Name='$name', email='$email' WHERE Id=".$_SESSION['state']);
If these are typos $POST, then it should be fixed in your code. It's supposed to read as $_POST. (unless its a typo on the question.) It is a superglobal.
I suggest you just use the object oriented interface. So that you wouldn't need to add it everytime:
<?php
include 'ini.php';
if (isset($_POST['name'], $_POST['email'])){
$name = $conn->real_escape_string(htmlentities($_POST['name']));
$email = $conn->real_escape_string(htmlentities($_POST['email']));
$update = $conn->query("UPDATE state SET Name='$name', email='$email' WHERE Id = " . $_SESSION['state']);
if($conn->affected_rows > 0) {
echo 'Setting have been updated.';
} else {
echo 'There was an error updating your setting.';
}
}
?>
Might as well use prepared statements since mysqli supports it:
if (isset($_POST['name'], $_POST['email'])){
$name = htmlentities($_POST['name']);
$email = htmlentities($_POST['email']);
$sql = 'UPDATE state SET Name = ?, email = ? WHERE Id = ?';
$update = $conn->prepare($sql);
$update->bind_param('ssi', $name, $email, $_SESSION['state']);
$update->execute();
if($update->affected_rows > 0) {
echo 'Setting have been updated.';
} else {
echo 'There was an error updating your setting.';
}
}
On the JS part:
You also have a typo on the form id and the JS:
<p>Name:<input type="text" id="updatetherone1"/></p> <!-- missing o -->
var name=$('[id=updateotherone1]').val();
Should be: <p>Name:<input type="text" id="updatetherone1"/></p>
Sidenote:
If you want to avoid those kind of silly typos, just id and label them properly. Example:
<p>Name:<input type="text" id="name_field"/></p>
<p>Email:<input type="text" id="email_field"/></p>