PHP Header redirect issue - javascript

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.

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!

why when i reload a page using AJAX the data disappears

Basically i find code on the internet to test and use it.
the problem is that when i reload the page, the data disappears.
what i want to happen is for the data or the value to just stay.
Thanks guys
Here is the code in index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pass Data to PHP using AJAX without Page Load</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h2>Enter Some Data Pass to PHP File</h2>
<div class="row">
<div class="col-md-3">
<form>
<div class="form-group">
<input type="text" id="pass_data" class=" form-control">
<input type="button" class="btn btn-success" onclick="passData();" value="Set">
<p id="message"></p>
</div>
</form>
</div>
</div>
</div>
</body>
<script type="text/javascript">
function passData() {
var name = document.getElementById("pass_data").value;
var dataString = 'pass=' + name;
if (name == '') {
alert("Please Enter the Anything");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
cache: false,
success: function(data) {
$("#message").html(data);
},
error: function(err) {
alert(err);
}
});
}
return false;
}
</script>
</html>
and here is my php code
<?php
$pass=$_POST['pass'];
echo json_encode($pass);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pass Data to PHP using AJAX without Page Load</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
<h2>Enter Some Data Pass to PHP File</h2>
<div class="row">
<div class="col-md-3">
<form>
<div class="form-group">
<input type="text" id="pass_data" class=" form-control">
<input type="button" id="success" class="btn btn-success" value="Set">
<p id="message"></p>
</div>
</form>
</div>
</div>
</div>
</body>
<script type="text/javascript">
$("#success").click(function () {
var name = document.getElementById("pass_data").value;
var dataString = 'pass=' + name;
if (name == '') {
alert("Please Enter the Anything");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
cache: false,
success: function (data) {
$("#message").html(data);
localStorage.setItem("data",data);
},
error: function (err) {
alert(err);
}
});
}
return false;
})
$(document).ready(function () {
var someVarName = localStorage.getItem("data");
console.log(someVarName)
$("#message").html(someVarName);
});
</script>
</html>
First of all i changed your js code to use more jquery syntax, as you already have included it (i trigger the on click event on the script and i don't put it in in html). After that in order not to lose your variable after refresh on ajax success i pass the value of data to localstorage, and after refresh (on document ready) i retrieve it and display it in the label.
Of course every time you put a new value and display it, it over-writes the previous one, so after refresh you display the latest value put in your input field.
I am not sure I understand what you mean but...
Before this line:
<!DOCTYPE html>
enter
<?php session_start(); ?>
In this line add
<input type="text" id="pass_data" class=" form-control" value="<?php echo $_SESSION['VAL']; ?>">
and in your php file:
<?php session_start();
$pass=$_POST['pass'];
$_SESSION['VAL'] = $pass;
echo json_encode($pass);
?>

failed to load chats in real time

I have created a basic chat application.
it shows the no. of users when u r logged in and u can chat to any of them .
but the problemm is that newly added chats to receiver is not displaying but its added in mysql and also displaying the messages in the sender's side.
plz help me with this....
<?php
session_start();
?>
<html>
<head>
<title>Live Table Data Edit</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="table-responsive">
<h3 align="center">You Are : <?php echo $_SESSION['name']; ?></h3><br />
<div id="live_data"></div>
</div>
<div id="messages"></div>
<div class="area" style="display:none">
<textarea id="text" name="text"></textarea>
<input type="submit" id="sub" name="sub" value="Send" />
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"select.php",
method:"POST",
success:function(data){
$('#live_data').html(data);
}
});
}
fetch_data();
$(document).on('click', '.first_name', function(){
var id=$(this).data("id1");
fetch_chat();
function fetch_chat()
{
$.ajax({
url:"fetch_chat.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
$('#messages').html(data);
$("div.area").show();
}
});
}
$("#sub").off("click").on("click", function() {
var text= $("#text").val();
$.post('insert_chat.php',{id:id,msg:text},function(data){
$("#messages").append(data);
$("#text").val('');
});
});
});
});
</script>

Uncaught ReferenceError: 'somevar' is not defined

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.

Categories

Resources