Passing data between PHP pages [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
My index.php is:
<head>
<meta charset="UTF-8">
<title>Example Ajax PHP Form</title>
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.0.min.js"></script>
</head>
<body>
<form id="my_form_id">
Your Email Address: <input type="text" id="email" /><br>
<button type="submit" id="ddd">button</button>
</form>
<script>
$(document).ready(function(){
$('#my_form_id').submit(function(e){
var email = $('#email').val();
console.log(email);
$.ajax({
type: 'post',
url: 'http://localhost/script.php',
data: {email: email},
success: function(data){
alert(data);
}
});
});
});
</script>
</body>
My goal is to pass an email from my index.php page to another file titled script.php. The script.php code is:
<?php
$emailAddress = '';
if(isset($_POST['email'])){
echo $_POST['email'];
$emailAddress = $_POST['email'];
}
echo 'Received email was: ' .$emailAddress;
?>
When I run my index.php page I am able to enter an email address and the data is successfully displayed in an alert box. However, when I refresh the script.php page it doesn't display the email address. Any help would be greatly appreciated!

<?php
$e = array();
$e['error'] = 'not ok';
if(isset($_POST['email'])){
//echo $_POST['email'];
//$emailAddress = $_POST['email'];
$e['emailAdress'] = $_POST['email'];
$e['text'] = 'Received email was: ';
$e['error'] = 'ok';
}
echo json_encode($e);
?>
Use the json_encode method in your php script
<script>
$(document).ready(function(){
$('#my_form_id').submit(function(e){
var email = $('#email').val();
console.log(email);
$.ajax({
type: 'post',
url: 'http://localhost/script.php',
data: {email: email},
success: function(data){
alert(data.error);
//do stuff
}
},"json");
});
});
</script>
And it is your index.php script that will receive the data.
It is Ajax which and made to work on a single page!

It's not possible to keep the value between page refresh unless you use some storage method: file, database or session.
In case you are using some of this, in index.php the first thing to do is retrieved the stored email and set it as the value of the input.
Simple pseudocode:
If there is email stored
Set email as input value
Show form
Check https://www.php.net/manual/en/reserved.variables.session.php for more info in PHP sessions
---- EDIT with session storage:
at the beggining of index.php add:
<?php
session_start();
$emailAddress = isset($_SESSION['email']) ? $_SESSION['email']:'';
?>
and the input definition now is:
Your Email Address: <input type="text" id="email" value="<?= $emailAddress ?>"/><br>
And script.php have to be like:
<?php
session_start();
$emailAddress = '';
if (isset($_POST['email'])) {
echo $_POST['email'];
$emailAddress = $_POST['email'];
$_SESSION['email'] = $emailAddress;
} else {
unset($_SESSION['email']);
}
echo 'Received email was: ' . $emailAddress;

If you want to display the email in the next page (i.e. script.php), you can use the following codes:
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Example</title>
</head>
<body>
<form method="post" action="script.php">
<p>Your Email Address: <input type="email" name="email" required /><br />
<button>Send</button></p>
</form>
</body>
</html>
script.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Example - script.php</title>
</head>
<body>
<p><?php
if(isset($_POST['email'])){
echo 'Received email was: ' . $_POST['email'];
} else {
echo 'No email is received. Something went wrong.';
}
?></p>
</body>
</html>
Alternatively, if you insist using AJAX to pass the data and display on screen, you can do the followings:
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Example</title>
<style>
#result { display: none; }
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</head>
<body>
<p>Your Email Address: <input type="email" name="email" id="txt_email" required /><br />
<button type="button" id="btn_send">Send</button></p>
<div id="result"></div>
<script>
$('#btn_send').click(function(){
$.post('script.php', {
email: $('#txt_email').val()
}, function(data) {
if(data.status == 'error') {
console.log('Error occurred');
} else if(data.status == 'success') {
$('#result').html('Email is ' + data.email).show();
}
});
});
</script>
</body>
</html>
script.php
<?php
header('Content-Type: application/json');
if(isset($_POST['email'])) {
$email = trim($_POST['email']); // TODO: validate email via filter_var()
echo json_encode(array('email' => $email, 'status' => 'success'));
} else {
echo json_encode(array('status' => 'error'));
}
?>

Related

PHP/jQuery Instant Search Not Working

I'm trying out a tutorial to learn how to do instant search with PHP/jQuery. I can't seem to find why this code won't work. This search was working before when I had the PHP in the same file as the index, but when I moved it to another file, it stopped working. I keep getting this console error message with each keystroke: ReferenceError: Can't find variable: $_POST. Any help would be deeply appreciated.
index.php file
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset-utf-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function searchkey() {
var searchTxt = $("input[name='search']").val();
$_POST("search.php", {searchVal: searchTxt}, function(output) {
$("#output").html(output);
});
}
</script>
<title>Search</title>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="search" placeholder="Search for members..." onkeyup="searchkey();">
<input type="submit" value="Search">
</form>
<div id="output"></div>
</body>
</html>
search.php file (same location as index.php)
<?php
$connection = mysqli_connect('localhost','root','root','LBD');
$output='';
if(isset($_POST['searchVal'])){
$searchkey= $_POST['searchVal'];
$searchkey=preg_replace("#[^0-9a-z]#i", "", $searchkey);
$query = mysqli_query($connection,"SELECT * FROM members WHERE ownerName LIKE '%$searchkey%' OR companyName LIKE '%$searchkey%'") or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output="There was no search result!";
}
else{
while($row=mysqli_fetch_array($query)){
$oName=$row['ownerName'];
$cName=$row['companyName'];
$output .='<div>'.$oName.'<br/>'.$cName.'</div>';
}
}
}
echo ($output);
?>
Looks like you've used the PHP $_POST in your script..
Try to use:
$.POST
Try this
$.ajax({
url: "search.php",
type: 'POST',
data: {
searchVal: searchTxt
},
})
.done(function(output) {
$("#output").html(output);
});

PHP fails to get $_POST from JS

I have created an HTML page and am attempting to use AJAX via JS to echo from a PHP page:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>User Retrieval</title>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
function getid(){
var userid = document.getElementById('userid').value;
$.post('Users2.php', {postname:userid},
function(data){$('#results').html(data);});
};
</script>
</head>
<body>
<h1>User Retrieval</h1>
<p>Please enter a user ID:</p>
<input type="text" id="userid" placeholder="Please insert user ID" onkeyup="getid()" />
<div id="results"></div>
</body>
</html>
I have tested the JS and see that userid indeed gets the information from the HTML.
I then wrote the following PHP:
<?php
if (isset ($_POST['postname'])) {
$name = $_POST['postname'];
echo name;
}
else
{
echo "There is a problem with the user id.";
}
?>
However, I am always getting the else echo statement.
What am I missing here?
I am using XAMPP for local host checks.
Try this, It might help
<?php
if ($_POST[]) {
$name = $_POST['postname'];
echo $name;
}
else
{
echo "There is a problem with the user id.";
}
?>
var userid = $("#userid").val();
$.ajax
({
type:'post',
url:'user2.php',
data:{
get_id:"user2.php",
userid:userid,
},
success:function(data) {
if(data){
$("#results").html(data);
}
});
Php File
<?php
if (isset ($_POST['userid'])) {
$name = $_POST['userid'];
echo $name;
}
else
{
echo "There is a problem with the user id.";
}
?>

I'm just learning code.I want to know javascript or php code to show hidden paragraph <p>

<p hidden> Wrong email or password
html
$email=$_POST["login"];
$password=$_POST["password"];
$zz= "Select * from employer where EMMail='$email' and EMpassword='$password'";
$sql="select * from student where StudentEmail='$email' and StudentPassword='$password'";
if $email && $password !=$zz || $email && $password !=$sql{
}
how to show that para when username or password is incorrect?
Using PHP
You can simply just do something like this
$failed=true;
if $email && $password !=$zz || $email && $password !=$sql{
$failed=false;
}
and later where this certain paragraph is found:
echo "<p ". ($failed?"hidden":"")+">Wrong password!</p>
Different Pages
I would recommend to use different pages like this:
login
|--index.php //loginform
|--login.php
|--fail
| |--index.php //with link to login form
home
|--index.php
includes
|--sql.php
login/index.php
<html>
<head>
<title>
Login
</title>
<body>
<form action="login.php" method="POST">
<table>
<tr><td>User</td><td><input name="user" placeholder="johndoe123/></td></tr>
<tr><td>Pass</td><td><input type="password" name="pass" placeholder="iluvyou%&-"/></td></tr>
<tr colspan=2><td><input type="submit" value="Login" /></td></tr>
</table>
</form>
</body>
</html>
login/login.php
Note: Use prepared statements!!! The method you used is extremly vulnerable to SQL injection and XSS. Also: PLEASE hash the password(s)!
<?php
include "/includes/sql.php";
$user=$_POST["user"];
$passtry=$_POST["pass"];
$sql="SELECT * FROM users WHERE user='?'";
$cmd = $con->prepare($sql);
$cmd->execute(array($user));
if($entry=$cmd->fetchObject()){
$pass=$entry->pass;
}else{
header("Location: fail");
exit(0);
}
if(password_verify($passtry,$pass)){
session_start();
$_SESSION["login"]=true;
$_SESSION["user"]=$user;
header("Location: ../home");
}else{
header("Location: fail");
exit(0);
}
?>
fail/index.html
<html>
<head>
<title>
Wrong password!
</title>
</head>
<body>
<p>Wrong password. Try again!</p>
</body>
</html>
home/index.html
<?php
session_start();
if(!$_SESSION["login"]){
header("Location: ../login/fail");
exit();
}
?>
<html>
<head>
<title>
<?php echo $_SESSION["user"] ?> - Home
</title>
</head>
<body>
PRIVATE CONTENT!!!
</body>
</html>
includes/sql.php depends on your sql engine.
Note: In your register form you must save the password using password_hash()

send information to database without having page reload

I have a site where you type into a text box and it will send what I wrote to my database.
I have been stuck with my page having to reload which is very troubling in my case. i am not familiar with ajax but i have heard it can be used to complete this task. i have 2 files one is called demo.php this sends the information to the server and at this time has a header that redirects me back to that page which i don't want.
I want to be able to keep sending things data to the sever without the page reloading. the other page is the index.php this is were i right into the text box and send the text to my database both files are listed below.
this is the demo.php
<?php
header("Location: http://mywebsite.com");
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value = $_POST['firstname'];
$sql = "INSERT INTO MyGuests (firstname) VALUES ('$value')";
if ($conn->query($sql) === TRUE) {
echo "working";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
this is the forum on index.php were i enter the information and send it. i need it to stay on that page and not reload in any way.
<form action="demo.php" method="post" />
<p> <input id="textbox" type="text" name="firstname" placeholder="Enter What You Want Your Message To Be" /></p>
<input id="textbox1" type="submit" value="Submit" />
</form>
my second attempt at index.php
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="navigation.css href="navigation/navigation.css">
<link rel="stylesheet" href="navigation/navigation.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
</head>
<body>
<form action="ajax_target.php" method="post" id="ajax-form">
<input type="text" name="firstname" />
<input type="button" name ="send" onclick="return f(this.form ,this.form.fname ,this.form.lname) " >
</form>
</body>
<script>
function submitForm(form){
var url = form.attr("action");
var formData = $(form).serializeArray();
$.post(url, formData).done(function (data) {
alert(data);
});
}
$("#ajax-form").submit(function() {
submitForm($(this));
});
</script>
</html>
You can have two files/pages for your purpose:
1. Form page
2. Ajax processing page where you request values will be inserted into your database.
Add this to your head tag
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
Steps to utilize ajax:
1. Include jquery library in form page
2. Include html form
3. Save values from ajax, that means process that ajax
HTML form suppose to be like this:
<form action="ajax_target.php" method="post" id="ajax-form">
<input type="text" name="firstname" />
<input type="submit" name="send" value="send" >
</form>
Ajax call:
function submitForm(form){
var url = form.attr("action");
var formData = $(form).serializeArray();
$.post(url, formData).done(function (data) {
alert(data);
});
}
$("#ajax-form").submit(function() {
submitForm($(this));
return false;
});
ajax_target.php handles formData, its validation and insertion to database.
your html/index form consists
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
</head>
<body>
<form action="demo.php" method="post" id="ajax-form">
<input type="text" name="firstname" />
<input type="submit" name="send" value="send" >
</form>
</body>
<script>
function submitForm(form){
var url = form.attr("action");
var formData = $(form).serializeArray();
$.post(url, formData).done(function (data) {
alert(data);
});
}
$("#ajax-form").submit(function() {
submitForm($(this));
return false;
});
</script>
</html>
your demo.php includes
<?php
//your db insertion goes here.
echo "inserted successfully";
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="navigation.css href="navigation/navigation.css">
<link rel="stylesheet" href="navigation/navigation.css">
</head>
<body>
<form action="ajax_target.php" method="post" id="ajax-form">
<input type="text" name="firstname" />
<input type="submit" name ="send" value="send" >
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
<script>
$(document).ready(function(){
var options = {
beforeSend: function () {
if (!confirm('Are you sure to submit ?')) {
return false;
}
},
success: function (response) {
alert(response);
},
error: function (response) {
alert(response);
};
}
$('#ajax-form').ajaxForm(options);
});
</script>
</body>
</html>
updated your index.php

Get responses from php (SweetAlert)

I want to make form html look like this :
<script>
function name()
{
var name = $('#name').val();
var url_send = 'send.php';
$.ajax({
url : url_send,
data : 'name='+name,
type : 'POST',
dataType: 'html',
success : function(pesan){
$("#result").html(pesan);
},
});
}
</script>
<script src="assets/bootstrap-sweetalert.js"></script>
<script src="assets/sweetalert.js"></script>
<link rel="stylesheet" href="assets/sweet-alert.css">
<form action="#" method="post">
<label>Name</label>
<input type="text" name="name"><br>
<input type="submit" onclick="name();">
<div id="result"></div>
and this is send.php
<?php
$name = $_POST['name'];
if($name) {
echo 'success';
} else {
echo 'failed';
}
?>
And the problem is,how i show SweatAlert modal,when result of php is Success Sweatalert will show Success Modal.And when failed it will show Failed Modal ?
Now what must i edit to my script?
I hope you are expecting code with jquery ajax;
See the code below;
index.php
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<link rel="stylesheet" type="text/css" href="sweetalert-master/dist/sweetalert.css">
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="sweetalert-master/dist/sweetalert.min.js"></script>
<script>
$(document).ready(function () {
$("#submit").on("click", function(e){
e.preventDefault();
var name_val = $("#name").val();
$.post( "send.php", {name_send:name_val}, function(data){
if (data == 'success'){
swal("Good job!", "Nice work!", "success");
return false;
}else{
swal("Here's a message!", "Please type a name");
}
});
});
});
</script>
</head>
<body>
<form>
<label>Name</label>
<input type="text" name="name" id="name"><br>
<input type="submit" id="submit">
</form>
</body>
</html>
send.php
<?php
$name = $_POST['name_send'];
if($name) {
echo 'success';
} else {
echo 'failed';
}
?>
$.ajax({
url : url_send,
data : {name: name},
type : 'POST',
dataType: 'html',
success : function(pesan){
$("#result").html(pesan);
},
});
in your ajax code you placed data : 'name='+name, , please have a look at what i did , maybe that helps
Jquery ajax accepts object in data parameter data: {key:value}. In the question we are using string as a parameter to data of jquery ajax

Categories

Resources