Updating database using AJAX form - javascript

I have a file, form.php, that has a small form for searching the database for people by first and last name. The form uses a JavaScript function to send variables to search_name.php through AJAX and information queried from mydatabase as values in a form.
I want to be able to update the information on the form in the #result element with the results from the search.
I tried doing a small example that did no have the form returned through AJAX and it worked but for some reason I am not able to do it in my bigger project.
Can anyone please help. I have looked for examples and information but I'm new to AJAX and PHP and can't figure out why this is happening.
form.php
<script language="JavaScript" type="text/javascript">
function ajax_post(){
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var errorMsg ="";
if (fn==null || fn=="" ){
errorMsg +="Enter First Name \n";
document.getElementById("first_name").focus();
}
if (ln==null || ln=="" ){
errorMsg +="Enter Last Name \n";
document.getElementById("last_name").focus();
}
if(errorMsg != ""){
alert(errorMsg);
document.getElementById("first_name").focus();
return false;
}else{
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "search_name.php";
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("result").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("result").innerHTML = "processing...";
}
}
</script>
</head>
<body>
<div class="left" id="search">
First Name: <input id="first_name" name="first_name" type="text" />
<br /><br />
Last Name: <input id="last_name" name="last_name" type="text" />
<br /><br />
<input name="myBtn" type="submit" value="Search" onClick="javascript:ajax_post();return">
<br /><br />
</div>
<div id="result"></div>
search_name.php
<?php $form_profile = '<form method="POST" action=""><table width="450px"><tr><td><label for="firstname" >First Name: </label></td><td><input type="text" id="first_name" name="first_name" maxlength="50" size="30" value="'.$first_name.'"/></td></tr><tr><td><label for="lastname" >Last Name: </label></td><td><input type="text" id="last_name" name="last_name" maxlength="50" size="30" value="'.$last_name.'"/></td></tr><tr><td><label for="headline">Headline</label></td><td><input type="text" id= "headline" name="headline" maxlength="50" size="30" value="'.$profile_headline.'"/></td></tr></table><input type="submit" id="submit" name="submit" value="Save and Update"></form>'; ?>
<?php
//check if form has been submitted
if(isset($_POST['submit'])){
$first_name= $_POST['first_name'];
$last_name= $_POST['last_name'];
$headline= $_POST['headline'];
$summary= $_POST['summary'];
$title_array= $_POST['title'];
$company_array= $_POST['company'];
$start_month_array= $_POST['start_month'];
$start_year_array= $_POST['start_year'];
$end_month_array= $_POST['end_month'];
$end_year_array= $_POST['end_year'];
if($first_name && $last_name){
//connect to server
$link = mysql_connect("localhost", "root", "########");
if($link){
mysql_select_db("mydatabase",$link);
}
//check if person exists
$exists = mysql_query("SELECT * FROM profile WHERE firstname = '$first_name' AND lastname = '$last_name'") or die ("The query could not be complete.");
if(mysql_num_rows($exists) != 0){
//update
mysql_query("UPDATE profile SET headline='$headline' WHERE firstname = '$first_name' AND lastname = '$last_name'") or die("Update could not be applied");
echo "Success!!";
}else echo "That alumni is not in the database";
}else echo "You must provide a first and last name.";
}
?>

As Timmy mentioned there is no submit value being posted (that only happens automatically if the post was triggered via a form). Also, you are trying to grab $_POST['first_name'] when you're sending 'firstname' (same goes for last_name vs lastname).
It's important to use some sort of developer tool when you are working with JavaScript / AJAX. I personally use Chrome Developer Tools (Press F12 in Chrome https://developers.google.com/chrome-developer-tools/). This will show you what the request / response actually looks like so you can figure out what your issues are. Based on what your front end it doing, I quickly rewrote the PHP script you are posting to:
<?php
//check if form has been submitted
if(isset($_POST['firstname']) || isset($_POST['lastname'])){
$first_name= $_POST['firstname'];
$last_name= $_POST['lastname'];
/*
$headline= $_POST['headline'];
$summary= $_POST['summary'];
$title_array= $_POST['title'];
$company_array= $_POST['company'];
$start_month_array= $_POST['start_month'];
$start_year_array= $_POST['start_year'];
$end_month_array= $_POST['end_month'];
$end_year_array= $_POST['end_year'];
*/
//connect to server
$link = mysql_connect("localhost", "root", "########");
if($link){
mysql_select_db("mydatabase",$link);
}
//check if person exists
$exists = mysql_query("SELECT * FROM profile WHERE firstname LIKE $first_name.'%' AND lastname LIKE $last_name.'%'") or die ("The query could not be completed.");
if(mysql_num_rows($exists) != 0){
//update
//mysql_query("UPDATE profile SET headline='$headline' WHERE firstname = '$first_name' AND lastname = '$last_name'") or die("Update could not be applied");
echo "Success!!";
} else {
echo "That alumni is not in the database";
}
} else {
echo "You must provide a first and last name.";
}
?>
I fixed the bad variable names and commented out the ones that are not being sent over at the moment. I also updated your MySQL query to use the LIKE string comparison function which is much better for searching. This way if someone doesn't know the last name, or only a portion, they can still finish the lookup. More on string comparison functions here: http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html. A copy and paste of the code should solve your problems for now.

Your javascript here:-
var vars = "firstname="+fn+"&lastname="+ln;
is not including "submit" which your PHP script requires to search the database, here:-
if(isset($_POST['submit'])){
So if you just add +"&submit=true" to the end of your vars variable, it should fix the given problem.
var vars = "firstname="+fn+"&lastname="+ln+"&submit=true";
Of course, you will see a lot of Undefined index warnings as your PHP script looks for lots of other variables that aren't sent initially =)
Hope this is of some help!

Related

Decode JSON package from PHP using AJAX

I am building a simple login system. I do not want the page to reload when the user submits the form, in case there is an error, and I need to seamlessly display an error message (Like wrong password). When the users submits the data, AJAX passes it onto the submit.php script. This script validates the data and then sets a JSON object to a number 1-3 based on what is wrong or right with the submitted credentials. I don't know how to have the AJAX call, decode the JSON, and then have some if statements that decide what to do based on the value of that JSON.
Below is the code I am using for the form.
HTML:
<form method="post" id="myForm">
<h1 class="title" unselectable="on">Login</h1>
<input placeholder="Username" type="text" name="username" class="form" id="username"/>
</br>
<input placeholder="Password" type="password" name="password" class="form" id="password"/>
</br>
<input class="button" type="button" id="submitFormData" onclick="SubmitFormData();" value="Submit"/>
</br>
</form>
JS/AJAX (Same page):
function SubmitFormData() {
var username = $("#username").val();
var password = $("#password").val();
$.post("submit.php", { username: username, password: password},
function(data) {
$('#results').html(data);
$('#myForm')[0].reset();
});
}
Next is the PHP (submit.php). The PHP will look at the incoming data from the AJAX script, and then assign an error number to a JSON object depending on what is wrong with the credentials.
$username = mysqli_real_escape_string($connect, $_POST["username"]);
$password = mysqli_real_escape_string($connect, $_POST["password"]);
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
if(password_verify($password, $row["password"]))
{
$Obj->error = "three";
$myJSON = json_encode($Obj);
}
else
{
$Obj->error = "two";
$myJSON = json_encode($Obj);
}
}
}
else {
$Obj->error = "one";
$myJSON = json_encode($Obj);
}
//error one=user not found
//error two=wrong password
//error three=all detials are correct
Now, the trouble I am having is back at the main page where the user is. I want the JS to look at the $myJSON variable and decide what to do based on that. I have written some pseudo code below, but I don't know if or how I can do this in JS or AJAX.
decode JSON package
if error=one, do something
if error=two, do something else
if error=three, run a php script that sets some session variables. (Is it possible to run php inside of JS?)
Any help accomplishing these results would be greatly appreciated.
This is a vanilla javascript solution:
const xmlhttp = new XMLHttpRequest;
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
//passes results to a function
start(JSON.parse(this.responseText));
}
}
xmlhttp.open("POST", "PHP WEBSITE URL", true);
//sends the request with a FormData object based on the form
xmlhttp.send(new FormData(document.getElementById("myForm")));
function start(object) {
alert(object);
}
For this to work, your PHP script will have to echo your result object. Example:
if ($_POST["username"] === "correctUsername" && $_POST["password"] === "correctPassword") {
//echo javascript object
echo json_encode(['success'=>true]);
} else {
//echo javascript object
echo json_encode(['success'=>false]);
}
Obviously it needs to be more complex but this is the idea.
I have made login pages before and instead of returning a success I used the current PHP page as the main one and echoed the info to fill the page as well as credentials that can be used with AJAX requests. Hopefully this helps.

Creating a simple Password login without the password hardcoded [PHP,Javascript,MySQL]

I'm trying to create a simple login promt on my local website. I already tried with Javascript, but I don't want the password to be hardcoded. The Users get the password by mail so there is no registration form needed. I searched on the Internet and I think it should work with PHP and Javascript. This is what i've come up with:
<SCRIPT>
function passWord() {
var testV = 1;
var pass1 = prompt('Enter password',' ');
while (testV < 3) {
if (!pass1)
window.open('Website.html',"_self");
if (pass1.toLowerCase() == "password") {
alert('Correct!');
window.open('./test/sitetwo.html',"_self");
break;
}
testV+=1;
var pass1 =
prompt('Wrong Password','Try again');
}
if (pass1.toLowerCase()!="password" & testV ==3)
return " ";
}
</SCRIPT>
<CENTER>
<FORM>
<input type="button" value="Enter Protected Area" onClick="passWord()">
</FORM>
</CENTER>
Does anyone of you know how to code this? Thank you for your help.
Login prompt is just one of possible approaches to hide information on your website. You have to decide first what are you trying to hide. For instance, if you if are providing some paid information to your clients - you can send the information itself by mail (instead of password). If you want to hide some part of site from other people - you can just give it weird url, like site.com/jkhgdsdkgf
Creating login backend with php and database obviously requires your php, mysql (or other database) and server administration skills and completely depends on details of your task, so it's hard to provide a useful advice here.
In my opinion, you should use a database to store all your credentials (like username, password, etc..)
If you don't know how to do it, you should know that if you want to run your php code, you need a php server and somewhere to put your db.
Here is how to set up a php server with Apache
https://www.ultraedit.com/support/tutorials-power-tips/uestudio/local-php-mysql-dev-environment.html
Here is how to set up a db with PhpMyAdmin
https://www.siteground.com/tutorials/phpmyadmin/create-populate-tables/
You need a login.php (where you log in), a test.php page (then you put in it whatever you want) and a check_User.php page (where to control if the credentials are correct).
Login.php
<html>
<head> <title>Login</title> </head>
<body>
<form action="check_User.php" method="post" id="login_form">
<label><b>Username</b></label>
<!-- USERNAME -->
<input type="text" placeholder="Enter Username" name="username" required>
<!-- PASSWORD -->
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<!-- LOGIN -->
<button type="submit">Login</button>
</form>
<body>
</html>
check_User.php
<?php
session_start();
$_POST["username"] = htmlspecialchars($_POST["username"]);
$_POST["password"] = htmlspecialchars($_POST["password"]);
$link = mysqli_connect("your_host", "your_db_username", "your_db_password", "your_db_name");
$query = "SELECT username, password
FROM your_db_name
WHERE username = \"".$_POST["username"]."\" AND password = \"".$_POST["password"]."\"
";
mysqli_query($link, $query);
$rows = array();
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
$rows[] = $row;
/* correct match */
if(mysqli_affected_rows($link) == 1)
{
$_SESSION["username"] = $_POST["username"];
$_SESSION["password"] = $_POST["password"];
}
if(isset($_SESSION["username"]) && isset( $_SESSION["password"]))
header("Location:test.php");
else {
alert("Wrong username or password");
}
?>
test.php
<?php
session_start();
// not logged in, not showing this page
if((!isset($_SESSION["username"]) || !isset( $_SESSION["password"]))
header("Location:login.php");
?>
<html>
....whatever you want this page to do
</html>

loop through JSON file using ajax, PHP & Javascript

I'm creating a small game where users must register or login before playing. I have a separate json file that stores already registered users.
Once a user enters their username and password into a field I make an AJAX call to retrieve the data using PHP with the intent of checking whether their details are on file. Firstly I tried sending back a JSON encoded object to parse through in Javascript. This is the code I have so far:
JSON:
{"LogIns":[
{
"Username":"mikehene",
"password":"123"
},
{
"Username":"mike",
"password":"123"
}
]
}
HTML:
<fieldset>
<legend>Please log in before playing</legend>
<form>
Username: <br>
<input type="text" placeholder="Enter a Username" id="username1" name="username"><br>
Password: <br>
<input type="password" placeholder="Enter a password" id="password" name="password"><br>
<input type="submit" value="Submit" onclick="return checkLogin();">
</form>
</fieldset>
PHP:
<?php
$username = $_POST['username'];
$str = file_get_contents('logins.json'); // Save contents of file into a variable
$json = json_decode($str, true); // decode the data and set it to recieve data asynchronosly - store in $json
echo json_encode($json);
?>
Javascript & AJAX call:
var usernamePassed = '';
function checkLogin(){
usernamePassed = document.getElementById("username1").value;
callAJAX();
return false;
}
function callAJAX(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp.responseText);
}
}
xhttp.open("POST", "LogInReg.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=" + usernamePassed);
}
function myFunction(response) {
var arr = response;
var objJSON = JSON.parse(arr);
var len = objJSON.length;
for(var key in objJSON){
console.log(key);
}
}
But it only prints out "LogIns". I also tried this:
for (var i = 0; i < objJSON.length; ++i) {
if(objJSON[0].Username == usernamePassed){
console.log("found it");
}
else{
console.log("didn't find it!");
}
}
Therefore I tried another approach (parse the data in the PHP file) like so:
foreach ($json['LogIns'][0] as $field => $value) {
if($json['LogIns'][0]['Username'] == $username){
echo "Logged In";
break;
}
else{
echo "No user found";
break;
}
}
But when I enter "mike" as a user name it is echoing "No user found". So I'm lost! I'm new to coding and trying to learn myself. I would love to learn how to do it both methods (i.e. PHP and Javascript).
Everything I've found online seems to push toward JQuery but I'm not quite comfortable/good enough at JQuery yet so would like to gradually work my way up to that.
I haven't even got to the register a user yet where I'm going to have to append another username and password on registration.
Any help would be GREATLY appreciated.
Thanks in advance
Try this
$json = json_decode($str, true);
$password = $_POST['password'];
foreach($json['LogIns'] as $res)
{
if($res['Username']==$username && $res['password']==$password)
{
echo json_encode($res['Username']);
//echo 'user found';
}
}

Using AJAX to send form data to php script (without jQuery)

I am trying to do a basic AJAX implementation to send some form data to a php script and db. I'm just doing this for learning purposes, and have taken it as far as I could. When I hit the "Create Profile" button, nothing is happening. From my code below, does anything obvious jump out at anyone in my syntax/structure?
Note* I've yet to implement the code to retrieve the data using AJAX, will do this later once I get the send working.
EDIT*** I made some slight changes to the sendFunction(), and have seen some success. Values are now being added to my database, but they values are blank, instead of the values in the form data.
Thank you for all help/suggestions ahead of time!
HTML doc:
<!DOCTYPE HTML>
<html>
<head>
<title>Ajax Form</title>
<script language="javascript" type="text/javascript">
function sendFunction() { // Create a function to handle the Ajax
var xmlhttpCreate; // Variable to hold the xmlhttpRequest object
if (window.XMLHttPRequest) { // Checks for browser compatibilities
xmlhttpCreate = new XMLHttpRequest();
}
else {
xmlhttpCreate = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttpCreate.onreadystatechange = function() {
if (xmlhttpCreate.readyState == 4) { // If server has processed request and is ready to respond
document.getElementById("createSuccess").innerHTML = xmlhttpCreate.responseText; // Display a success message that the data was sent and processed by the php script & database
}
}
var fName = document.getElementById('firstName').value; // Dump user firstName into a variable
var lName = document.getElementById('lastName').value; // Dump user lastName into a variable
var queryString = "?fName=" + fName + "&lName=" + lName; // A query string that will be sent to the php script, which will then send the values to the db
xmlhttpCreate.open("GET", "ajax_create.php" + queryString, true); // Open the request
xmlhttpCreate.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttpCreate.send(); // Send the request
}
</script>
</head>
<body>
<h3>Create Profile</h3><br>
<form name="form">
First Name: <input type="text" id ="firstName"/><br><br>
Last Name: <input type="text" id="lastName"/><br><br>
<input type="button" onclick="sendFunction()" value="Create Profile">
</form><br>
<div id="createSuccess"></div><br>
<h3>Search for Profile</h3><br>
<form name="searchForm">
First Name: <input type="text" id="searchFirstName"/><br><br>
<input type="button" onclick="sendFunction()" value="Search for Profile"/>
</form><br><br>
<div id="resultFN"></div><br>
<div id="resultLN"></div><br>
</body>
</html>
And here is my PHP script:
<?php
// Connect to the database
$con = mysqli_connect('localhost', 'root', 'intell', 'ajax_profile');
// GET variables from xmlhttpCreate
$fName = $_POST['fName'];
$lName = $_POST['lName'];
// Escape the user input to help prevent SQL injection
$fName = mysqli_real_escape_string($fName);
$lName = mysqli_real_escape_string($lName);
// Build the query
$query = "INSERT INTO users (firstName, lastName) VALUES ('$fName', '$lName')";
mysqli_query($con, $query);
mysqli_close($con);
$success = "Profile added to the database";
echo $success;
?>
you are sending data with method GET and you want to get the date in your php file with POST ... now you have two solutions . you can change the javascript code to send with GET like this :
var queryString = "fName=" + fName + "&lName=" + lName; // A query string that will be sent to the php script, which will then send the values to the db
xmlhttpCreate.open("POST", "ajax_create.php", true); // Open the request
xmlhttpCreate.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttpCreate.send(queryString);
or you can change the way you get the data on your php file like this:
$fName = $_GET['fName'];
$lName = $_GET['lName'];
don't do both things , only one, change either javascript function or php file.

Phone Number Not Inserted Into Database

I'm creating a simple form, which takes a couple of fields as input, runs some AJAX checks and submits to SQL database via PHP. I'm able to insert all other fields EXCEPT the phone number. Here's a snippet of the codes:
HTML ---
<form name="signupform" id="signupform" onSubmit="return false;">
<div>Phone Number: </div>
<input id="phon" type="text" maxlength="20">
<button id="signupbtn" onClick="signup()">Create Account</button>
<span id="status" style="color: red"></span>
</form>
JS ---
function signup() {
var status = document.getElementById("status");
var phone = document.getElementById("phon").value;
status.innerHTML = phone; //testing, doesn't display anything
var ajax = ajaxObj("POST", "index.php"); // accepted
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "Succesfully signed-up!"){ ///returned from php file
status.innerHTML = ajax.responseText;
}
}
}
ajax.send("phone="+phone); //shoots variable to php
}
PHP ---
if(isset($_POST["phone"])) {
$phone = $_POST['phone'];
echo $phone; //was testing, again, nothing shows
$sql = "INSERT INTO users(phone) VALUES('$phone')";
}
$query2 = mysqli_query($con, $sql);
echo 'successfully_updated';
NOTE: I tried to check if JS and PHP are receiving the phone number, but it's not displaying anything (other form elements such as name and email are displayed, though, tested that already). But later-on, in the PHP code, it isn't showing any error when checked against "if (isset($_POST["phone"])), it inserts the other elements of the form without trouble. No clue why that's happening, any ideas please? My guess is that since JS doesn't reflect the value, that's where the error lies.
Been searching and trying in vain since hours! Any help would be great, thanks!
using jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
phoneNum = $("#phon").val();
$("#signupbtn").click(function(){
$.ajax({url:"./index.php",data:{phone:phoneNum},success:function(result){
alert(result);
}});
});
});
</script>
status.innerHTML = phone; //testing, doesn't display anything
must be
document.getElementById("status").innerHTML = phone;
why not write $query2 = mysqli_query($con, $sql) or die(mysqli_error());
That way, you can see what the error occurs
Please try this
$sql = "INSERT INTO users(phone) VALUES('".$phone."')";

Categories

Resources