Send and receive data from PHP - javascript

I'm new to web development, especially PHP, jQuery, AJAX...
I'm trying to make the user enter a name, then the index.html sends it to a php file, the php file saves it to a file of names and changes a div element with the id of status on the website.
I can't figure out the problem, the div element's inner HTML stays "processing..."
index.html
<html>
<head>
<script>
function ajax_post(){
document.getElementById("status").innerHTML = "processing...";
$.post("server.php", { username: $("#userName").val() }, function(data) {
$("#status").html(data);
})
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
Username: <input id="userName" name="userName" type="text"> <br><br>
<input name="myBtn" type="submit" value="Check" onclick="ajax_post();"> <br><br>
<div id="status"></div>
</body>
</html>
server.php
<?php
if(!empty($_POST['username'])){
$data = $_POST['username'];
echo 'You are now registered,' . $data;
$fname = "save.text";
$file = fopen($fname, 'a');
fwrite($file, $data . "\n");
fclose($file);
}
?>
I'm assuming my $.post syntax is wrong, but I don't really understand it.

Try this I have executed this code and it worked for me.
Index.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function ajax_post(){
document.getElementById("status").innerHTML = "processing...";
console.log($("#userName").val());
$.post("server.php", { username: $("#userName").val() }, function(data) {
$("#status").html(data);
})
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
Username: <input id="userName" name="userName" type="text"> <br><br>
<input name="myBtn" type="submit" value="Check" onclick="ajax_post()"> <br><br>
<div id="status"></div>
</body>
</html>
Server.php
<?php
if(!empty($_POST['username'])){
$data = $_POST['username'];
echo 'You are now registered,' . $data;
$fname = "save.text";
$file = fopen($fname, 'a');
fwrite($file, $data . "\n");
fclose($file);
}
?>

Related

jQuery PHP Post

I got a problem maybe is simple but dont know how to load jquery_post.php when I send the data for jquery_send.php I resume I send information from jquery_send.php to jquery_post.php and I want that after send the page jquery_post.php load with the data
This is what I have in jquery_send.php:
<html>
<head>
<link href='http://fonts.googleapis.com/css?
family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#name").val();
var vemail = $("#email").val();
if(vname=='' && vemail=='')
{
alert("Please fill out the form");
}
else if(vname=='' && vemail!==''){alert('Name field is required')}
else if(vemail=='' && vname!==''){alert('Email field is required')}
else{
$.post("jquery_post.php",
{
name:vname,
email:vemail
},
function(response,status){
alert("*----Received Data----*nnResponse : " + response+"nnStatus : " + status);
$("#form")[0].reset();
});
}
});
});
</script>
</head>
<body>
<div id="main">
<h2>jQuery Ajax $.post() Method</h2>
<hr>
<form id="form" method="post">
<div id="namediv"><label>Name</label>
<input type="text" name="name" id="name" placeholder="Name"/><br></div>
<div id="emaildiv"><label>Email</label>
<input type="text" name="email" id="email" placeholder="Email"/></div>
</form>
<button id="btn">Send Data</button>
</div>
</body>
</html>
and in jquery_post.php I have this:
<?php
if($_POST["name"])
{
$name = $_POST["name"];
$email = $_POST["email"];
echo "Welcome ". $name ."!";
?>
It works just fine, but you have a syntax error in you jquery_post.php
<?php
if($_POST["name"])
{
$name = $_POST["name"];
$email = $_POST["email"];
echo "Welcome ". $name ."!";
} // you missed this
?>
it was returning Parse error: syntax error, unexpected end of file
Please try, this may help
<html>
<head>
<link href='http://fonts.googleapis.com/css?
family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#name").val();
var vemail = $("#email").val();
if(vname=='' && vemail=='')
{
alert("Please fill out the form");
}
else if(vname=='' && vemail!==''){alert('Name field is required')}
else if(vemail=='' && vname!==''){alert('Email field is required')}
else{
$.post("post.php",
{
name:vname,
email:vemail
},
function(response,status){
alert("*----Received Data----*nnResponse : " + response+"nnStatus : " + status);
$("#form")[0].reset();
window.location.href = 'post.php';
});
}
});
});
</script>
</head>
<body>
<?php session_start(); ?>
<div id="main">
<h2>jQuery Ajax $.post() Method</h2>
<hr>
<form id="form" method="post">
<div id="namediv"><label>Name</label>
<input type="text" name="name" id="name" placeholder="Name"/><br></div>
<div id="emaildiv"><label>Email</label>
<input type="text" name="email" id="email" placeholder="Email"/></div>
</form>
<button id="btn">Send Data</button>
</div>
</body>
</html>
And in jquery_post.php I have made some changes When you post data to jquery_post.php it will create a session named "user" you can retrieve name any time from the session as I did.
<?php
session_start();
if(isset($_POST["name"]))
{
$_SESSION['user'] = $_POST["name"];
$name = $_POST["name"];
$email = $_POST["email"];
}
echo "Welcome ". $_SESSION['user'] ."!";
?>

PHP in JavaScript brokes all scripts

When I'm using PHP in JavaScript, then all scripts don't work...
Even if I use php in comment.
<script>
//var variable = <?php echo json_encode($_SESSION['abc']); ?>;
</script>
This comment above destroy all scripts in <script></script> tags.
When I'll delete this line with the comment, then every script will work.
The same thing is when I just want to use PHP in JavaScript (without comment).
Could You help me ?
Here is code which was cut by me (to give You only necessary part of code), please help :) :
<?php
session_start();
if (isset($_POST['login']) && isset($_POST['password']) && isset($_POST['email']))
{
$validation = true;
$firstName = $_SESSION['firstName'];
$lastName = $_SESSION['lastName'];
$street = $_SESSION['street'];
$phone = $_SESSION['phone'];
$login = $_POST['login'];
$password = $_POST['password'];
$email = $_POST['email'];
require_once "connect.php";
mysqli_report(MYSQLI_REPORT_STRICT);
try
{
$connection = new mysqli($host, $db_user, $db_password, $db_name);
if($connection->connect_errno!=0)
{
throw new Exception(mysqli_connect_errno());
}
else
{
if ($validation == true) // when validation process will be successfuly done - i cut validation process
{
if($connection->query("INSERT INTO users values (NULL, '$firstName', '$lastName', '$street', '$phone', '$login', '$password', '$email')"))
{
$_SESSION['abc'] = "done";
//here is also header(location) to login page
}
else
{
throw new Exception($connection->error);
}
}
$connection->close();
}
}
catch(Exception $e)
{
echo '<div class="error">error. sorry, please to register in other term</div>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script>
//there are other functions for local/session storage
function deleteSessionData()
{
var variable = "<?php echo $_SESSION['abc']; ?>";
if(variable == "done")
{
sessionStorage.removeItem('firstName');
sessionStorage.removeItem('lastName');
sessionStorage.removeItem('street');
sessionStorage.removeItem('phone');
sessionStorage.removeItem('login');
sessionStorage.removeItem('password');
sessionStorage.removeItem('email');
}
}
</script>
</head>
<body>
<form id="myForm" method="post">
<label for="login">Login: </label>
<input type="text" id="login" name="login">
<label for="password">Password: </label>
<input type="text" id="password" name="password">
<label for="email">E-mail:</label>
<input type="email" id="email" name="email">
<button onclick="java script: document.getElementById('myForm').submit();deleteSessionData();">Register</button>
</form>
</div>
</body>
</html>
you need to comment the php too
//var variable = <?php // echo json_encode($_SESSION['abc']); ?>;
I wouldn't inject PHP into javascript like this without sanitation though.

Send PHP errors back to index

So I have an index.php and a r.php. R.php is the registration part. And index.php is the actual form. My question is how can I have errors from r.php be send back to index.php if they exist. So instead of displaying errors on r.php I want them on index.php and prevent the form from advancing.
Here's the index.php
<!DOCTYPE html>
<html>
<body>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
Its all very simple. Now here's r.php
<?php
$name = $_POST['name'];
if ($name < 3){
//display error
}
else {
//proceed
}
?>
Should I do this with JS? Or this there a better way.
One way is to use sessions:
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<body>
<?php echo isset($_SESSION['message']) ? $_SESSION['message'] : ''; ?>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
<?php
session_start();
unset($_SESSION['message']);
$name = $_POST['name'];
if ($name < 3){ // you probably want strlen($name) < 3
$_SESSION['message'] = 'error';
header('Location: index.php');
exit;
}
else {
//proceed
}
?>
Other than sessions you could redirect back with a query string and use that:
header('Location: index.php?message=' . urlencode('some kind of error');
Then:
<?php echo isset($_GET['message']) ? $_GET['message'] : ''; ?>
Using a single script for this would be easier, just put this all in one file, and check to see if the form has been submitted. If the form has been submitted, you an just include the variables you want straight away.
This is pretty crude, but it gives you an idea of where you can go with this:
<?php
if (isset($_POST['name'])) {
// Begin processing form stuff
$name = $_POST['name'];
// Initialise error variable
$error = null;
if ($name < 3) {
// Display error, for example:
$error = 'Name is less than 3';
} else {
// Proceed
}
}
?>
<!DOCTYPE html>
<html>
<body>
<?php if ( ! empty($error)) { ?>
<p><?php echo $error; ?></p>
<?php } ?>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
</html>
<!DOCTYPE html>
<html>
<?php
$msg = '';
if(isset($_GET['e'])
{
$msg = "Error! Input not valid.";
}
?>
<body>
<?php
if($msg!='')
{
echo "<font color='red'>".$msg."</font>";
}
?>
<form method="post" action="r.php">
<input type="text" name="name" placeholder="Name">
<input type="submit">
</form>
</body>
Just pass a variable e using GET request to the index page if an error is found.
<?php
$name = $_POST['name'];
if ($name < 3){
header("Location: index.php?e=error");
}
else {
//proceed
}
?>
GET request will send the variable e using the URL, and if e is found to be having a value, it means there was an error in r.php
Use javascript for simple form validation. In case you require some security stuff or db stuff, you can use session/cookie or use header function to go back.

Need an Ajax call to destroy session

I have a script where when a user get verified he/she is brought to Home.php. At the moment Home.php doesn't do much. But in the bottom left hand corner I have a log out button. And as you know when the user clicks on this button he expects his session to be destroyed and for him to be redirected to a log in page. Unfortunately you can't make a click listener in php. I have browsed for an hour looking for a solution but I have not been able to find the right key word or something.
This is my code
EDIT: You only really have to read some code from Home.php the est is only if someoe wants to run the code if they are not sure of their answer
Index.php(Login Page)
<?php
session_start();
mysql_connect("localhost","root","") or die ("cannot");
mysql_select_db("virtualdiary") or die ("db");
if (isset ($_POST["Username"])&& isset($_POST["Password"]))
{
$Username = $_POST["Username"];
$Password = $_POST["Password"];
$_SESSION["username"] = $Username;
$DB_Check = " SELECT * from users Where username = '".$Username."' and password = '".$Password."' " ;
$result = mysql_query($DB_Check);
if(mysql_fetch_assoc($result) === false){
$error = "invalid username or password";
}else{
header( 'Location: Home.php' ) ;
}
}
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="Index.css"/>
<title>Login</title>
</head>
<body>
<div id="main">
<div class="messages">
<?php
if(isset($error))
echo $error; ?>
</div>
<form action="Index.php" method="post">
<h5>Diary Name:</h5>
<input name="Username" type="text"/>
<h5>Password:</h5>
<input name="Password" type="password"/>
</br>
</br>
</br>
<input name="login" type="submit"/>
</form>
<p>Click HERE to register.</p>
</div>
</body>
</html>
Home.php
<?php
session_start();
echo "Username = " . $_SESSION["username"] . " !";
mysql_connect("localhost","root","") or die ("cannot");
mysql_select_db("virtualdiary") or die ("db");
if (isset($_POST["entry"])){
$entry = $_POST["entry"];
$submission = "INSERT INTO `virtualdiary`.`entries` (`entry`) VALUES ('". $entry . "')";
mysql_query($submission);
}
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="Home.css"/>
<title>Home</title>
</head>
<body>
<h1>Entry: </h1>
<form method="post" action="Home.php">
<textarea name="entry" rows="24" cols="87">
<?php
if (isset($_POST["entry"])){
echo $entry;
}
?>
</textarea>
</br>
</br>
<input name="submit" type="submit"/>
</form>
<button id="LogOut">Log Out</button>
</body>
</html>
From what I have found from searching around I will need a Home.js file with an ajax call. I don't know the first thing about Ajax so I will probably need code to paste or a very blunt tutorial.
Thanks
You could change the logout href to /Logout.php, and in Logout.php have
<?php
session_start();
session_destroy();
header('Location: /Index.php');
?>
That will simply destroy the users current session, then redirect the user back to the Index.php page.
The AJAX way would be (using jQuery, I can't remember the vanilla JS syntax for ajax calls)
$.ajax({
type: 'GET',
url: '/Logout.php',
success: function(msg) {
if (msg == 'loggedOut') {
window.location.href = 'Index.php';
}
}
});
And then you'd need to change Logout.php, instead of the header line, make it echo/die/print loggedOut (or a json string which would probably be better, but this is just an example).

Get form popup upon successful submission

How do I go about getting this form to display "Submitted" using basic javascript popup window upon successful submission?
<!DOCTYPE html>
<html>
<head>
<title>Site :: </title>
<link rel="stylesheet" media="screen" href="css/wicahost.css" />
<link rel="stylesheet" media="screen" href="css/global.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>
<?php require_once('inc/php/clearfieldJs.php'); ?>
<script type="text/javascript">
$(document).ready(function() {
$("#splashtease").RSV({
rules: [
"required,emAdd,Please enter your email address.",
"valid_email,emAdd,Please enter a valid email address.",
]
});
});
</script>
</head>
<body>
<script src="http://www.benjaminkeen.com/software/rsv/jquery/jquery.rsv.js"></script>
<div id="splashTeaserBox">
<h1 class="wicasplashcenter">Signup!</h1>
<div class="wicasplashcenter">Captivating interests and inspiring collaboration.</div>
<form id="splashtease" action="inc/subscribe.php" method="post">
<?php $usrBrowser = $_SERVER['HTTP_USER_AGENT']; $todayDt = date('Y-m-d'); ?>
<input type="text" name="emAdd" class="splashtease" value="Your Email Address ..." onFocus="clearText(this)" />
<input type="hidden" name="brwsr" value="<?php echo $usrBrowser; ?>" style="margin:0; padding:0;" />
<input type="hidden" name="dt" value="<?php echo $todayDt; ?>" style="margin:0; padding:0;" />
<input type="submit" name="submit" value="" class="splashteasesub" />
</form>
</div><!--splashTeaserBox--></body>
</html>
PHP
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="dnbame"; // Database name
$tbl_name="subscriber"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
/* Obliterate bad input */
$goodEmail = mysql_real_escape_string($_POST['emAdd']);
$goodBrowser = mysql_real_escape_string($_POST['brwsr']);
$goodDate = mysql_real_escape_string($_POST['dt']);
$sql= "INSERT INTO subscriber (Email, Browser, DateSubscribed) VALUES('$goodEmail','$goodBrowser','$goodDate')";
$result = mysql_query($sql);
if (!$result) {
die('Invalid Email, please retry.');
}
else{
echo var success;
}
?>
A basic example:
In subscribe.php, change:
else{
echo var success;
}
to:
else {
echo "<html><body onload=\"alert('Submitted');\"><p>Submission successful.</p></body></html>";
}
#user886187's solution will reload the page upon submission and then display a JavaScript pop-up when the page has reloaded.
You might want to submit the form and then display the pop-up without reloading the page. In that case you need to submit the form via Ajax, and then alert "submitted" in the callback function:
function callback() {
alert('submitted');
}
Here's a tutorial on how to submit a form via Ajax:
http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
put this code in your subcribe.php
else {
header ('Location: formPage.php?message=Success');
}
and this code inside head of formPage.php
<head>
<?php if ($_GET['message']) {echo '<script type="text/javascript">alert("Form Submited Successfully");</script>';} ?>
</head>

Categories

Resources