Using pure javascricpt ajax request to echo in php [closed] - javascript

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 2 days ago.
Improve this question
Hey im trying to get rid of jquery and go pure javascript.
The problem is when do the ajax request no data is coming back from the request
Here is process. I am not getting any data in the processing part.
<form name="inputform" method="post">
<input type="text" id="user" name="user">
<input type="text" id="name" name="name">
<input type="text" id="email" name="email">
<input type="button" value="submit" onclick="myFunction()">
</form>
<script>
function myFunction()
{
var data = new FormData();
//apend name first then variable
var user = document.getElementById("user").value;
var name = document.getElementById("name").value;
data.append('user', email);
data.append('name', name);
data.append('email', email);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'test-process.php', true);
xhr.onload = function () {
// do something to response... show data in alert
//console.log(this.responseText)
alert(this.responseText);
};
xhr.send(data);
}
</script>
test-process.php
<?php
$user = $_POST["user"];
$name = $_POST["name"];
$email = $_POST["email"];
echo $user;
echo $name;
?>

Related

Javascript dynamicly change DOM using PHP

PHP code
<?php
...
//Extract the data that was sent to the server
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$findemail = [
"email" => $email,
"password" => $password,
];
$cursor = $collection->findOne($findemail);
if($cursor){
if($cursor['email'] == $email and $cursor['password'] == $password){
// I Know these two lines don't work but I want to show what I want to do
echo "success";
header('location: cms-view-products.html');
}
else {
echo "failed";
header('location: login.php');
}
}
?>
AND this is my HTML code
<?php include('demo2.php') ?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="demo2.php" onsubmit="return false"; method="post">
Email: <input type="email" name="email" required >
name: <input type="password" name="password" required >
<button type='submit' onclick="loadContent()">Load</button>
</form>
<div id="ServerContent">
<p>Dynamically loaded content goes here</p>
</div>
<script>
function loadContent(){
var url = "demo2.php";
var email = document.getElementsByName('email').value;
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById("ServerContent").innerHTML = this.responseData;
}
else
alert("Error communicating with server");
}
var data = `JSON.stringify({
"email": "document.getElementsByName('email').value",
"name": "document.getElementsByName('name').value"
})`;
xhr.send(data);
}
</script>
</body>
</html>
I've currently tried to echo the message via JS, the specific element <p id=" feedback"></p>, nevertheless it doesn't work. With PHP the process works, nevertheless, I can't redirect users using headers. I've found $_SESSION could resolve this issue. However, my question is to use JS to open a pop-up and then redirect the user to x page?
I edited the post since comments advised me about using Ajax and so this is my first attempt. I can always achieve one of the two either redirect the user to x page or show an error massage. but I can't do both.
Also, I don't want to alert the massage, but to change HTML element dynamically.
Thanks guys for your time and comments.

Is this php login system secure? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Is this login page secure, researching about sql-injection, is their a vulnerability if so how do I manage it?
I previously encrypted the users details into a file and stored it locally. I also use localhost, thinking about moving to a domain. Are there any issues with storing users details in a file?
Please disregard the html
<?php
session_start();
?>
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type="text" name="Username"value="">
<?php if ($_SERVER["REQUEST_METHOD"] == "POST"){
$user = $_REQUEST['Username'];
} ?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type="password" name="Password"value="">
<?php if ($_SERVER["REQUEST_METHOD"] == "POST"){
$password = $_REQUEST['Password'];
}
if (isset($_POST['submit'])) {
$file = $user.".txt";
if (file_exists($file)){
$contents = file_get_contents($file);
$ciphering = "AES-128-CTR";
$iv_length = openssl_cipher_iv_length($ciphering);
$options = 0;
$decryption_iv = '#secret#';
$decryption_key = "#key#";
$decryption= openssl_decrypt ($contents, $ciphering,
$decryption_key, $options, $decryption_iv);
if($decryption==$password){
echo("details match");
setcookie("username", $user,time()+2000);
$_SESSION["logged_in"] = true;
$_SESSION["username"] = $user;
header("Location:/login/new folder/findchat.php?username");
exit();
}
else{
echo('Complete im not a robot');
}
}
else{echo("pasword or username is not valid");}
}
?>
<input type="submit"value="submit"name="submit">
</body>
</html>
Apologies of my bad spelling, Thanks
Wow, this is awful. There's tons of vulnerabilities. Here's the ones that jump out at me at first glance:
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
This is vulnerable to XSS, like this: http://example.com/badlogin.php/"><script>alert("xss")</script>
$file = $user.".txt";
if (file_exists($file)){
$contents = file_get_contents($file);
Trivial directory traversal.
$decryption= openssl_decrypt ($contents, $ciphering,
$decryption_key, $options, $decryption_iv);
if($decryption==$password){
You're supposed to hash passwords, not encrypt them.
About the only vulnerability you don't have is SQL injection, and that's because you don't use any SQL.

How to stop page refresh using Javascript [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 3 years ago.
Improve this question
I tried multiple ways to stop the page but unfortunately, it won't work, I have one frontend form of Wordpress Plugin
i try may time but code not worked
Plugin form code
echo '<div id="submit_car_form">';
echo '<form id="cd_car" name="cd_car" class="cd_car" method="post" action="'.$_SERVER['PHP_SELF'].'" enctype="multipart/form-data" >';
echo '<input type="hidden" name="author_id" value="'. get_current_user_id().' " />';
echo '<p><label for="title">Title</label><br />';
echo '<input type="text" id="title" value="" size="60" name="title" />';
echo '</p>';
..........................
i Have multiple inputs
..........................
echo '<p align="left"><input type="submit" tabindex="6" id="submit_car" name="submit_car" /></p>';
wp_nonce_field( "car-frontend-post" );
echo '</form>';
echo '</div>';
Javascript Code for Stop refresh on form Submit
jQuery(document).ready(function($) {
$('#submit_car').on('submit', function(event){
// $('#cd_car').on('submit', function(e){
// $('#cd_car').submit(function(e){
// $('#submit_car').click(function(e){
e.preventDefault();
var message = document.getElementById("file").value;
var title = document.forms["cd_car"]["title"].value;
if (title == ""){
alert("Title cannot be empty");
return false;
}
else {
$.ajax({
type: 'POST',
dataType: 'JSON',
data: new FormData($('#car_data')[0]),
contentType: false,
cache: false,
processData: false,
success: function(data){
console.log(data);
alert('Your Form Submited');
},
error: function(data){
console.log(data);
alert('something wrong');
}
});
return false;
}
});
});
Your form has an id of cd_car, not submit_car! Therefore, your JS handler will not target it until you change the selector.
Also, as mentioned in the comments, your event object in your handler is called event, but in your code you are using e.preventDefault() instead of event.preventDefault()

AJAX request failing to be recognized as POST by PHP script [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 3 years ago.
Improve this question
I am trying to post a form to a PHP script, and it is getting stuck at validating the request as a POST request, and thus it exits from the PHP script. The AJAX request returns as successful, but the data returned from the database says the recognition of the request as POST failed. I've tried changing the content types etc, to no avail.
JS:
$(document).ready(function() {
$("#delete4").on('click', function(e) {
e.preventDefault();
var ok = confirm('Are you sure you want to delete this?');
if (ok == true)
{
console.log("true")
var data = $("#form4").serialize();
$.ajax({
data: data,
type: "post",
url: "delete_AJAX.php",
success: function(data) {
console.log("successfully deleted");
console.log(data);
//$("#div4").remove();
},
error: function(data) {
alert("fail");
console.log(data);
}
});
} else {
return;
}
});
});
HTML:
<form type="text" name="form4" id="form4" action="delete_AJAX.php" method="post">
<div class="aligner">
<button type="button" class="button_div" name="edit" onclick="send(52)">Edit</button>
<button type="button" class="button_div" id="delete4">Delete</button>
<button type="button" class="button_div" name="read" onclick="send2(52, 13)">See</button>
</div><br>
<input type="hidden" id="hidden_c4" value="13" name="hidden_c">
<input type="hidden" id="hidden_bid4" name="hidden_bid" value="52">
</form>
PHP:
require_once("db.php");
if ($_REQUEST['REQUEST_METHOD'] === 'POST')
{
$bid = $_POST['hidden_bid'];
echo "passed request";
$sql = "SELECT * FROM xxx WHERE yyy = $bid";
$result = mysqli_query($connection, $sql);
if ($result === false)
{
die("f1");
}
$resultCheck = mysqli_num_rows($result);
if (!resultCheck > 0)
{
echo "ERROR NO RESULT";
exit();
};
$row = mysqli_fetch_assoc($result);
$delete_cover = $row['cover'];
unlink($delete_cover);
// updating table row
$sql2 = "DELETE FROM xxx WHERE (yyy=?);";
$stmt = mysqli_stmt_init($connection);
if (!mysqli_stmt_prepare($stmt, $sql2))
{
header("Location: ../create.php?error&prepare1111");
exit();
}
else
{
$stmt->bind_param("i", $bid);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
$connection->close();
echo "successfully deleted";
}
} else {
echo "FAILURE TO REQUEST";
}
So I keep consistently getting failure "FAILURE TO REQUEST", and when I remove any barrier to the script, post is shown as empty, and the variables arent set. Thus it stops at the "f1" error. Any help would be amazing!! Thankyou!
You seem to be using the wrong global variable for the "REQUEST_METHOD".
Instead of $_REQUEST['REQUEST_METHOD'] use $_SERVER['REQUEST_METHOD']
In the conditional,
$_REQUEST['REQUEST_METHOD'] should be replaced with $_SERVER['REQUEST_METHOD'].
Maybe could this help
if( $_POST ) {
echo 'posted';
//do some stuff
}

Why is this post method not being retrieved? [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 5 years ago.
Improve this question
Currently working on a messaging system for my site. I've created a JavaScript function to send post data, and a corresponding PHP file to insert the data. However, the data is not being sent to the database. I'm not sure if the error is in the JavaScript or the PHP file as there is no error log being created.
HTML:
<form action="javascript:sendPM();" name="pmForm" id="pmForm" method="post">
<input name="pm_send_id" id="pm_send_id" type="hidden" value="<?php echo $_SESSION['userID']; ?>" />
<input name="pm_send_name" id="pm_send_name" type="hidden" value="<?php echo $_SESSION['userName']; ?>" />
<input name="pm_receive_id" id="pm_receive_id" type="hidden" value="<?php echo $row['userID']; ?>" />
<input name="pm_receive_name" id="pm_receive_name" type="hidden" value="<?php echo $row['userName']; ?>" />
X
<h4>Send to <?php echo $row['userName']; ?></h4>
<div class="sectionheader"></div>
<div id="interaction"></div>
<br>
<p>Comment:</p>
<textarea name="pmTextArea" id="pmTextArea"></textarea>
<p>Select Video:</p>
<input name="pmSubmit" type="submit" value="Submit" />
</form>
JavaScript:
$('#pmForm').submit(function(){$('input[type=submit]', this).attr('disabled','disabled');});
function sendPM(){
var pmTextArea = $("pmTextArea");
var sendName = $("pm_send_name");
var sendID = $("pm_send_id");
var receiveName = $("pm_receive_name");
var receiveID = $("pm_receive_id");
var url = "messages.php";
if (pmTextArea.val() == ""){
$("#interaction").html('Comment field is empty.').show().fadeOut(5000);
}
else {
$.post(url,{ message: pmTextArea.val(), sendername: sendName.val(), senderid: sendID.val(), recname: receiveName.val(), recID: receiveID.val() }, function(data){
$("#interaction").html(data).show().fadeOut(5000);
document.pmForm.pmTextArea value='';
});
}
}
PHP:
<?php
session_start();
require_once 'class.channel.php';
require_once 'dbconfig.php';
$user_message = new USER();
if (isset($_POST['message'])) {
$to = ($_POST['recID']);
$from = ($_POST['senderid']);
$toName = ($_POST['sendername']);
$fromName = ($_POST['recname']);
$msg = htmlspecialchars($_POST['message']);
$stmt = $user_message->runQuery("INSERT INTO inbox(send_id, receive_id, timesent, comment) VALUES(?, ?, ?, ?)");
$stmt->bindValue(1,$from);
$stmt->bindValue(2,$to);
$stmt->bindValue(3,now());
$stmt->bindValue(4,$msg);
$stmt->execute();
}
?>
You need to use # to retrieve value using their id, which you are missing.
var pmTextArea = $("pmTextArea");
should be
var pmTextArea = $("#pmTextArea");
And yes, you need to correct, which #RyanHame pointed
document.pmForm.pmTextArea value='';
to
document.pmForm.pmTextArea.value='';

Categories

Resources