I'm trying to create a form for changing a users password. No errors are being generated in the console but nothing is being updated. The validation side is also working so it must be down to the Ajax part?
Disclaimer: I know I shouldn't be using mysql in PHP, but I'm trying to get the basics down and will learn mysqli at a later date :)
Also, config.php is used in multiple other functions so I know config.php is fine.
Any idea what is going wrong?
HTML:
<fieldset>
<form method="post" name="password-form" id="form-password">
<label>Password:</label> <br>
<input type="password" name="password" id="password" value="" size="32" />
<br>
<br>
<label>Re-Enter Password:</label> <br>
<input type="password" name="password-check" id="password-check" value="" size="32" />
<br>
<br>
<input type="submit" value="Submit" id="passsubmit">
</form>
</fieldset>
JQuery:
$(function(){
$("#passsubmit").click(function(){
$(".error").hide();
var hasError = false;
var newpass = $("#password").val();
var checkVal = $("#password-check").val();
if (newpass == '') {
$("#password").after('<span class="error">Please enter a password.</span>');
hasError = true;
} else if (checkVal == '') {
$("#password-check").after('<span class="error">Please re-enter your password.</span>');
hasError = true;
} else if (newpass != checkVal ) {
$("#password-check").after('<span class="error">Passwords do not match.</span>');
hasError = true;
}
if(hasError == true) {return false;}
if(hasError == false) {
$.ajax({
type: "POST",
url: "resource/changepassword.php",
data: {newpass:newpass},
success: function(){}
});
};
});
});
PHP:
<?php
session_start();
include('config.php');
$user_check=$_SESSION['login_user'];
$newpass=$_POST['newpass'];
$sql_rec = "select UserID from useradmin where username='$user_check' ";
$rs_rec = mysql_query($sql_rec);
$data_rec = mysql_fetch_object($rs_rec);
$userID = $data_rec->UserID;
$updatesql="UPDATE useradmin SET passcode='$newpass' WHERE UserID=$userID";
mysql_query($updatesql, $bd) or die(mysql_error());
?>
$bd is my MySQL connection details from config.php.
UPDATE:
I've added <div id="passsubmit2">123</div> to my page and changed the jquery to:
$(function(){
$("#passsubmit2").click(function(){
And it works perfectly, so it's only when using the form button that it doesn't work?
Figured it out eventually.
I needed to add event.preventDefault(); to prevent the normal form submit from firing.
Since you are sending form data to your server through an Ajax request, you dont need that input of submit type at first place, because this will try to submit the form on click and you will have to write additional code for stopping the default functionality of that submit button. So replace that submit button with simple html button or a link.
change your data inside ajax to
if(hasError == false) {
$.ajax({
type: "POST",
url: "resource/changepassword.php",
data: {
newpass : newpass,
},
success: function(){}
});
};
because you are not sent the data to server and info variable not declared
Make sure to pass all the required data to the PHP server. Right now, from what I can see, you are passing an empty variable.
info={
newpass : newpass,
checkVal: checkVal
};
$.ajax({
type: "POST",
url: "resource/changepassword.php",
data: info,
success: function(response){
console.log(response);
}
});
On the PHP side:
<?php
$newPassword=$_POST['newpass '];
EDIT: Going a bit further with this, you really want to store a user ID (unique numeric ID) in the session rather then the username. Referencing through-out your mysql DB using the username as a unique value is a very poor idea (trust me, I made the same mistake).
Also, you should require users to enter their old password whenever changing a current password (what if they left the website up on their computer).
Related
I have a php file that has jquery ajax on it to submit a form and save its contents into a mysql without doing a page refresh.
My issue is if I load the file that the ajax call does the contents are saved into the database however if I try to use the form nothing gets saved to the database even though I get a success message.
Here is my code
The HTML file
<div id='backinstock-form'>
<form>
<input id='instockemailadr'>
<input id='instockpid' value='5' type='hidden'>
<input name='submit' class='submitbackinstock' type='button' value='Submit'>
</form>
<span class='error' style='display:none'> Please Enter A Valid Email</span>
<span class='success' style='display:none'> Email Submitted Success</span>
</div>
require(['jquery'], function($)
{
$(".submitbackinstock").click(function()
{
var instockemailadr = $("#instockemailadr").val();
var instockpid = $("#instockpid").val();
var dataString = 'usereaddr='+ instockemailadr + '&sku=' + instockpid;
if(instockemailadr =='' || instockpid =='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
//console.log(dataString);
var dataString = new formData();
dataString.append('usereaddr', instockemailadr);
dataString.append('sku',instockpid);
$.ajax({
type: "POST",
url: "<?php echo $block->getBaseUrl(); ?>/pub/media/theme_customization/backin-stock-email-code/backinstock_process_email.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
The PHP File
<?php
// MySQL portion
$conn = mysqli_connect("localhost", "root", "root");
mysqli_select_db($conn,"multisitedb");
$usereaddr = mysqli_real_escape_string($conn, $_POST['usereaddr']);
$stockproductid = mysqli_real_escape_string($conn, $_POST['sku']);
$created_on = date('Y-m-d h:i:s');
$result = mysqli_query($conn, "INSERT INTO multisitedb.backinstock_email_addresses(email_addr, product_sku, created_on)
VALUES ('$usereaddr','$stockproductid','$created_on')");
if($result) {
echo $result; // or whatever you want
} else {
echo "Something went wrong.";
}
?>
First, you didn't specify a Database in your php script. The format is mysqli_connect(host, username, password, database);
Secondly, your ajax code seems wrong. You're making a post request. The data should be an instance of formData(). You can modify this way:
var dataString = new formData();
dataString.append('usereaddr', instockemailadr);
dataString.append('sku',instockpid);
//...
data: dataString,
success: function(){
Also, your PHP script is not doing security checks. You need to validate user inputs as well as use prepared statements to prevent against SQL injection attack.
I want to pass a variable to college.php where that variable can be used to fetch data.
I already tried get and post methods using form, but then using get the variable values are visible in address bar and using get form resubmission alert appears
this is what I used.
<form class="morestories"method="get" enctype="multipart/form-data" action="college.php">
<input type="hidden" name="collegename" value="<?php $collegename=$row['name']; echo $collegename; ?>">
<input class="morestoriesbutton" type="submit" name="collegeselectlink" value="More Stories" />
</form>
also the variables i am passing to college.php file, on refresh it should be used again to access data so any possible help
This is a example where I am passing name and password to a php function ,
you can refer this and apply it accordingly to your condition.
$(document).ready(function(){
//this is my button
$("#click").click(function(){
// getting username and password from my html
username = $("#name").val();
password = $("#pad").val();
if(username=="" || password==""){
alert("please check the details");
} else {
$.ajax({ url: 'reverse.php',
data: {username:username,password:password},
type: 'post',
success: function(output) {
alert(output);
}
});
}
});
});
I have a question that's blowing my mind: how do I send a form ID stored in a PHP variable to my AJAX script so the right form gets updated on submit?
My form is a template that loads data from MySQL tables when $_REQUEST['id'] is set. So, my form could contain different data for different rows.
So, if (isset($_REQUEST["eid"]) && $_REQUEST["eid"] > 0) { ... fill the form ... }
The form ID is stored in a PHP variable like this $form_id = $_REQUEST["eid"];
I then want to use the button below to update the form if the user changes anything:
<button type="submit" id="update" class="form-save-button" onclick="update_form();">UPDATE</button>
and the following AJAX sends the data to update.php:
function update_form() {
var dataString = form.serialize() + '&page=update';
$.ajax({
url: 'obt_sp_submit.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: dataString, // serialize form data
cache: 'false',
beforeSend: function() {
alert.fadeOut();
update.html('Updating...'); // change submit button text
},
success: function(response) {
var response_brought = response.indexOf("completed");
if(response_brought != -1)
{
$('#obt_sp').unbind('submit');
alert.html(response).fadeIn(); // fade in response data
$('#obt_sp')[0].reset.click(); // reset form
update.html('UPDATE'); // reset submit button text
}
else
{
$('#obt_sp').unbind('submit');
alert.html(response).fadeIn();
update.html('UPDATE'); // reset submit button text
}
},
error: function(e) {
console.log(e)
}
});
}
I'd like to add the form's id to the dataString like this:
var dataString = form.serialize() + '&id=form_id' + '&page=update';
but I have no idea how. Can someone please help?
The most practical way as stated above already is to harness the use of the input type="hidden" inside a form.
An example of such would be:
<form action="#" method="post" id=""myform">
<input type="hidden" name="eid" value="1">
<input type="submit" value="Edit">
</form>
Letting you run something similar to this with your jQuery:
$('#myform').on('submit', function(){
update_form();
return false;
});
Provided that you send what you need to correctly over the AJAX request (get the input from where you need it etc etc blah blah....)
You could alternatively include it in the data string which; I don't quite see why you would do.. but each to their own.
var dataString = form.serialize() + "&eid=SOME_EID_HERE&page=update";
Sounds like a job for a type=hidden form field:
<input type="hidden" name="eid" value="whatever">
You have to write the string dynamically with PHP:
var dataString = form.serialize() + "&id='<?php echo $REQUEST['eid'] ?>'+&page=update";
On the server you can write Php code on the document, and they will be shown as HTML/JS on the client.
I found a tutorial here : http://tutorialzine.com/2009/08/creating-a-facebook-like-registration-form-with-jquery/ (please take a look)
It's a nice tutorial, I followed everything there and remove extra stuff I don't want , like the functions.php with generate_function option as I am not in need of birthday etc. stuff.
All I want is a NAME(usrname) , EMAIL(email) , Password(password) , when the user click on "REGISTER" button (which is the form submit button), the script I got from the tutorial will send the data over to "regprocess.php" which contains validation check codes like checking if the submitted form data is empty.
But when I click REGISTER , the data is not sent back (the error message) from the "regprocess.php" nor the success message.
When i check with my firebug , the JSON response is showing the full php code like the one below(scroll down).
Here's my code :
HTML-
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript" src="register.js"></script>
<form id="regForm" action="regprocess.php" method="post">
<label for="usrname">Name:</label>
<input id="usrname" name="usrname" type="text" value="" class="nor">
<label for="email">Email:</label>
<input id="email" name="email" type="text" value="" class="nor">
<label for="password">Password:</label>
<input id="password" name="password" type="password" value="" class="nor">
<table><tr><td style="width:290px;"><div id="error"> </div></td><td><input name="register" type="submit" value="Register" id="regbtn"><center><img id="loading" src="images/load.gif" alt="Registering..." /></center></td></tr></table>
</form>
Okay the Ajax script is in "register.js" above.
Ajax script(register.js)-
$(document).ready(function(){
$('#regForm').submit(function(e) {
register();
e.preventDefault();
});
});
function register()
{
hideshow('loading',1);
hideshow('regbtn',0);
error(0);
$.ajax({
type: "POST",
url: "regprocess.php",
data: $('#regForm').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
hideshow('loading',0);
hideshow('regbtn',1);
}
});
}
function hideshow(el,act)
{
if(act) $('#'+el).css('visibility','visible');
else $('#'+el).css('visibility','hidden');
}
function error(act,txt)
{
hideshow('error',act);
if(txt) $('#error').html(txt);
}
CSS:
Regbtn is the submit button , it's visibility is set to visible
loading is set to hidden
error is set to hidden
When a user click on Regbtn , loading visibility will become visible while Regbtn hides(visibility:hidden).
It's done in the Ajax script(register.js).
Okay now the php:
PHP(regprocess.php)-
if(empty($_POST['usrname']) || empty($_POST['email']) || empty($_POST['password']))
{
die('{status:0,"txt":"Fill in All Fields"}');
}
if(!(preg_match("/^[\.A-z0-9_\-\+]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $_POST['email'])))
die('{status:0,"txt":"Please Provide a Valid Email"}');
echo '{status:1,txt:"registered.html"}';
This checks whether the username , email and password data is empty , if yes , returns a message which will be displayed in the Error(#error in html) , it also checks whether email provided is valid.
If everything else is right , user will be directed to registered.html
But i think the script can't get the error message back from the php.
I hope someone can help me. Thanks.
Have a nice day.
hmm not too much of an answer but what I do on my forms is a I submit via ajax and put the result from the php page in the parent of the form.
below is the plugin in code. it works when the form is a child of a div by default.
(function($){
$.fn.extend({
//pass the options variable to the function
ajaxForm: function(options)
{
//Set the default values, use comma to separate the settings, example:
var defaults =
{
target: 'div'
}
var options = $.extend(defaults, options);
return this.each(function()
{
var o=options
$(this).submit(function(event)
{
event.preventDefault();//stop from submiting
//set needed variables
var $form = $(this)
var $div = $form.parent(o.target)
$url = $form.attr("action");
//submit via post and put results in div
$.post( $url, $form.serialize() , function(data)
{ $div.html(data) })
})
});
}
});
})(jQuery);
note this will run for every form so change it as you would wish.
whatever you want to display just echo on the php page. also this is made for post and the php page will access anything just like any other form being with post.
also it wouldn't be hard to modify if you felt necessary to send as json instead.
You need to put php tags around the php code, like this:
<?php
if(empty($_POST['usrname']) || empty($_POST['email']) || empty($_POST['password']))
{
die('{status:0,"txt":"Fill in All Fields"}');
}
if(!(preg_match("/^[\.A-z0-9_\-\+]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $_POST['email'])))
die('{status:0,"txt":"Please Provide a Valid Email"}');
echo '{status:1,txt:"registered.html"}';
?>
I have the following ajax call
$.ajax(
{
type: "POST",
url: "Utilities/CheckUsername.php",
data: "un="+ un,
success: function(data)
{
if(data!=1)
{
$('#mike').html(data);
return false;
}
}
});
I want the page to stay if the username is taken, else redirect to whats in the action attribute of the for.
Obviously this isn't working. But why? I would like to not use preventdefault, so that I could get a better understanding of where the problem and solution is.
EDIT:
The server code
<?php
$seed = 'n48sma94r98';
$email = $_POST['un'];
$mysqli = new mysqli('localhost','uml','uml','uml');
if (!$mysqli)
{
printf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error());
exit;
}
$query = "Select User_Email as Email from user2 where User_Email = AES_ENCRYPT('$email','$seed') ";
$result = $mysqli->query($query);
if($result->num_rows > 0)
{
echo "1";
}
else
{
echo "2";
}
?>
The entire form minus the meta:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Untitled</title>
<link rel="stylesheet" type="text/css" href="my.css">
<script type="text/javascript" src="Resources/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript">$(document).ready(function(){
$("#login").submit(function() {
var un = $('#username').val();
$.ajax(
{
type: "POST",
url: "Utilities/CheckUsername.php",
data: "un="+ un,
success: function(data)
{
if(data!=1)
{
$('#mike').html(data);
return false;
}
}
});
});
});
</script>
</head>
<body>
<form name="login" id="login" method="post" action="dsds.html">
UserName<input type="text" name="username" id="username"value="">
Password<input type="text" name="password" id="password" value="">
Password Again<input type="text" name="passwordagain" id="passwordagain" value="">
<input type="hidden" name="NewClass" id="NewClass" value="true">
<input type="submit" name="submit" id="submit" value="submit">
</form>
<span id = "mike"></span>
</body>
</html>
Some advice. Name your variables and methods. What is 'un' and 'data'? What do they contain?
Also what type of data is returned? String, HTML, XML, JSON?
If you want to redirect you can use window.location = 'someURL';
To send a form you can do this: $('#form-id').submit();
You could return more meaningful messages, like usernameExists,usernameFound or usernameNotExists,usernameNotFound. Even if you are the only one working on this project, when you go around and ask for help, peeps need to understand your code. It should read like sentences.
I suppose you use
if(data!=1)
to see of the username was taken or not?
Did you try to see the value of data using some sort of a debugger? (or even an alert()).
As I suppose you are not sending a 1 from the server when the username is already taken...
I usually use OK as response indicator (or whatever you call that). If the response (your data) starts with OK it's positive, otherwise the entire message is the error:
In Javascript:
success: function(response) {
if ( 'OK' == response.substr(0, 2) ) {
// Okay, so show something green or do nothing
var message = response.substr(2); // Everything after "OK"
}
else {
// Not okay, so show something red or redirect
var goto = response;
// The entire response message `response` is the target destination
// If you don't want PHP to define the redirect location, just hard code it right here
window.location = goto;
}
}
And in PHP:
$result = $mysqli->query($query);
$usernameExists = $result->num_rows > 0; // A nice boolean
exit( $usernameExists ? '/error.html' : 'OKThis username is fine' );
PS. The return false in the success function does nothing. You can omit that.
edit
Without changing the PHP:
success: function(response) {
if ( '1' !== response ) {
window.location = 'error.html';
}
}
Since response is a string, I'd check for that (and not a number). And it never hurts to check for identicallity (===) instead of equality (==).