Value from onSubmit prompt to PHP GET - javascript

I have a modifypassword form that modifys the password in a flat file for a user.( I know its not safe etc. ).
So the thing is: whenever I click on modify password on my website, I get a prompt that asked to enter a new password. All fine, after that it will submit the form. But I cannot get the variable somehow that is typed in. I want to $_GET['newpw'] so I can use it to adjust my flat file.
So I have a form like this:
echo "<td> <form action=\"admin.php\" method=\"GET\" onsubmit=\" modifyPassword();\">
this is the modifyPassword function:
<script type="text/javascript">
function modifyPassword() {
var newpw=prompt("Enter a new password");
if(newpw !== null) {
$.ajax({
type: "GET",
url: "admin.php",
data: {data: newpw},
success: function(data) {
console.log(data);
}
});
}
}
</script>
And when the form is actually submitted I want to get the value from what is typed in like this:
echo $_GET['data'];
This is all in the same file.
The output of $_GET['data'] does not show anything.
The rest just works fine when I choose a static password like: "test". It will update my flat file, but I want to get the user input to change the password.
Can someone tell me what i am doing wrong?

I think the base problem may be, that you have event handler onsubmit, but the form gets submited anyway. So the actual prompt has no chance to execute.
You should add return false; or manage the logic in modifyPassword() method.
For example this may help to stop form to submit:
echo "<td> <form action=\"admin.php\" method=\"GET\" onsubmit=\"modifyPassword(); return false;\">"
OR
If you want to submit the form in standard way, just to change the password, just change the input value.
Modify form: echo "<td> <form action=\"admin.php\" method=\"GET\" onsubmit=\"modifyPassword(this)\"><input type=hidden name=newpw />"
And then change the javascript:
<script type="text/javascript">
function modifyPassword(passForm)
{
var newpw = prompt("Enter a new password");
if (newpw !== null)
{
passForm.newpw.value = newpw;
}
}
</script>
Then you should have the value in php in $_GET['newpw'].

Your current PHP code:
}elseif (isset($_GET['Modify'])){ echo $_GET['data'];
But according to the Ajax request code, you don't send a Modify parameter so the $_GET['Modify'] isn't set and therefore the condition returns false and never reach to the echo $_GET['data'] part.
You need to add another parameter to the data as in the following:
JS
<script type="text/javascript">
function modifyPassword(){
var newpw=prompt("Enter a new password");
if(newpw !== null){
$.ajax({
type: "GET",
url: "admin.php",
data: {action: 'modifypass', data: newpw}, //Added another parameter.
success: function(data)
{
console.log(data);
}
});
}}
</script>
PHP
elseif (isset($_GET['action']) && $_GET['action'] == "modifypass"){
echo $_GET['data'];

Related

How to check unique username before form submission

I have been trying this for hours now. I want to check if the username already exist in DB or not. If it does, alert and don't submit. If it doesn't, submit. Here is my code.
$(function() {
$("#new_user").on("submit", function() {
var anyFieldIsEmpty = $('.newuser_input').filter(function() {
return $.trim(this.value).length == 0;
}).length > 0;
if (anyFieldIsEmpty) {
alert("There are empty fields!");
return false;
}
else {
check_curr_username();
return false;
}
});
});
function check_curr_username() {
var username = $("#user_username").val();
$.ajax({
"url": "/checkusername",
"data": {"name":username},
"type": "get",
"dataType": "json",
"success": function(data) {
alert('Username'+' '+data.username +' '+'is already taken' );
$("#user_username").focus();
return false;
},
"error": function() {
$("#new_user").submit();
return true;
}
});
}
This is a Rails form. The code is only working when the username already exist. But if not then the form is not submitting.
we need the checkusername page but i think that the form isn't submitted because error isn't triggered (ie: no error happened).
checkusername page should return a specfic value if the username is not already used then you can process the form.
This is how I check for unique username. I may get down-voted because it's not Rails, but PHP.
<style>.nodisplay{display: none;}</style>
<form id="usersigningup" name="usersigningup" method="post" action="">
<input type='text' name='name' id='nose' pattern='[A-Za-z0-9_]{5,20}' required>
<input type='text' name='password' id='password' pattern='[A-Za-z0-9_]{5,20}' required>
<input class="nodisplay" type="submit" id="usersignup" name="usersignup" value="Go!"></form><br>
<span id='response'></span>
In my CSS the default display for the submit button is set to none. next I use a javascript keyup function to collect the input field of id='nose' (which is the username) and send an ajax post to php which then runs a query on my database.
$(document).ready(function(){
$('#nose').keyup(function(){
var name = $('#nose').val();
$.ajax({
type: 'post',
data: {ajax: 1,name: name},
success: function(response){
$('#response').html(response);
}});});});
Next I use a mysqli query.
<?php include ('connect.php'); if( isset($_POST['ajax']) && isset($_POST['name']) ){
$un = $_POST['name'];
$sql51 = mysqli_query($conn, "SELECT username FROM mysite Where username = '$un'");
if (mysqli_num_rows($sql51) > 0) {
echo "<font color='red'>Sorry <b><i>" . $un . "</i></b> has been taken</font><script>document.getElementById('usersignup').style.display='none';</script>";
} else {
echo "<font color='green'><b>The Username <i>" . $un . "</i> is available</b></font><script>document.getElementById('usersignup').style.display='block';</script>";}
exit;}?>
Notice the 'if' statement in the query; this will either run one of two scripts. The first will be to keep the display of the submit button as none if there is an exact match and echo 'Sorry (username) has been taken' in an html element with the id='response'. The second script will echo 'The username (username) is available' and set the display of the submit button style to 'display:block'; making it clickable.
As I said this all happens on a keyup event so the query runs everytime you press a key and let it up you will see the characters you type in the response element; along with seeing the submit button or not.
The PHP in this example is meant as an example and not to be considered safe from hackers; although, there is a pattern attribute set in the form disallowing most characters. I hope this helps.

"Like" system PHP, using AJAX

i want to make like/unlike system with PHP and jQuery/AJAX..
Here is my form in PHP foreach... Here i have own id's for every form;
<?php foreach ($vid as $var) { ?>
<form class="classform" action="functions/videolike.php" method="post">
<input type="text" name="id" value="<?php echo $var['video_id'];?>">
<button class="submitbuttonclass"type="submit">Like</button>
</form>
<?php } ?>
Here is my Ajax script;
<script>
// this is the id of the submit button
$(".submitbuttonclass").click(function() {
$.ajax({
type: 'post',
url: "functions/videolike.php",
data: $(".classform").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
the codes are working but not correctly;
When i click "like" button is working good, i cheked the database, caunting, inserting, deleting , working good...
But I want to make this with AJAX becouse, refreshing page is stopping the video when user watching video if he click the like button. Video is preloading becouse page refresh...
After i add my ajax script its working. But when i am clicking the like button, AJAX is posting to PHP, only the last id in the foreach loop,
THE Question?
How to make AJAX to get all of the id's in PHP foreach loop ??
And this is my videolike.php if you want to check;
<?php
session_start();
if($_POST['id'] && #$_SESSION["userid"]){
require_once "connectdb.php";
$id = $_POST["id"];
$VLcheck = "SELECT count(*) FROM `videolikes` WHERE user_id = ? AND liked_vid_id=?";
$reslike = $conn->prepare($VLcheck);
$reslike->execute(array($_SESSION["userid"],$id));
$VLrow = $reslike->fetchColumn();
echo $VLrow;
if ($VLrow > 0){
$VLcheck = "DELETE FROM `videolikes` WHERE user_id = ? AND liked_vid_id=?";
$reslike = $conn->prepare($VLcheck);
$reslike->execute(array($_SESSION["userid"],$id));
} else {
$curentsess= $_SESSION["userid"];
$INSlike = $conn->prepare("INSERT INTO videolikes(user_id, liked_vid_id)
VALUES('$curentsess','$id')");
$INSlike->execute();
}} else {die;}
?>
As you have a lot forms with class .classform, so how do you think your script should select the proper one?
The asnwer is - script can't, you should help it). Use .closest function to find closest <form> for a clicked button:
$(".submitbuttonclass").click(function() {
var form = $(this).closest("form");
// or find closest element with class `classform`
//var form = $(this).closest(".classform");
$.ajax({
type: 'post',
url: "functions/videolike.php",
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});

Why Its not working: Jquery Ajax success data with PHP return variable [duplicate]

This question already has answers here:
When should I return true/false to AJAX and when should I echo "true"/"false"
(4 answers)
Closed 6 years ago.
I am trying to create a Ajax functions that made a decision based on a return var from PHP. The main issue I have is the return var will display correctly when I print it to an html class, but the decision within ajax still produces the same result of false.
Below is the PHP form:
<form class="LogInForm" method="post" action="Auth.php" >
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="Email Address" value="<?php echo $_SESSION['email'];?>">
</div>
<div class="form-group">
<input type="password" class="form-control" name="pw" placeholder="password">
</div>
<button type="submit" class="btn btn-default btn-block">Submit</button>
And below is the jquery script:
$('.LogInForm').on('submit', function(e){
var values = $(this).serialize();
// get value of action attribute
var desination = $('.RemoveProd').prop('action');
// get current location url
// prevent page from leaving to desination
e.preventDefault();
$.ajax({
url: desination,
type: 'post',
data: values,
success: function(data){
if(data == 1){;
alert("True");
$('.Test').html(data);
}
else{
alert("False");
$('.Test').html(data);
}
},
error: function(){
}
});
});
The PHP Function:
function Auth()
{
//start session and compture login info
$pass = md5($_POST['pw']);
$user = $_POST['email'];
//connect to DB
$conn = Connect();
//Select all queries
$select = "SELECT Email, Password FROM customers WHERE Email ='".$user."' AND Password = '".$pass."'";
$results = $conn->query($select);
//search in db for user and passwrod, also store quires in var to store in sessions.
if ($results->num_rows > 0) {
$bool = true;
}
else{
$bool= false;
}
echo $bool;
}
What happens is if I don't put in the right password if alerts me False and under the submit button tell me what the data is (which is null). When I put in the correct password, it still alerts me False but the data displays under the submit button as 1.
Also note when I bypass the Ajax function The PHP function works correctly.
Update
I was able to get this working. All i did was move the php file Auth.php to another directory and it seem to fixed the issue. I know it wasn't a file path issue. I thank you all for your time and thank you for answering and pointing me in the right direction with security vulnerabilities.
Javascript == is false if the values are of different types. I suspect the value you're getting back through AJAX is being read as the string "1" instead of the integer 1 (or the boolean TRUE). Try changing your comparison to:
if(data == '1')...
i have tested this, its working correct
$('.LogInForm').on('submit', function(e){
var values = $(this).serialize();
// get value of action attribute
var desination = $('.RemoveProd').prop('action');
// get current location url
// prevent page from leaving to desination
e.preventDefault();
$.ajax({
url: desination,
type: 'post',
data: values,
success: function(data){
//remember the returned value is a type string if not changed or maybe it a raw integer from php
if(parseInt(data.trim().replace(/\D*/g,'')) == 1){
alert("True");
$('.Test').html(data);
}
else{
alert("False");
$('.Test').html(data);
}
},
error: function(e){
//check the logged error for more details
console.log(e)
}
});
});

Unable to send jQuery variable with string content to PHP using jQuery AJAX function?

The code snippet for the jQuery function looks like:
function addMessage() {
if (textval != "") {
text_string='<div class="alert-box round"><p class="text-left">' + userName + ':' + textval + '</p></div></br>';
alert(text_string);
$.ajax({
type:"POST",
url:"process.php",
data: {'text_string': text_string},
cache:false,
success:function(){
alert("submitted")
}
});
$("input[type=text]:last").val("");
}
enterButton = 0;
}
The process.php code looks like:
<body>
<?php
//$host = "localhost";
$text_string=$_POST['text_string'];
echo "string submitted is".$text_string;
?>
</body>
I get alerts showing value of text_string and then the "submitted", but when I open the php page, it shows an error:
Undefined index: text_string
I've seen various answers, none of them seem to be the case for mine. Is the problem in PHP code or jQuery code or both?
If you want to save the value passed by the AJAX request for the next time you load "process.php", try saving it in the session. So, you could change your code to:
<?php
session_start();
// Store value in session if it is passed
if (isset($_POST['text_string'])){
$_SESSION['text_string'] = $_POST['text_string'];
}
// Read and echo value from session if it is set
else if (isset($_SESSION['text_string'])){
$text_string=$_SESSION['text_string'];
echo "string submitted is".$text_string;
}
?>
Now, your PHP script will store the passed value in the session, and will echo that stored value should you load the page elsewhere. (Another alternative is to store the value in a database...though I'm not sure if you have one set up at the moment.)
Hope this helps! Let me know if you have any questions.

How to access Javascript array in PHP file and printing array values in Javascript

I have first PHP file where I have form and it's action is directing me to next php file. The code snippet is as below:
<form name="drugForm" action="drug_form2.php" onsubmit="return validateForm()" method="post">
In function validateForm (javascript) I am checking whether text area is filled and at least a checkbox is checked. And I am creating array, here in javascript, to get checkbox values. The js code is below:
function validateForm()
{
var x=document.forms["drugForm"]["dname"].value;
var y=document.drugForm.drug;
var y_array = [];
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else if (Boolean(x))
{
for(k=0;k<y.length;k++)
{
if(y[k].checked)
{
var arr_val = y[k].value;
y_array.push(arr_val);
//alert(arr_val);
}
}
for(m=0;m<y.length;m++)
{
if(y[m].checked)
{
for(l=0;l<y_array.length;l++)
{
alert("This is array " + y_array[l]);
}
dataString = y_array ; // array?
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "drug_form2.php",
data: {data : jsonString},
cache: false,
success: function(){
alert("OK");
}
});
//alert("The array length is " + y_array.length);
//return true;
}
}
alert("Check one checkbox at least");
return false;
}
}
Here, from this function I want send array to php, for this reason I referred following link but it didn't work:
Send array with Ajax to PHP script
Now, my queries are as following:
Why am I not able to print array value inside second for loop? and
How can I access javascript array in PHP file?
I have PHP file too to check whether array values are printing properly, but it is not giving those values. Below is second PHP file to get javascript array in PHP file:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$data = json_decode(stripslashes($_POST['data']));
// here i would like use foreach:
foreach($data as $d){
echo $d;
}
echo "Its in form2 and working fine";
?>
</body>
</html>
Am I including ajax function at right place?
You can just append each item in your javascript array into a string seperated by a unique character/s. As for my experience, it's easier than passing it as an array. Then pass the string to PHP.
In your PHP code, use the string method explode to create an array out of the string. Then go with the rest of your code logic.
if javascript array is simple array,than change it to csv and passed it has string.
In php serverside just explode that string you will again get array in php.
javscript
$.ajax({
type: "POST",
url: "drug_form2.php",
data: {data : y_array.join(',')},
cache: false,
success: function(){
alert("OK");
}
});
php
$array= explode(",", $_POST['data']);

Categories

Resources