Uncaught ReferenceError: 'somevar' is not defined - javascript

Am trying to insert some data into mysql through ajax call but while am trying to get the data from my form javascript throws me this error "Uncaught ReferenceError: anjelis is not defined" on the first variable
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>aloooooooooooooo!!!!!!!!!</title>
<link rel="stylesheet" href="bootstrap/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css.css">
<script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.js"></script>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
$(document).ready(function(e){
$.ajaxSetup({cache:false});
setInterval(function(){$('#chatlog').load('logs.php');},1000);
setInterval(function(){$('#user_list').load('user_list.php');},1000);
});
function submitChat(){
var uname=<?php echo $_SESSION['username']?>;
var msg=form.msg.value;
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById('chatlog').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open('GET','insert.php?username='+uname+'&msg='+msg,true);
xmlhttp.send();
}
</script>
</head>
The body
<body>
<nav class="navbar navbar-inverse">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">ChatCY</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><?php if(!isset($_SESSION['username'])){echo 'Login/Signin';}else{
echo'Logout';}?></li>
</ul>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="panel panel-default">
<div id="chatlog" class="panel-body"></div>
</div>
</div>
<div class="col-md-2">
<div class="panel panel-default">
<div id="user_list" class="panel-body"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8">
<form class="form-inline">
<form name="form" class="form-group" onsubmit="return false;">
<input type="textarea" class="form-control" name="msg" style="width:90%;"<?php if(!isset($_SESSION['username'])){
echo 'disabled="disabled" placeholder="You must be logged in to chat .."';}?>></input>
<button type="button" class="btn btn-default" name="send" <?php if(!isset($_SESSION['username'])){
echo 'disabled="disabled"';}?> onClick="submitChat();">send</button>
</form>
</form>
</div>
</div>
</div>

There are a lot of issues in your code.
Quotes are missing in the variable. Add quotes here:
var uname = "<?php echo $_SESSION['username']?>";
Session is not started. Start the session using:
session_start();
Try not to mix up both PHP and HTML. Keep it separate. Don't use echo to write the HTML tags.
No <input /> has an ending tag, and there's no <input type="textarea"... It should be replaced with <input type="text".
Use jQuery or some other awesome libraries for doing complex functions like AJAX calls or something. That makes your and dev's life easier, by providing functions for all the browsers and less clutter of code.
$.ajax(function () {
"url": "/",
// Blah Blah
});

You missed the code
session_start(),
well you can do it another way, create a inpu tag in your html
<input type='hidden' id='uname' value="<?php echo $_SESSION['username']?>">
in js
get your id like this
var uname = $('#uname').val();

Missed the quotes -
var uname= "<?php echo $_SESSION['username']?>";
var form = $('form.form-group');
If it is
var uname = somevar;
somevar will be undefined.
You are not passing or defining form to the function or inside the function.

Related

access table from PHP database in Javascript

I have created a login page that allows you to log in using username and password. However, it is currently so that you are always redirected to the "profile" page and there is then checked by PHP whether the login data are correct, because the data are on the DB.
Therefore I have the idea with a validate function directly on the loginpage to check if the data is correct and then I just create a session.
Does anyone have an idea how I can do this?
Here is the code:
<?php session_start();?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Login</title>
<link href="bootstrap_style.css" rel="stylesheet" id="bootstrap-css"> <!-- maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css -->
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <!-- //maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js or bootstrap.js-->
<script src="jquery.js"></script> <!-- //cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="wrapper fadeInDown">
<div id="formContent">
<!-- Tabs Titles -->
<!-- Icon -->
<div class="fadeIn first">
<img src="default_logo2.png" id="icon" alt="User Icon" onclick="window.open('url', '_blank');"/>
</div>
<!-- Login Form -->
<form action="searchpage.php" method="post" onsubmit="validateForm(event);">
<input type="text" id="login" class="fadeIn second" name="username" placeholder="username">
<input type="password" id="password" class="fadeIn third" name="password" placeholder="password">
<input type="submit" class="fadeIn fourth" value="Log In">
</form>
<!-- Remind Passowrd -->
<div id="formFooter">
<a class="underlineHover" style="color:red" id="warning"></a>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
function validateForm(event) {
var input_username = document.getElementById("login");
var input_password = document.getElementById("password");
if (input_username.value == '' || input_username.value.charAt(0) == ' ' || input_password.value == '') {
event.preventDefault();
document.getElementById("warning").innerHTML = "Fill empty fields!";
}
else {
return true;
}
}
</script>
with this I reach the DB:
$pdo = new PDO('mysql:host=localhost;dbname=ausleihe', 'root', '');
and that is the SELECT:
$login_session = "SELECT * FROM login WHERE username = '".$hereshouldbetheusernamefromform."' AND password = '".herethepasswordfromform."'";
If you need more code or have questions, ask me!
Thx
Client-side JavaScript cannot directly access a Host-side PHP program except through AJAX calls. Only the Host-side software has access to Host-side databases.

How to save search engine entry to csv file

I am trying to make a search engine by comparing any search entry to my csv files. But i am not able to save my search entry into csv file. Below are my html code.
<!DOCTYPE html>
<html>
<head>
<title>Search Engine</title>
<meta name="viewreport" content="width=device-width", intial-scale=1>
<link rel="stylesheet" href="css/style.css"/>
<script type="text/javascript" src="validate.js"></script>
</head>
<body>
<div class="container">
<h1 class = "title">Search Engine</h1>
<form name="search" action="search.php" method="post">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="search" id="search">
<div class="input-group-btn">
<button class="gobtn" type="submit">Go!</button>
<i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
</div>
</body>
</head>
</html>
And this is my search.php code
<?php
$keys = array('search');
$csv_line = array();
foreach($keys as $key){
array_push($csv_line,'' . $_GET[$key]);
}
$fname = 'search.csv';
$csv_line = implode(',',$csv_line);
if(!file_exists($fname)){$csv_line = "\r\n" . $csv_line;}
$fcon = fopen($fname,'a');
$fcontent = $csv_line;
fwrite($fcon,$csv_line);
fclose($fcon);
?>
Whenever I tried to search something, i kept on getting errors on the line array_push($csv_line,'' . $_GET[$key]);
TQ in advance!

How can I show a DIV element without creating a new row?

I crated a small login form where I check the username in a external php file. After that I give back an error message or redirect to another site.
My problem is to show the error message. I want a short message above the login form if the username != „test“. In my script, the errormessage appears above the login form, but the login form jumps one row deeper.
Question 1:
How can a create a placeholder above the login form? So that the login form is fix?
Question 2:
Is it the right way to fill a JavaScrpt Variable in PHP as in my Code?
Thanks for your help!
< script >
var error_login;
if (error_login == 1) {
$('#errorText').show();
} else {
$('#errorText').hide();
} <
/script>
<?php
//debug
error_reporting(-1);
ini_set('display_errors', true);
session_start();
session_unset();
session_destroy();
?>
<!doctype html>
<html lang="de">
<head>
<title>Hello World</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
</head>
<body>
<?php include ("login.php"); ?>
<div class="container">
<div id="errorText" class="row justify-content-center">
Login failed!
<!-- This should be a placeholder -->
</div>
<!-- Formular Beginn -->
<div class="row justify-content-center">
<div class="col-md-6">
<form class="form" role="form" method="post" action="?login=1" accept-charset="UTF-8" id="login">
<div class="input-group" id="frmGrpBenutzer">
<input type="password" class="form-control input-lg" id="user" name="user" placeholder="Username" required autofocus>
<span class="input-group-btn">
<button type="submit" class="btn btn-primary btn-custom btn-lg" title="login" id="loginbtn"><span>Go</span></button>
</span>
</div>
</form>
</div>
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>
</html>
Here the login.php file:
<?php
session_start();
if(isset($_GET['login'])) {
$user = $_POST['user'];
if ($user == "test") {
$_SESSION['username'] = $user;
header('Location: site2.php');
} else {
echo "<script>
var error_login = 1;
</script>";
}
}
There are a few possibilities. The easiest would be to set your div with an opacity:0 or visibility:hidden this will make it still take space in the document flow.
Another option, could be to set it's position:absolute this will prevent it to take space inside your login form. Doing this will make it overlap tough, so there would need to be a padding or margin to offset the content of the form.
As for setting your javascript variable with PHP, that's one way to do it yes, but your script already defines error_login... Another way to do it, is use a holder HTML element, give it an id, and a data-* attribute. This will make it very easy to read the information from code:
$('button').click(function() {
console.log($('#login_status').data('login-error'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="login_status" data-login-error="1"></div>
<button>Click me to get result</button>
You could also add all the data you want into a JSON string as the div's content, and parse it once the page loaded.

PHP Header redirect issue

I have this code that works well and can actually insert data. My problem is in the redirecting back to the page I was from. I have an index.html and add_cars.php
The index.html is like so:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
$('#search').keyup(function(){
var search = $('#search').val();
$.ajax({
url:'search.php',
data:{search:search},
type:'POST',
success:function(data){
if(!data.error){
$('#result').html(data);
}
}
});
}); // Search function end
$("#add-car-form").submit(function(evt){
evt.preventDefault();
var postData = $(this).serialize();
var url = $(this).attr('action');
$.post(url, postData, function(php_table_data){
$("#car-result").html(php_table_data);
});
}); // add car function end
}); // Document ready function end
</script>
<div id="container" class='col-xs-6 col-xs-offset-3'>
<div class="row">
<h2 >Search the Database</h2>
<input type="text" name="" class='form-control' name='search' id='search' placeholder='Search our inventory'>
<br>
<br>
<h2 class="bg-success" id="result">
</h2>
</div>
<div class="row">
<form id="add-car-form" class="col-xs-6" action="add_cars.php" method="post">
<div class="form-group">
<input type="text" name="car_name" placeholder="Car name" class="form-control">
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Add Car" name="">
</div>
</form>
<div class="col-xs-6">
<div id="car-result">Sometkasdf</div>
</div>
</div>
</div>
</body>
</html>
and my add_cars.php is like so:
<?php
include("db.php");
if(isset($_POST['car_name'])){
$car_name = $_POST['car_name'];
$query = "INSERT INTO cars(car) VALUES ('$car_name')";
$query_car_name = mysqli_query($connection, $query);
if(!$query_car_name){
die("QUERY FAILED");
}
header("Location: index.html");
exit;
}
?>
When I redirect back to my index.html, I am getting two forms. It's like the first form is copied at the end of it. To be exact, the first form is copied to the #car-result div. What should happen is; it should go back to my index.html and the input box should only have the placeholder value. What am I doing wrong here or what should I do? All help is appreciated.

Class are not working on pre tag in html [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am trying to add a class on pre tag using javascript, i tried this code..
<?php
session_start();
include 'connection.php';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Post-Question</title>
<link rel="stylesheet" href="css/bootstrap.css"/>
<link rel="stylesheet" href="code-prettify-master/loader/prettify.css"/>
<style>
</style>
</head>
<body>
<div class="row">
<div class="container">
<div class="page-header"></div>
<div class="well-lg col-md-6">
<?php
if(isset($_SESSION['sucess']))
{?>
<span class="alert alert-success"><?php echo $_SESSION['sucess'];?></span>
<?php
unset($_SESSION['sucess']);
}
elseif(isset($_SESSION['error']))
{?>
<span class="alert alert-danger"><?php echo $_SESSION['error'];?></span>
<?php
unset($_SESSION['error']);
}
?>
</div>
<div class="well well-lg">
Post Your Question Here!
</div>
<div class="col--md-6">
<form action="ques.php" method="post">
<input type="text" name="question" placeholder="Enter your issue here" class="form-control"><br>
<div class="panel panel-default">
<!-- Default panel contents -->
<div class="panel-heading">
<span class="btn"><span class="glyphicon glyphicon-bold"></span></span>
<span class="btn"> <span class="glyphicon glyphicon-italic"></span></span>
<span class="btn"><span class="glyphicon glyphicon-link"> </span></span>
<span class="btn"> <span class="glyphicon glyphicon-chevron-left"> </span>
<span class="glyphicon glyphicon-chevron-right"></span></span>
<span></span>
<span></span>
</div>
<div class="panel-body">
<textarea class="form-control" name="desc" placeholder="Iuuse Description">
</textarea><br/>
<input type="submit" class="btn btn-default">
</form>
</div>
</div>
<div class="container">
<?php
$smt=$conn->prepare("SELECT * FROM qa");
$smt->execute();
while($rows=$smt->fetch(PDO::FETCH_OBJ)):?>
<div class="h2"> <?php echo $rows->QUES; ?>!</div>
<div class="h4"><pre><code><?php echo htmlentities($rows->ANS); ?></code></pre></div>
<?php endwhile;?>
</div>
</div>
</div>
<script src="js/jquery.js"></script>
<script type="text/javascript">
$(window).load(function () {
// var pro=document.getElementsByTagName('pre');
$('pre code').addClass('prettyprint');
});
</script>
<script src="code-prettify-master/loader/run_prettify.js"></script>
<script src="js/bootstrap.js"></script>
</body>
</html>
if i use another class insted of prettyprint, then the code works and also if i use the prettyprint class like <pre class="prettyprint"> then it will works, but i want to use it useing the js method.I am using this plugin
First of all, there is no point in having <code> in <pre> in your html as it may screw up your syntax highlight:
<div class="h4"><pre><?php echo htmlentities($rows->ANS); ?></pre></div>
If your intention is to add a class to pre: do it with $('pre').addClass('prettyprint');; if you want prettyprint syntax highlight to work on these pres, just in case, run the prettyprint script after you have added the class to the the pres.
$(window).load(function () {
$('pre code').addClass('prettyprint');
$.getScript( "code-prettify-master/loader/run_prettify.js", function( data, textStatus, jqxhr ) {
console.log("prettified");
});
});
although it should work just fine like this.
If you are using prettify.js instead of run_prettify.js, you need to call prettyPrint() in this manner.
If you want attach an on-click event for some <b></b>, you should give it a class first: <b class="click_this_old_sport"> hey jude</b> then in simply do this in jQuery:
$(".click_this_old_sport").click(function(){ alert("clicked!") });
Here I think you have some thing to do
$(window).load(function () {
// var pro=document.getElementsByTagName('pre');
$('pre').addClass('prettyprint');
});
Class name prettyprint you are using in code is wrong. It should be prettifyprint. Change your code to
$('pre code').addClass('prettifyprint');
It should work

Categories

Resources