I am trying to implement a simple form which will eventually connect to a database and make entries in it. In the tag,I am calling the php file which will connect me to the database in the back-end.
index.html
<html>
<head>
<script>
function submitForm(formId){
//var formData= $.(formId).serialize();
$.ajax({
url:'new-user.php',
type:'POST',
data:{
user_name=$("#user_name").val(),
password=$("#password").val();
}
success:function(response){
alert(response);
}
});
}
</script>
</head>
<body>
<form onsubmit="submitForm('#myForm');" id='myForm'>
User Name: <input type="text" name="user_name" id="user_name" />
Password: <input type="text" name="password" id="password" />
<input type="submit"/>
</form>
</body>
</html>
new-user.php
<?php include 'database.php';?>
<?php
mysqli_query($connect,"create table login(User_name varchar(50) NOT NULL,Password varchar(50) NOT NULL)");
$user_name=$_POST['user_name'];
$password=$_POST['password'];
if(empty($user_name)){
$name_error="name is required";
}
mysqli_query($connect,"Insert into login(User_name,Password) values('$user_name','$password')");
if(mysqli_affected_rows($connect)>0){
echo "<p>Credentials added</p>";
echo "<a href='index.html'>Go back</a>";
}else{
echo "<p>Error</p>";
echo mysqli_error($connect);
}
?>
database.php
<?php
$connect=mysqli_connect('localhost','root','','testdb');
if(mysqli_connect_errno($connect)){
echo 'failed to connect';
}
?>
The above is not creating any table in the testdb database.Neither,it is generating any alert messages.The Url however changes after clicking the submit button as http://localhost/try2/?user_name=aayushi&password=ded but after that nothing happens. This is my first php code, so I don't really know what's the meaning of this exactly.
Okay, since no one seems to actually be reading your code, there's a couple of syntax errors that I missed until I threw it into PhpStorm
Change your function to this:
function submitForm(formId){
$.ajax({
url:'/new-user.php',
type:'POST',
data:{
user_name: $("#user_name").val(),
password: $("#password").val()
}
})
.complete(function (response) {
alert(response)
})
return false; // Prevents the form from submitting the standard way
}
EDIT: Change the form to this:
<form onsubmit="return submitForm('#myForm');" id='myForm'>
In your ajax method, the success property is wrong
It is written as suceess, when it was supposed to be success
Also, to avoid refreshing the page, insert return false; at the end of the function submitForm
Related
I have created a chatbot using rivescript and javascript. I want to save the user's messages and chatbot responses to a database.
In html code I have made this form for the messages:
<div id="dialogue"></div>
<form onSubmit="return chatbot.sendMessage()">
<div class="text-box">
<input type="text" name="message" id="message" autocomplete="off" placeholder="Please wait... loading...">
<input class="send-button" type="submit" value=" " id="butsend">
</div>
</form>
</div>
I used a php file named connect.php to connect with the db.
I modified the command:
<form onSubmit = "return chatbot.sendMessage ()"> to
<form onSubmit = "return chatbot.sendMessage ()" method = "POST" "action =" connect.php>
resulting in the user's first message being entered in the database and then a new blank page appearing instead of the dialog.
Ιs there any way to continue the dialogue and at the same time store the data in the database when the send button is pressed?
I have solved the problem using this function:
function writetoDB(inputmessage, outputmessage){
$.ajax({
url: "save.php",
type: "POST",
data: {
user: inputmessage,
botreply: outputmessage,
},
cache: false,
success: function(dataResult){
}
})
}
that calls the php file:
<?php
include 'database.php';
$user=$_POST['user'];
$botreply=$_POST['botreply'];
$sql = "INSERT INTO `dialogs`( `user`, `bot`)
VALUES ('$user','$botreply')";
if (mysqli_query($conn, $sql)) {
echo json_encode(array("statusCode"=>200));
}
else {
echo json_encode(array("statusCode"=>201));
}
mysqli_close($conn);
?>
My problem now is that not all values are imported in database. For example, if there are 20 messages, only 10 are written to the db.
I'm attempting to use ajax to send input from an html form and try to fine the email in a MySQL database. I tested the search and it works just fine (using dummy data.) I have my PHP files running on WAMP. I checked Chrome to see if the email/password are showing and they are.
Here is my code:
HTML & Ajax
<html>
<head>
<!--initialize jquery from js folder-->
<script src ="js/jquery-3.3.1.min.js"></script>
</head>
<body>
<!--output of the json-->
<div>
<!--set the id to DOM to show output-->
<ul id="DOM">
</ul>
</div>
<form>
<label><b>Email</b></label>
<input type="text" placeholder="Enter email" id="email"
required>
<br/>
<label><b>Password</b></label>
<input type="text" placeholder="Enter password" id="passwrd"
required>
<br/>
<button type="button" id="submit">Login</button>
</form>
insert
delete
show data
login
<!--Implementation of jquery/ajax-->
<script type="text/javascript">
$('#submit').on('click',function(e){
e.preventDefault()
var data = {
email: $("#email").val(),
passwrd: $("#passwrd").val()
}
$.ajax({
url : "http://localhost/api/login.php",
type : "POST",
dataType : "json",
data : JSON.stringify(data),
//on success it will call this function
success : function(data){
alert(data.toString());
//if fail it will give this error
}, error : function(e){
alert("failed to work:" +JSON.stringify(e));
}
});
});
</script>
</body>
</html>
PHP
include "db.php";
header('Content-type: application/json');
//$con->escape_string
$email = isset($_POST['email']);
//$email = "fk5829#wayne.edu";
$result = $con->query("SELECT * FROM users WHERE email='$email'");
echo "$email";
if($result->num_rows == 0){ //if the user doesnt exist
$_SESSION['message'] = "user doesnt exist";
echo ' / user not exist / ';
}
else{ //user exists
$user = $result->fetch_assoc();
if(password_verify(isset($_POST['passwrd']), $user['passwrd'])){
//Verify the password entered
//if password correct, link information from DB to session
//variables
$_SESSION['f_name']= $user['f_name'];
$_SESSION['l_name']= $user['l_name'];
$_SESSION['email']= $user['email'];
$_SESSION['authorized']= $user['authorized'];
//Will be used to check if users session is logged
//in/allowed to do things
$_SESSION['logged_in'] = true;
//return to Success
return $_SESSION['logged_in'];
exit("Success");
}
else{
$_SESSION['message'] = "You have entered the wrong password,
please try again";
}
echo ' / user exists / ';
}
echo ' / After the check / ';
My question is this: Why is the email from the form id "email" not getting stored in $email? is it on my ajax request side? or is it in my PHP file when im trying to $_POST?
Any direction is appreciated.
I tried this function and got it to work. Maybe you can try this too.
<script type="text/javascript">
$('#submit').on('click',function(e){
e.preventDefault()
$.post('http://localhost/api/login.php', {email:$("#email").val(),passwrd:$("#passwrd").val()},
function(data){
alert(data.toString());
}).fail(function(e){
alert("failed to work:" +JSON.stringify(e));
});
});
</script>
I need to be able to send a JavaScript variable to a PHP function. I was able to get it working for hard-coded values such as the code below.
<button onclick="submitform()">Click me</button>
<script>
function submitform(){
document.write(' <?php send_mail('hello'); ?> ');
}
</script>
<?php
function send_mail($subject){
//$subject => 'hello'
//Do something with subject
}
?>
However, I cannot replace the hard-coded value with a variable. I would also like to find another way to issue the PHP function call. I believe the solution lies in an ajax request. I cannot find a way to do this with the PHP code directly embedded as it is now. All of the other examples I cannot get to work. If possible, I would appreciate a demo as well. Thanks!
You can do it using forms:
<form action="send_mail.php" method="post">
<input type="text" id="mail" name = "mail">
<input type="submit" class="btn" value="Send Mail">
</form>
Then you can access the mail using $_POST["mail"] from the send_mail.php page
Another way to do it is ajax:
$.ajax({ url: '/send_mail.php',
data: {action: 'sendEmail', mymail:$('#mail').val()},
type: 'post',
success: function(output) {
alert(output);
}
});
Then in the send_mail.php page you can do:
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
$mail = $_POST['mymail'];
switch($action) {
case 'sendEmail' : send_email();break;
// ...etc...
}
}
Demo for same page call:
<?php
if(isset($_GET['action'])=='myfunc') {
echo "Hello";
}
?>
<form action="?action=myfunc" method="post">
<input type="text" id="mail" name = "mail">
<input id="clickMe" type="submit" value="clickme"/>
I build a link shortener,just for fun!
Everything works, but everytime I create a link and submit the form, the page reloads! I wanted to prevent that with onclick="return false;"but it didnt work.
<input class="submit" type="submit" value="Create!" />
$('#contactForm').submit(function () {
sendContactForm();
return false;
});
But nothing works, the file is just stuck and doesn't do anything! What am I doing from ? This is the problem page https://viid.su
PHP
require("db_config.php");
$uid = 1;
$flink = $_POST['url'];
if(!preg_match("/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i", $flink)) {
$html = "Error: invalid URL";
} else {
$db = mysqli_connect($host, $username, $password);
$conn = new mysqli($host, $username, $password, $database);
$id = substr(md5(time().$flink), 0, 5);
if($conn->query("INSERT INTO `".$database."`.`link` (`id`, `flink`,`adonly`,`userid`) VALUES ('".$id."', '".$flink."','true','".$uid."');")) {
$html = 'Your short URL is <a class="test" href="https://viid.su/'.$id.'">https://viid.su/'.$id.'</a>';
} else {
$html = "Error: cannot find database";
}
mysqli_close($db);
}
You can submit a form without reloading the page by using something like an AJAX call.
JavaScript
$('#contactForm').submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "path/to/your/script.php",
data: $('#contactForm').serialize(), // Packs the form's elements
success: function(data)
{
// Do something here if the call succeeded
alert(data);
}
});
}
HTML
<form id="contactForm">
<input type="text" name="username" />
<input type="text" name="email" />
<input type="submit" value="Submit form" />
</form>
PHP
<?php
echo $_POST['username'];
?>
Something along those lines should work, and you don't need anything else, as you are already using jQuery.
you need to use event object as parameter in function callback and call event.preventDefault()
Just change the <input type="submit" /> into something like <button onclick="return false;" id="shortenLinkButton">Send</button>
Then with jQuery you can catch the even like this:
// This code will be usable after the page has fully loaded
$(document).ready(function(){
// Catch the onclick event
$('#shortenLinkButton').on('click', function() {
// do something
alert('clicked the button, do your ajax stuff here after retrieving the data from the input');
});
});
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
...
...
<form id="validate_mail" action="/wp-content/custom-php/validate_mail.php" method="POST">
<input name="mail_name" type="text" value="" />
<input type="submit" value="submit" />
</form>
<div id="validate_mail_result"></div> // placeholder for html code that is returned
<script> // main script
var form=$('#validate_mail');
form.submit(function(ev){
$.ajax({
type : form.attr('method'),
url : form.attr('action'),
data : form.serialize(),
success : function(result{
$('#validate_mail_result').html(result);
}
});
ev.preventDefault();
});
</script>
PHP (which is called by the main script)
<?php
...
...
// Connect to MySQL
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$connection = new mysqli($servername,$username,$password);
if (mysqli_connect_errno()){
printf("MyErrorMsg: %s\n", mysqli_connect_error());
exit();
}
// Perform request
$mail_name = $_POST[mail_name];
$full_mail_name = $mail_name . "#mydomain.me";
$connection->select_db("MAILSERVER");
$queryMailExists = "SELECT id FROM users WHERE mailname = '" . $mail_name . "'";
$resultMailExists = $connection->query($queryMailExists);
$row_cnt = $resultMailExists->num_rows;
$connection->close();
if (is_valid_email_address_5321($full_mail_name)==0){
echo "Not a valid email-address according to RFC5321";
}elseif(row_cnt==0){ //check if email name allready taken
echo "Mail available";
echo "
<form id=\"purchase_mail\" action=\"/wp-content/custom-php/purchase_mail.php\" method=\"POST\">
<input id=\"password\" style=\"width: 280px;\" name=\"password\" type=\"password\" value=\"\" />
<div id=pswrd_struct_chk></div>
<input id=\"password_retyped\" style=\"width: 280px;\" name=\"password_retyped\" type=\"password\" value=\"\" />
<div id=pswrd_match_chk></div>
<script> // this script and the one after this are blocking the main script
var form=$('#purchase_mail');
$('#password').keyup(function(ev){
$.ajax({
type : form.attr('method'),
url : \"/wp-content/custom-php/password_structure_check.php\",//just checks if the password strength is weak/acceptable/good
data : form.serialize(),
success : function(result){
$('#pswrd_struct_chk').html(result);
}
});
$('#password_retyped').val(\"\");
$('#pswrd_match_chk').html(\"\");
});
</script>
<script>
var form=$('#purchase_mail');
$('#password_retyped').keyup(function(ev){
$.ajax({
type : form.attr('method'),
url : \"/wp-content/custom-php/password_match_check.php\",
data : form.serialize(),
success : function(result){
$('#pswrd_match_chk').html(result);
}
});
});
</script>
<input type=\"submit\" value=\"PAY\" />
";
}else{
echo "<div>Mailname allready taken!</div>";
}
?>
When i comment out the two last scripts everything works as intended. The 3 different if-cases in the PHP do echo their html codes into the placeholder but when i leave the scripts uncommented once the "elseif(row_cnt==0)" section is executed the main script gets stuck and i do not get any echo for the other two if-cases no matter what is submited (enterd in the input field with the id=mail_name).
I was not able to google my problem.
Thanks for your time end effort.
AJAX does not allow script tags to be passed in the results when type is HTML. Supposing that you somehow manage to pass the scripts, you will still have to retrigger the script which is somewhat bothersome.
I would suggest you to write the html adding code in the success message and passing on the variables such as form action, URLs, etc from PHP. This way you won't face those issues and you will also be able to get the job done.
I checked your code. You can try doing something like:
First AJAX:
$.ajax({
//logic for the first ajax
}).done(function(){
//**second ajax**
})
First of all you should follow the rule:
in php script - just php code, no js and css; in js script - just js, no css.**
It not just a good style, it will help you to facilitate your work!
I just move your html and js from validate_mail.php to main page, and it looks like:
<html>
<head></head>
<body>
<form id="validate_mail" action="/wp-content/custom-php/validate_mail.php" method="POST">
<input name="mail_name" type="text" value="" />
<input id="btn_validate_mail" type="button" value="submit" />
</form>
<div id="validate_mail_result1" style="display: none;">Not a valid email-address according to RFC5321</div>
<div id="validate_mail_result2" style="display: none;">
Mail available
<form id="purchase_mail" action="/wp-content/custom-php/purchase_mail.php" method="POST">
<input id="password" style="width: 280px;" name="password" type="password" value="" />
<div id="pswrd_struct_chk"></div>
<input id="password_retyped" style="width: 280px;" name="password_retyped" type="password" value="" />
<div id="pswrd_match_chk"></div>
</form>
</div>
<div id="validate_mail_result3" style="display: none;">Mailname allready taken!</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$('#btn_validate_mail').click(function () {
var form = $('#validate_mail');
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (result) {
$('#validate_mail_result'+result).show();
},
error: function (xhr, status, error) {
// If you will receive any errors - you will see it here.
console.log(error);
},
complete: function () {
form.hide();
}
});
});
$('#password').keyup(function(ev){
var form=$('#purchase_mail');
$.ajax({
type : form.attr('method'),
url : "/wp-content/custom-php/password_structure_check.php",//just checks if the password strength is weak/acceptable/good
data : form.serialize(),
success : function(result){
$('#pswrd_struct_chk').html(result);
}
});
$('#password_retyped').val("");
$('#pswrd_match_chk').html("");
});
$('#password_retyped').keyup(function(ev){
var form=$('#purchase_mail');
$.ajax({
type : form.attr('method'),
url : "/wp-content/custom-php/password_match_check.php",
data : form.serialize(),
success : function(result){
$('#pswrd_match_chk').html(result);
}
});
});
</script>
</html>
It looks much better, but still terrible. And js don't should be here, and css too.
Now validate_mail.php looks:
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$connection = new mysqli($servername,$username,$password);
if (mysqli_connect_errno()){
printf("MyErrorMsg: %s\n", mysqli_connect_error());
exit();
}
// Perform request
$mail_name = $_POST['mail_name'];
$full_mail_name = $mail_name . "#mydomain.me";
$connection->select_db("MAILSERVER");
$queryMailExists = "SELECT id FROM users2 WHERE mailname = '" . $mail_name . "'";
$resultMailExists = $connection->query($queryMailExists);
$row_cnt = $resultMailExists->num_rows;
$connection->close();
if (is_valid_email_address_5321($full_mail_name)==0){
echo 1;
}elseif($row_cnt==0){ //check if email name allready taken
echo 2;
}else{
echo 3;
}
So much easier...
I don't want talk about xss, sql injections and else, because your question not about it, but you should remember about it.
You need to continue separate js and html and css...
I just try to show how it can be much easier to reach what you need... hope it will be helpful...
Good news. You just had typos in your code. I ran the relevant parts on a local server and your scripts are executing as expected. Enjoy!
HTML
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<form id="validate_mail" action="validate_mail.php" method="POST">
<input name="mail_name" type="text" value="" />
<input type="submit" value="submit" />
</form>
<div id="validate_mail_result"></div>
<script> // main script
var form = $('#validate_mail');
form.submit(function(ev){
$.ajax({
type : form.attr('method'),
url : form.attr('action'),
data : form.serialize(),
// success : function(result{ <-- typo
success : function(result){
$('#validate_mail_result').html(result);
}
});
ev.preventDefault();
});
</script>
</body>
</html>
PHP - validate_mail.php
<?php
// }elseif(row_cnt==0){ <-- typos here too, maybe more above, didn't check
// }else if($row_cnt == 0){
echo "Mail available";
echo "
<form id=\"purchase_mail\" action=\"/wp-content/custom-php/purchase_mail.php\" method=\"POST\">
<input id=\"password\" style=\"width: 280px;\" name=\"password\" type=\"password\" value=\"\" />
<div id=pswrd_struct_chk></div>
<input id=\"password_retyped\" style=\"width: 280px;\" name=\"password_retyped\" type=\"password\" value=\"\" />
<div id=pswrd_match_chk></div>
<script> // this script and the one after this are blocking the main script
var form=$('#purchase_mail');
$('#password').keyup(function(ev){
$.ajax({
type : form.attr('method'),
url : \"/wp-content/custom-php/password_structure_check.php\",//just checks if the password strength is weak/acceptable/good
data : form.serialize(),
success : function(result){
$('#pswrd_struct_chk').html(result);
}
});
$('#password_retyped').val(\"\");
$('#pswrd_match_chk').html(\"\");
});
</script>
<script>
var form=$('#purchase_mail');
$('#password_retyped').keyup(function(ev){
$.ajax({
type : form.attr('method'),
url : \"/wp-content/custom-php/password_match_check.php\",
data : form.serialize(),
success : function(result){
$('#pswrd_match_chk').html(result);
}
});
});
</script>
<input type=\"submit\" value=\"PAY\" />
";
//}else{
// echo "<div>Mailname allready taken!</div>";
//}
?>
Ignoring the already-mentioned errors here (invalid HTML, invalid PHP, etc.), your easiest (and best) solution to this is simply to refactor your code so it doesn't return the HTML/JS. Just put all of the HTML/JS that is currently being returned by the PHP into your page and hide it. Have the PHP return a status code of some sort ("invalid-email"/"ok"/"taken", etc.) and have jQuery hide/unhide the appropriate response on the page. This keeps a separation of concerns between your presentation and your business logic.
If you are using jQuery version 1.7 and above
Change
var form=$('#validate_mail');
form.submit(function(ev){
$.ajax({
To:
var $(document).on('submit','#validate_mail',function(ev){
$.ajax({
Also try and keep your JQuery scripts together maybe in a main.js file and definitely outside and away from your PHP. So you should write the JS for the #purchase_mail directly under your #validate_mail submit function in the same way as I described and it will work when you ajax your form into the page.
The script you are pulling in with Ajax will not work unless you evaluate eval() it somehow but doing that will open your script up to potential security vulnerabilities.
Hope that helps dude