How to check if a username is already taken with ajax and sql? - javascript

i'm trying to check if a username exists in the db with ajax. I don't know why it doesn't work i tried many things and still get nothing.
this is the code that i'm actually trying. the php code works but doesn't send the result to the ajax function
html >Registration.php
<input class="form-control" onblur="checkUser()" id="Pseudo" type="text name="Pseudo" value="" required>"
<span id="availability" name="availability" value=""> </span>
php >Welcome.php
if(!empty($_POST['Pseudo']))
{
$pseudo = $_POST['Pseudo'];
$connexion = mysqli_connect('localhost', 'root', '', 'database');
if(!$connexion)
{
die('Error during connexion ');
}
$sql = "SELECT * FROM Web_database WHERE Pseudo='$pseudo'";
$result = mysqli_query($connexion, $sql);
echo mysqli_num_rows($result);
}
Javascript > Registration.php
function checkUser()
{
var Pseudo = $('#Pseudo').val();
$.ajax({
url:'Welcome.php',
method:"POST",
data:{Pseudo:Pseudo},
success:function(data)
{
if(data == '0')
{
$('#availability').html('Pseudo correcte');
}
else
{
$('#availability').html('Pseudo déja utilisé');
}
}
});
}

First of all, you can probably optimize your SQL:
$sql = "SELECT COUNT(*) FROM Web_database WHERE Pseudo='$pseudo'"
Instead of using mysqli_num_rows().
You are also opening yourself up to SQL injection unless you use prepared statements.
As for your AJAX, it doesn't seem to be wrong. I found this question to be very similar so you might want to check that out. When in doubt, console.log() the response from PHP to see what's actually being returned. Or better yet, add a breakpoint.

Related

Can't insert into database an autofill fields?

it's my first time asking here,
I've been trying to look for something similar in other questions asked, and couldn't find it.
I have a form with Zip code line(textbox) and State line(textbox),
now, the stateboxes are auto-filled by a javascript by entering a valid US zip code.
the form itself is a bit longer.
I only show the relevant code that has been edited by me,
It was a select menu before (and everything worked just fine - data was entered into databse), and I changed it, so no select will be needed.
There is also css file, but it's irrelevant (designing isn't the issue)
So, here is my html code :
<html>
<head>some content here</head>
<body>
<form method="post" action="process.php">
<div class="title"><h2>my form title</h2></div><br>
<div align="center" class="element-name">
</span>
<span align="center" id="zipbox" class="nameFirst">
<input type="text" class="medium" pattern="[0-9]*" name="col2" id="col2" maxlength="5" placeholder="Type your ZIP code" onkeypress='validate(event)'required/>
</span>
<span align="center" id="zipbox2" class="nameLast">
<input type="text" class="medium" pattern="[0-9]*" name="col4" id="col4" maxlength="5" placeholder="Type your ZIP code" onkeypress='validate(event)'required/>
</span></div>
<div align="center" class="element-name">
<span class="required"></span>
<span align="center" id="statebox" class="nameFirst">
<input type="text" class="medium" name="col1" id="col1" placeholder="" required />
<label class="subtitle">From</label>
</span>
<span align="center" id="statebox2" class="nameLast">
<input type="text" class="medium" name="col3" id="col3" placeholder="" required />
<label class="subtitle">To</label>
</span></div>
<p align="center"><input type="reset" value="Clear"></p>
</body>
</html>
some javescript !
<script src="//code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(document).ready(function() {
$("#col2").keyup(function() {
var el = $(this);
if (el.val().length === 5) {
$.ajax({
url: "http://zip.elevenbasetwo.com",
cache: false,
dataType: "json",
type: "GET",
data: "zip=" + el.val(),
success: function(result, success) {
$("#city").val(result.city);
$("#col1").val(result.state);
}
});
}
});
});
</script>
<script>
$(document).ready(function() {
$("#col4").keyup(function() {
var el = $(this);
if (el.val().length === 5) {
$.ajax({
url: "http://zip.elevenbasetwo.com",
cache: false,
dataType: "json",
type: "GET",
data: "zip=" + el.val(),
success: function(result, success) {
$("#city2").val(result.city);
$("#col3").val(result.state);
}
});
}
});
});
</script>
and php code to process the form :
- it's 13 columns, but i know for sure that the other values are correct.
- col0 represent the date.
<?php
require_once('recaptchalib.php');
$privatekey = "mycaptchakey";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
$process = FALSE;
} else {
// Your code here to handle a successful verification // Your code here to handle a successful verification
}
define('CONST_SERVER_TIMEZONE', 'EDT');
define('CONST_SERVER_DATEFORMAT', 'YmdHis');
$current_date = date("Y-m-d H:i:s");
$col0 = $_POST['col0'];
$col1 = strtoupper($_POST['col1']);
$col2 = strtoupper($_POST['col2']);
$col3 = strtoupper($_POST['col3']);
$col4 = strtoupper($_POST['col4']);
if ( isset($col1) && isset($col2) isset($col3) && isset($col4) && $error == FALSE ) {
$process = TRUE;
} else {
$process = FALSE;
}
$mode = "mysql";{
define ('DB_USER', 'uname');
define ('DB_PASSWORD', 'pass');
define ('DB_HOST', 'host');
define ('DB_NAME', 'dbname');
$dbc = #mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) or die('Failure: ' . mysql_error() );
mysql_select_db(DB_NAME) or die ('Could not select database: ' . mysql_error() );
$query = "INSERT INTO mytable VALUES ('$current_date','$col1','$col2','$col3','$col4')";
$q = mysql_query($query);
if (!$q) {
exit("<p>MySQL Insertion failure.</p>");
} else {
mysql_close();
//for testing only
//echo "<p>MySQL Insertion Successful</p>";
}}
header( 'Location: http://mywebsite.com/index.php' );
?>
i'm not sure if i'm doing it right but here is my
mytable structure :
1 - sid - int(11) AUTO_INCREMENT
2 - col0 - date
3 - col1 - text utf8_unicode_ci
4 - col2 - text utf8_unicode_ci
5 - col3 - text utf8_unicode_ci
6 - col4 - text utf8_unicode_ci
and so on up to 12 columons.
Help please ! what is going wrong here ?
EDIT :
Thank you very much r3wt for the usefull information,
there is a lot to fix especially when it comes to the php part of it :)
ok, so i was able to fix the insertion.
i missed a critical value -
$query = "INSERT INTO mytable VALUES ('$current_date','$col1','$col2','$col3','$col4')";
should have been:
$query = "INSERT INTO mytable VALUES ('','$current_date','$col1','$col2','$col3','$col4')";
that's is because all this form info is going into a phpGrid table
and i had a hidden column 'sid' which is automatically beeing filled.
I promise that in the next time I will be prepare with some more knowledge :)
thanks again.
This waits until a second has past after they have finished typing in the element, then submits the ajax request.
$(function(){
$("#col4").keyup(function() {
var col4val = $(this).val();
clearTimeout(timer);
timer = setTimeout(function(){fillLocation(col4val)}, 1000);
});
var timer = null;
function fillLocation(value){
$.get('http://zip.elevenbasetwo.com', {zip: value} , function(data){
var result = JSON.parse(data);
$("#city2").val(result.city);
$("#col3").val(result.state);
});
}
});
also, your php code is considered to be woefully insecure because you are using mysql.
also, i just noticed a glaring error, you are missing and and operator between $col2 isset and $col3, check your ajax i guarantee you it is returning 500 internal server error:
if ( isset($col1) && isset($col2) isset($col3) && isset($col4) && $error == FALSE ) {
$process = TRUE;
} else {
$process = FALSE;
}
also, your query is wrong. its obvious you are just copy and pasting things together here. go read the mysql manual on INSERT statements and go read up on the mysqli and pdo extensions for php.
A valid mysql statement looks like:
INSERT INTO mytable (column1,column2,column3) VALUES ('val1','val2','val3')
realizing this, you could construct the statement in php like so
$query = mysql_query("INSERT INTO mytable (column1,column2,column3) VALUES ('".$val1."','".$val2."','".$val3."')");
if you continue to use mysql you will get your site hacked, its just a matter of time, especially since you don't sanitize any of your data. please make the smart choice and use mysqli or pdo to interface with the database from php.
As per the request of Dikei, i'm going to introduce you briefly to prepared statements with mysqli so that you may learn to use safe methods for interacting with the database.
$mysqli = new mysqli('host','username','password','databasename');
$mysqli->set_charset("utf8");
$stmt = $mysqli->prepare("INSERT INTO mytable (column1,column2,column3) VALUES (?,?,?)");//bind your variables in the same order!
//s for a string, d for a double floating point integer, and i for unsigned int.
$stmt->bind_param('sss',$col1,$col2,$col3);
if($stmt->execute()) {
$row = $stmt->insert_id ?: null;
if(!empty($row))
{
//query success
}else{
//query failure
}
$stmt->close();
}
$mysqli->close();
if you need more info, i provided a broader example of working with mysqli using the Object Oriented approach here(its in part two of the answer): login session destroyed after refresh

Creating a unique variable for data

Hi guys so i have created a simple comment box for my site now. It works perfectly, however the problem i am having is that i have different pages which are going to require different comment box. I cant seem to figure out how to get the comment box to be unique for every page. So right now my database holds this :
Called comments:
id
comment
comment1
comment_date
Now my idea is that everything was stored into comment, so i added comment1 for other page to store the info. However i have no clue how to edit the php file to get it to work with comment1. Any help on this would be great.
HTML:
<div class="comment_container">
<div class="comments">
<?php
include_once("comments.php");
?>
</div>
<div class="comments_form">
<table>
<tr><td><textarea id="comment_text"></textarea></td>
<td><input type="button" id="comment_process" value="Post Comment"/></td></tr>
</table>
</div>
</div>
JS:
$(document).ready(function() {
$('#comment_process').click(function() {
if ($('#comment_text').val() != "") {
$.post("comments.php?action=post", {
comment: $('#comment_text').val()
}, function(data) {
$('.comments').html(data);
$('#comment_text').val("");
});
}
});
});
PHP:
include_once("connect.php");
function convert ($date) {
$converteddate = date("F j, Y g:ia", strtotime($date." +1day"));
return $converteddate;
}
function getComments(){
$comments = "";
$sql = mysql_query("SELECT * FROM comments") or die(mysql_error());
if(mysql_num_rows($sql) == 0){
$comments = "<div class='each_comment'>There are no comments</div>";
} else {
while($row = mysql_fetch_assoc($sql)){
$comments .= "<div class='each_comment'><small><em>".convert($row['comment_date'])."</em></small><br />".$row['comment']."</div>";
}
}
return $comments;
}
function postComments($comment){
$comment = mysql_real_escape_string(strip_tags($comment));
$sql = mysql_query("INSERT INTO comments (comment, comment_date ) VALUES ('".$comment."', now())");
return true;
}
if((isset($_GET['action'])) && ($_GET['action']== "post")){
postComments($_POST['comment']);
}
echo getComments();
Thanks again for the help
DISCLAIMER
For future visitors:
Don't copy this code, as it has several issues that go beyond answering the question.
What you need to add is an identifyer for the type of comment. (Type could be replaced with something more suitable to your case like 'product', 'user', ... whatever the difference is/what they are related to)
So in your database add that new column:
comments
--------
id
comment
type
comment_date
Now you need to pass around that type through all your calls, and it shall be specified in your 'HTML'-Page (which actually is php...).
<div class="comment_container">
<div class="comments">
<?php
// specify the type needed on that page
$type = 1;
include_once("comments.php");
echo getComments($type);
?>
</div>
<div class="comments_form">
<table>
<tr><td><textarea id="comment_text"></textarea></td>
<td><input type="button" id="comment_process" value="Post Comment"/></td></tr>
</table>
</div>
</div>
<script>
// specify the type in javascript
var type=1;
$(document).ready(function() {
$('#comment_process').click(function() {
if ($('#comment_text').val() != "") {
// add the type here:
$.post("comments.php", {
comment: $('#comment_text').val(),
type: type,
action: 'post'
}, function(data) {
$('.comments').html(data);
$('#comment_text').val("");
});
}
});
});
</script>
and in comments.php:
//....some code left out here
function getComments($type){
$comments = "";
$sql = mysql_query("SELECT * FROM comments where type=$type") or die(mysql_error());
if(mysql_num_rows($sql) == 0){
$comments = "<div class='each_comment'>There are no comments</div>";
} else {
while($row = mysql_fetch_assoc($sql)){
$comments .= "<div class='each_comment'><small><em>".convert($row['comment_date'])."</em></small><br />".$row['comment']."</div>";
}
}
return $comments;
}
function postComments($comment, $type){
$comment = mysql_real_escape_string(strip_tags($comment));
$sql = mysql_query("INSERT INTO comments (comment, comment_date, type ) VALUES ('".$comment."', now(), ".$type.")");
return true;
}
if((isset($_POST['action'])) && ($_POST['action']== "post")){
postComments($_POST['comment'], $_POST['type']);
// send all the comments back to client
echo getComments($_POST['type']);
}
// moved to html-file: echo getComments($type);
NOTE
There are several issues with that code.
First don't use mysql functions. For real. Unsecure and deprecated/deleted as of php7. Use mysqli or pdo. Furthermore your sql can be hacked with sql injection. Read about prepared statements.
The general structure of that code is not very good.
Try to seperate output and formating from getting data.
For example it would be much better if a function called 'getComments' only would get the comments from the database, then let others decide what to do with that data. The less one function does the better.
Please read about coding styles, maybe start learning object oriented programming.
I hope this still helps you to get a clue of where to go!

Using AJAX to send form information to another page using a button

Hello I have two files that are supposed to be connected to one another. I want to send an AJAX request to another page that uses a sql query to send form information.
The application that I'm trying to create is a questionnaire with eight questions, each questions has four answers paired together with the same id (qid) and each answer has a value from the database. After you answer eight questions you will see a button that sends an AJAX request to the page test.php, (named submitAJAX).
The problem is that although my connection with AJAX is working, the values from the form are not being sent to my database. Previously I thought that the problem may lie with the form page, but now I I think the problem lies in this file:
test.php (file with json)
<?php
$localhost = "localhost";
$username = "root";
$password = "";
$connect = mysqli_connect($localhost, $username, $password) or die ("Kunde inte koppla");
mysqli_select_db($connect, 'wildfire');
if(count($_GET) > 0){
$answerPoint = intval($_GET['radiobtn']);
$qid = intval($_GET['qid']);
$tid = intval($_GET['tid']);
$sql2 = "INSERT INTO result (qid, points, tid) VALUES ($qid, $answerPoint, $tid)";
$connect->query($sql2);
$lastid = $connect->insert_id;
if($lastid>0) {
echo json_encode(array('status'=>1));
}
else{
echo json_encode(array('status'=>0));
}
}
?>
I think that the problem may lie in the row where: if($lastid>0) {
$lastid should always be more than 0, but whenever I check test.php I get this message: {"status":0} What's intended is that I get this message: {"status":1}
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<?php
$localhost = "localhost";
$username = "root";
$password = "";
$connect = mysqli_connect($localhost, $username, $password) or die ("Kunde inte koppla");
mysqli_select_db($connect, 'wildfire');
$qid = 1;
if(count($_POST) > 0){
$qid = intval($_POST['qid'])+1;
}
?>
<form method="post" action="">
<input type="hidden" name="qid" id="qid" value="<?=$qid?>">
<?php
$sql1 = mysqli_query($connect,"SELECT * FROM question where answer != '' && qid =".intval($qid));
while($row1=mysqli_fetch_assoc($sql1)){
?>
<input type='radio' name='answer1' class="radiobtn" value="<?php echo $row1['Point'];?>">
<input type='hidden' name='tid' class="tid" value="<?php echo $row1['tid'];?>">
<?php echo $row1['answer'];?><br>
<?php
}
?>
<?php if ($qid <= 8) { ?>
<button type="button" onclick="history.back();">Tillbaka</button>
<button type="submit">Nästa</button>
<?php } else { ?>
<button id="submitAjax" type="submit">Avsluta provet</button>
<?php } ?>
</form>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
function goBack() {
window.history.go(-1);
}
$(document).ready(function(){
$("#submitAjax").click(function(){
if($('.radiobtn').is(':checked')) {
var radiobtn = $('.radiobtn:checked').val();
var qid = $('#qid').val();
var answer = $('input[name=answer1]:radio').val();
$.ajax(
{
type: "GET",
url: 'test.php',
dataType: "json",
data: "radiobtn="+radiobtn+"&qid="+qid,
success: function (response) {
if(response.status == true){
alert('points added');
}
else{
alert('points not added');
}
}
});
return false;
}
});
});
</script>
</body>
The values that I want to send to my database from test.php are:
qid(int), tid(int), Point(int)
There is a database connection, and my test.php file's sql query should work, but its not sending form information. Is there something that I need to rewrite or fix to make it work?
First, your data parameter in the AJAX call is not using the correct syntax. You're missing brackets. It should look like:
data: JSON.stringify({ radiobtn: radiobtn, qid: qid }),
Second, I'd suggest using POST instead of GET:
type: "POST",
which means that you need to look for your data in $_POST['radiobtn'] and $_POST['qid'] on test.php. NOTE: you should check for the key you expect using isset() before assigning the value to a variable, like so:
$myBtn = isset($_POST['radiobtn']) ? $_POST['radiobtn'] : null;
Third, for testing, use a console.log() inside your condition that checks for the checkbox being checked in order to verify that condition is working as expected.
if($('.radiobtn').is(':checked')) {
console.log('here');
UPDATE:
Fourth: You should specify the content type in your AJAX call, like so:
contentType: "application/json; charset=utf-8",
After you execute your query that inserts the result you can use a sql statement to select the last insert id. Try something like
$sql2 = "INSERT INTO result (qid, points, tid) VALUES ($qid, $answerPoint, $tid)";
$connect->query($sql2);
$result = $connect->query("SELECT LAST_INSERT_ID()");
$row = $result->fetch_row();
$lastid = $row[0];
That should return the correct last insert id, if that was where your error was occurring.
mysqli_insert_id() returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute.
In your SQL, you are providing the ID yourself, there is no auto-increment. So you should get 0 from $connect->insert_id, because the function returns zero if there was no previous query on the connection or if the query did not update an AUTO_INCREMENT value.
For your purpose, you can use the return value of mysqli_query() instead, which returns TRUE on success and FALSE on failure.
if($connect->query($sql2)) {
echo json_encode(array('status'=>1));
}
else{
echo json_encode(array('status'=>0));
}

Outputting SQL queries with Javascript, PHP and AJAX

I'm trying to have a form, which when submitted returns the output from a simple SQL query onto the page without needing to be reloaded (AJAX). I can get simple outputs to work but when I use the PHP for the SQL query nothing is returned. Any help would be much appreciated. I also can't find anyway to check what is wrong with my Javascript/Php.
Pretty new to web development so apologies if this is trivial. All previously found solutions haven't worked
My Code;
a1.php
<script src='../js/scriptget.js'></script>
<form>
<fieldset>
<legend>Login</legend>
Username:<br>
<input type="text" name="myusername" placeholder="Username">
<br>
Password:<br>
<input type="text" name="mypassword" placeholder="Password">
<br><br>
<input type="submit" value="Submit" onclick='return getAccount();'>
</fieldset>
</form>
scriptget.js
function getAccount(){
var phpOut = $.ajax({
type: 'GET',
url: 'submitInjection.php',
data: 'myusername=billsmith&mypassword=password'
});
drawOutput('hello');
return false;
}
function drawOutput(responseText){
var container = document.getElementById('output2');
container.innerHTML = responseText;
}
submitinjection.php
<?php
$host="localhost"; //Host Name
$username="root"; // MySql Username
$password="root"; // Mysql Password
$db_name="Honours2"; //Database Name
$tbl_name="Users"; // Table Name
// Connect to server and select database
$conn = mysql_connect("$host", "$username", "$password") or die("Cannot Connect");
mysql_select_db("$db_name") or die("Cannot select DB");
// User and Password sent from form
$myusername = $_GET['myusername'];
$mypassword = $_GET['mypassword'];
/**
Protect MYSQL INJECTION
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
*/
$sql = "SELECT *
FROM $tbl_name
WHERE username = '$myusername'
AND password = '$mypassword'
";
$result=mysql_query($sql);
/* echo $sql; */
if (!$result){
die('Invalid Query: ' . mysql_error() . $sql);
}
if ($result){
echo($sql);
}
/* var_dump($result); */
while ($row = mysql_fetch_assoc($result)){
echo $row['username'];
echo ": ";
echo $row['balance'];
}
mysql_free_result($result);
$conn->close();
?>
Thanks in advance
You need to process the results of your ajax call in for example a success function. You can also use things like .done() or $.when().then(), check the jQuery manual for that.
A simple example using a success function:
var phpOut = $.ajax({
type: 'GET',
url: 'submitInjection.php',
data: 'myusername=billsmith&mypassword=password',
success: function(data_returned) {
alert(data_returned);
// or
$('#output2').html(data_returned);
}
});
Some additional notes:
Don't use GET to send sensitive information to the server, use POST instead;
Don't store plain-text passwords, salt and hash them;
The mysql_* functions are deprecated, you should switch to mysqli_* or PDO where you can use prepared statements to avoid sql injection, making escaping unnecessary.
You have to add a success callback function to your $.ajax() call. That callback function should call your 'drawOutput' function with response it gets as a parameter. Something like this:
success: function (data) {
drawOutput(data);
}

How to use AJAX, Javascript, and PHP on multipart forms?

I have this update status form for my current project. As of now I am able to update my status with HTML entries only. I was wondering how I would go about allowing users to update with a photo. I know that the input type must be "file" and I need to add "enctype="multipart/form-data" to the form. What parts of the wall.js and functions.php do I need to modify to allow status update with photos. I do have a upload.php script but don't know how I can get it all to work together. Any clues or direction to try next would be great.
HTML Form
<form method="post" action="">
<input type="text" name="update" id="update">
<br />
<input type="submit" id="update_button" class="update_button"/>
</form>
wall.js //update status
$(document).ready(function()
{
$(".update_button").click(function()
{
var updateval = $("#update").val().split('\\').pop();
var dataString = 'update='+ updateval;
if(updateval=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('Loading Update...');
$.ajax({
type: "POST",
url: "message_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#flash").fadeOut('slow');
$("#content").prepend(html);
$("#update").val('');
$("#update").focus();
$("#stexpand").oembed(updateval);
}
});
}
return false;
});
}
Functions.php //Insert Update
public function Insert_Update($id, $update)
{
$update=htmlentities($update);
$time=time();
$ip=$_SERVER['REMOTE_ADDR'];
$query = mysql_query("SELECT msg_id,message FROM `messages` WHERE id_fk='$id' order by msg_id desc limit 1") or die(mysql_error());
$result = mysql_fetch_array($query);
if ($update!=$result['message']) {
$query = mysql_query("INSERT INTO `messages` (message, id_fk, ip,created) VALUES ('$update', '$id', '$ip','$time')") or die(mysql_error());
$newquery = mysql_query("SELECT M.msg_id, M.id_fk, M.message, M.created, U.username FROM messages M, users U where M.id_fk=U.id and M.id_fk='$id' order by M.msg_id desc limit 1 ");
$result = mysql_fetch_array($newquery);
return $result;
}
else
{
return false;
}
}
On the PHP side, see the "Handling File Uploads" section of the PHP manual at http://www.php.net/manual/en/features.file-upload.php. Chances are you'll want to use the "POST method uploads" (a la the $_FILES magic variable). Read all five sub-sections there to know how it all works and avoid problems.
Oh, and before putting any user input into your SQL queries, make sure to escape it using mysql_real_escape_string() / mysql_escape_string(). Hopefully that stuff wasn't in your example only because you were trying to keep your posting brief.

Resources