PHP fails to get $_POST from JS - javascript

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.";
}
?>

Related

Passing data between PHP pages [closed]

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'));
}
?>

Pop up box with message from php file

I have been working on a php file and would like to display whether a file has been uploaded or not
I have tried:
if (move_uploaded_file($file_tmp, $file)) {
echo "<script type='text/javascript'>alert('File sucessfully uploaded');</script>";
} else {
echo "<script type='text/javascript'>alert('Upload failed');</script>";
}
But it is not producing a pop up. However I can see it in the developer options under response. Any idea how I can solve this please?
You'll have to print alert(); inside a valid html. See this example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload</title>
</head>
<body>
<form name="form" method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
Upload File: <input type="file" size="30" id="userfile" name="userfile">
<?php
$upload_dir = $_SERVER['DOCUMENT_ROOT'] . "/upload/";
if (!is_dir($upload_dir)) {
#mkdir($upload_dir, 0755, true);
}
if (isset($_FILES['userfile'])) {
$temp_name = $_FILES['userfile']['tmp_name'];
$file_name = $_FILES['userfile']['name'];
$file_path = $upload_dir.$file_name;
}
if ((isset($_FILES['userfile'])) && (is_uploaded_file($_FILES['userfile']['tmp_name']))) {
if (#move_uploaded_file($temp_name, $file_path)) {
#chmod($file_path,0755);
echo "<script type='text/javascript'>alert('File sucessfully uploaded');</script>";
} else {
echo "<script type='text/javascript'>alert('Upload failed');</script>";
}
}
?>
<input type="submit" name="submit" value="Upload">
</form>
</body>
</html>
This example works fine for me. I hope this helps.

Browser does not response to header redirect

please help... i am new to php. Thanks
php1 is to send a data ('1234') via method Post to php2. php2 is supposed to redirect using Header Location to php3 with a data ('invalid').
Developer Tools of Chrome indicate that everything went well (Post data sent and received. Get data sent and received).
Somehow, the browser does not response and stay at php1. I have tried Safari and Firefox. No response.
Would be really grateful if you could advise. Thanks
The 3 php files are:
php1
<?php
session_start();
$M = '';
if (isset($_GET['m'])) {
$M = $_GET['m'];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#send').click(function () {
var str = '1234';
$.post('php2.php',
{
email: str
},
function (data, status) {
}
);
});
});
</script>
</head>
<body>
<div>
<button id="send">SEND</button>
<br>
<?php echo $M; ?>
</div>
</body>
</html>
php2
<?php
session_start();
ob_start();
error_reporting(E_ALL);
if (!empty($_POST)){
$Email = $_POST['email'];
if (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
header('Location: php3.php?m=invalid');
exit();
}
} else {
header('Location: php1.php?m=nodata');
exit();
}
ob_end_flush();
?>
php3
<?php
session_start();
$M = '';
if (isset($_GET['m'])) {
$M = $_GET['m'];
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<?php echo $M; ?>
</div>
</body>
</html>
Here is a screenshot of chrome developer:
You should change the code for php1.php like this
<?php
session_start();
$M = '';
if (isset($_GET['m'])) {
$M = $_GET['m'];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#send').click(function () {
var str = '1234';
$.post('php2.php',
{
email: str
},
function (data, status) {
$("#content").html(data); // <----- ADDED
}
);
});
});
</script>
</head>
<body>
<div id="content">
<button id="send">SEND</button>
<br>
<?php echo $M; ?>
</div>
</body>
</html>

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);
});

How to enable javascript in my website?

I am doing a project to remotely display the data on the P10 Modules. I made the website for it, but whenever I want to retrieve data from the specific webpage on my website I get the error that is mentioned below;
The error I get when I try to retrieve data from the webpage1
The URL for the webpage is http://haider.paks.pk/test1/newfile.txt
<html>
<body>
<script type="text/javascript" src="/aes.js" ></script>
<script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("b2a5a77ff21b1f1b4e9b8d9099c2f834");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://haider.paks.pk/test1/newfile.txt?i=1";</script>
<noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript>
</body>
</html>
How can I possibly solve this issue? How to enable javascript in the coding? Where I would do it?
The codes for the web pages are;
Index page (Main Page)
<?php
//include auth.php file on all secure pages
include("auth.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome Home</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p>Welcome <?php echo $_SESSION['username']; ?>!</p>
<form action="get_msg.php" method="post">
<p>Select Department </p>
<br>
<select name="dept">
<option value="cs">CS</option>
<option value="ee">EE</option>
<option value="btn">BTN</option>
</select>
<p>Enter your message:<br />
<textarea name="sms" rows="10" cols="40"></textarea></p>
<p><input type="submit" value="Send it!" onclick="show()"></p>
</form>
<script>
function show() {
alert("Message send successfully");
}
</script>
<input type="button" name="b1" value="Show History"onclick="location.href='history.php'">
<p>This is secure area.</p>
<p>Dashboard</p>
Logout
</div>
</body>
</html>
get message page (The page that retrieves the sent message from the server
<html>
<body>
<?php
require_once('db_con.php');
?>
<?php
//echo $_POST["sms"];
//$sms = $_POST["sms"];
session_start();
$_SESSION["favcolor"] = $sms;
//echo $_SESSION["favcolor"];
//echo $_POST["sms"];
$sms = $_POST["sms"];
$dept=$_POST["dept"];
echo $dept;
if($dept=="cs"){
$sql_query = "INSERT INTO cs VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if($dept=="ee"){
$sql_query = "INSERT INTO ee VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if($dept=="btn"){
$sql_query = "INSERT INTO btn VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if(mysqli_query($con,$sql_query))
{
}
else
{
echo " Data insertion error.. ".mysqli_error($con);
}
$sql = "SELECT * FROM message";
$iid=last_insert_id($sql);
echo "here";
echo $iid;
?>
</body>
</html>
**Index2 webpage (The webpage that retrieves the message from get message webpage and sends it to the text file **
<html>
<body>
<?php
require_once('db_con.php');
?>
<?php
//echo $_POST["sms"];
//$sms = $_POST["sms"];
session_start();
$_SESSION["favcolor"] = $sms;
//echo $_SESSION["favcolor"];
//echo $_POST["sms"];
$sms = $_POST["sms"];
$dept=$_POST["dept"];
echo $dept;
if($dept=="cs"){
$sql_query = "INSERT INTO cs VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if($dept=="ee"){
$sql_query = "INSERT INTO ee VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if($dept=="btn"){
$sql_query = "INSERT INTO btn VALUES('','$sms')";
if( $sql_query){
header("location:index2.php?deptt=$dept");
}
}
if(mysqli_query($con,$sql_query))
{
}
else
{
echo " Data insertion error.. ".mysqli_error($con);
}
$sql = "SELECT * FROM message";
$iid=last_insert_id($sql);
echo "here";
echo $iid;
?>
</body>
</html>
I have resolved the issue. There is nothing wrong with the code. The only thing due to which this issue raised was that I was using free domain for my website. When I uploaded the same files on a paid hosting service, the issue was resolved and my arduino was able to retrieve the data from the web server.

Categories

Resources