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
Related
I'm trying to make a "sign in status" thing.
Here is a summary of what is happening.
User fills our field and jQuery request is sent.
Credentials are validated.
Screen displays a welcome message.
So I can get the welcome message sent back to me if the credentials are valid (or error if credentials are false), but here is where the issue resides...
I am having a really difficult time storing anything in PHP as a global variable using my only jQuery (no included file) approach... So my workaround was to take the passed message (Let's just say when credentials are valid, I pass back something like "X" or "1"), and then when the data comes back in the jQuery, I put an if statement in the callback, but it isn't working.
I know that the data being passed is matching what is being compared, and i've tested many different things to pass back, but the comparison is not being done.
Perhaps it isn't possible to do things like if statements in a jQuery callback, but also maybe I'm doing something wrong.
HTML:
<label>Sign In</label>
<br>
<label>Username</label>
<input type="text" id="name1">
<label>Password</label>
<input type="text" id="pass1">
<br>
<button type="submit" id="button2">Sign In</button>
<div id = "xx1">Status: Offline</div>
<div id = "xx2"></div>
jQuery:
$(document).ready(function(){
$("#button2").click(function(){
var name1=$("#name1").val();
var pass1=$("#pass1").val();
var key = "signIn";
$.ajax({
url:'rpc.php',
method:'POST',
data:{
name1:name1,
pass1:pass1,
key:key
},
success:function(data){
if(data === '1')
{
document.getElementById('xx1').innerHTML = "Status: Online";
}
document.getElementById('xx2').innerHTML = data;
//var p = data;
}
});
});
});
(xx2 is updating by the way)
Lastly, relevant bits of my rpc.php:
else if($_POST['key'] === "signIn")
{
$name1=$_POST['name1'];
$pass1 = $_POST['pass1'];
if($name1 !== "" && $pass1 !== "")
{
$sql = "SELECT * FROM whatever";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if($name1 === $row["username"])
{
$UNTrue = true;
if (password_verify($pass1, $row['password'])) {
$PassTrue = true;
}
}
}
} else {
//echo "0 results";
}
if($UNTrue === true && $PassTrue === true)
{
echo "1";
$conn->close();
}
else
{
echo "<p align=center style = 'color:#ba261b'>(Incorrect Username or Password) </p>";
$conn->close();
}
}
else
{
echo "<p align=center style = 'color:#ba261b'>(Please Fill Required Fields) </p>";
$conn->close();
}
}
So data is "1" in this scenario, as displayed to my via xx2, and xx1 remains as "Status: Offline".
I'm wondering if I have to store the data in a JavaScript variable first, and then later somehow referencing it again ASAP.
The other option would be to figure out how to use PHP global variables without file inclusion.
Is it possible even though you're echoing "1", it's getting interpreted as a number? Assuming the data response you get in the success callback is literally just what your PHP script echoes, that's the first thing that jumps out to me, since (1 === "1") is false.
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.
I have built a simple search tool for my Web App to search through my client database. It returns form submit buttons in a dropdown so that, when a selection is made, the selected clients ID is passed in a POST to the following page. The following page receives this POST and populates with all of the stored information about that client. This works the way I need it to for the most part, but I have a couple questions.
1) most autocompletes/autosuggests that I have seen examples of return JSON data as the results. Is using JSON inherently a smoother or safer process for this?
2) my search results (form buttons) display in a dropdown but are not navigable via TAB or ARROW keys. What is needed to add this accessibility? I tried to add TabIndex to the buttons but that did nothing.
I arrived at this particular solution for my need of a search function after failing miserably to understand some of the pre-packaged Autocomplete solutions out there. They seemed much more complex than what I needed for this Web App.
Here is what I am using.
HTML:
<div class="row">
<div class="col-12">
<input onKeyUp="myFunction()" type="text" id="searchterm" placeholder="Search for existing client">
<div class="searchResults" id="results"></div>
<script>document.getElementById("results").style.visibility='hidden';</script>
<script type="text/javascript" src="js/watchdog.js"></script>
</div>
</div>
JAVASCRIPT:
function myFunction() {
var input = document.getElementById("searchterm").value;
if (input && input.length >= 2) {
$.ajax({
type: "POST",
url: "searchengine.php",
data: {input : input},
success: function(data) {
if (data) {
document.getElementById("results").style.visibility='visible';
document.getElementById("results").innerHTML = data;
}
else {
document.getElementById("results").style.visibility='hidden';
}
}
});
}
else {
document.getElementById("results").style.visibility='hidden';
return false;
}
}
PHP:
<?php
include ('connect.php');
$input = trim($_POST['input']);
$input = htmlspecialchars($input);
$equiv = '%' . $input . '%';
// prepare stmt, bind param, execute
$stmt = $conn->prepare("SELECT client_id, firstname, lastname, city, state FROM client WHERE firstname LIKE ? OR lastname LIKE ?");
$stmt->bind_param("ss", $equiv, $equiv);
$stmt->execute();
$stmt->bind_result($client_id, $firstname, $lastname, $city, $state);
while ($stmt->fetch()) {
echo "
<form name=\"clientSearchResults\" action=\"client.php\" method=\"post\">
<input name=\"client_id\" value=\"$client_id\" type=\"hidden\">
<div class=\"wrapper\">
<input style=\"height: 25px;\" type=\"submit\" value=\"$firstname $lastname - $city, $state\"></input>
</div>
</form>
";
}
// close statement
$stmt->close();
include ('disconnect.php');
?>
Re: TAB key access to submit buttons.
Looking into this further I found the answer to the accessability issue here:
submit-button-not-focused-even-though-tabindex-is-properly-set
This seems to be an issue I encountered because of my laptop being a Mac.
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!
I'm trying to create a comment system on my website where the user can comment & see it appear on the page without reloading the page, kind of like how you post a comment on facebook and see it appear right away. I'm having trouble with this however as my implementation shows the comment the user inputs, but then erases the previous comments that were already on the page (as any comments section, I'd want the user to comment and simply add on to the previous comments). Also, when the user comments, the page reloads, and displays the comment in the text box, rather than below the text box where the comments are supposed to be displayed. I've attached the code. Index.php runs the ajax script to perform the asynchronous commenting, and uses the form to get the user input which is dealt with in insert.php. It also prints out the comments stored in a database.
index.php
<script>
$(function() {
$('#submitButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
$("#comment_part").html(html);
window.location.reload();
}
});
});
});
</script>
<form id="comment_form" action="insert.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="userInput"/>
<input type="submit" name="submit" value="submit" id = "submitButton"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<div id='comment_part'>
<?php
$link = mysqli_connect('localhost', 'x', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
</div>
insert.php
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
//header("Location:csair.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
The insert.php takes in the user input and then inserts it into the database (by first filtering and checking for bad words). Just not sure where I'm going wrong, been stuck on it for a while. Any help would be appreciated.
There are 3 main problems in your code:
You are not returning anything from insert.php via ajax.
You don't need to replace the whole comment_part, just add the new comment to it.
Why are you reloading the page? I thought that the whole purpose of using Ajax was to have a dynamic content.
In your ajax:
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
//this will add the new comment to the `comment_part` div
$("#comment_part").append(html);
}
});
Within insert.php you need to return the new comment html:
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
mysqli_close($link);
//here you need to build your new comment html and return it
return "<div class='comment'>...the new comment html...</div>";
}
else{
die('comment is not set or not containing valid value');
}
Please note that you currently don't have any error handling, so when you return die('comment is not set....') it will be displayed as well as a new comment.
You can return a better structured response using json_encode() but that is outside the scope of this question.
You're using jQuery.html() which is replacing everything in your element with your "html" contents. Try using jQuery.append() instead.