Ajax and MySql inserting, checking and retrieving - javascript

I have two database tables, guestlist and attendance
On one HTML page, I have a window.onload script that I want to check the guestlist via AJAX. If the firstname AND lastname in the url query appear in the guestlist table, then load the page. If not, load an error message.
When the page is properly loaded, the firstname and lastname are pre-populated in two input fields. The user completes the rest of the form and clicks submit, inserting their firstname and lastname into the attendance table.
If the firstname and lastname already appear in the attendance table, load an error message. If the firstname AND lastname to not appear in the attendance table, submit the form information to the attendance table.
When it comes to Ajax, I am not the bright bulb in the pack. This is the code I currently have:
HTML
<body>
<div id="formDiv">
<form id="partyForm" name="party" action="party_insert" method="post">
<h1>Welcome to The Party</h1>
<input name="first_name" id="firstname" class="input" type="text" maxlength="99" placeholder="First Name"><br/>
<input name="last_name" id="lastname" class="input" type="text" maxlength="99" placeholder="Last Name"><br/>
<input name="costume" id="costume" class="input" type="text" maxlength="999" placeholder="What are you supposed to be?"><br/>
<div id="buttonDiv">
<a class="button" id="submit" style="cursor:pointer;">SUBMIT</a>
</div>
</form>
</div>
<script>
window.onload = function () {
var fname_init = decodeURIComponent(getUrlVars()["fname"]);
var lname_init = decodeURIComponent(getUrlVars()["lname"]);
if(fname_init !== "undefined" && lname_init !== "undefined"){
var newString = 'fname='+encodeURIComponent(fname_init)+'&lname='+encodeURIComponent(lname_init);
$.ajax({
type: "GET",
url: "guestList.php",
data: newString,
success: function(){
alert("ON THE LIST");
$('#firstname').val(fname_init);
$('#lastname').val(lname_init);
},
error: function(){
alert("NOT ON THE LIST");
window.location = 'error1.html?fname='+encodeURIComponent(fname_init)+'lname='+encodeURIComponent(lname_init);
}
})
}
}
$("#submit").click(function() {
validate();
});
function submit(){
var fname = $("#firstname").val();
var lname = $("#lastname").val();
var cost = $("#costume").val();
var dataString = 'fname='+encodeURIComponent(fname)+'&lname='+encodeURIComponent(lname)+'&cost='+encodeURIComponent(cost);
$.ajax({
type: "POST",
url: "partyEntry.php",
data: dataString,
success: function() {
alert("ENJOY THE PARTY");
clearForms();
}
});
}
function validate(){
if ($("#firstname").val() == ""){
alert("Please Enter your First Name");
} else {
if ($("#lastname").val() == ""){
alert("Please Enter your Last Name");
}else{
if ($("#costume").val() == ""){
alert("You have to have a costume to be eligible for this raffle");
}else{
submit();
}
}
}
}
function clearForms() {
$('#partyForm')[0].reset();
}
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
</script>
</body>
guestList.php
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "party";
$link = mysql_connect($host, $user, $password);
mysql_select_db($database);
//SURVEY INFORMATION
$fname = mysql_real_escape_string($_REQUEST['fname']);
$lname = mysql_real_escape_string($_REQUEST['lname']);
$checkClient = "SELECT * FROM guestlist WHERE first_name = ".$fname." AND last_name = ".$lname;
mysql_query($checkClient) or die(mysql_error());
mysql_close($link);
?>
partyEntry.php
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "party";
$link = mysql_connect($host, $user, $password);
mysql_select_db($database);
//SURVEY INFORMATION
$fname = mysql_real_escape_string($_REQUEST['fname']);
$lname = mysql_real_escape_string($_REQUEST['lname']);
$cost = mysql_real_escape_string($_REQUEST['cost']);
$addClient = "INSERT INTO attendance (first_name, last_name, costume) VALUES ('$fname','$lname', '$cost')";
mysql_query($addClient) or die(mysql_error());
mysql_close($link);
?>
The error I am getting is that even though a name is not on the guestlist, it will still show that they are ON THE LIST. So I must be doing something wrong in the Ajax call to guestlist.php, but I have no idea what. I also am having problems scripting out an ajax call to check if the guest has already been put into the attendance table.

Like I said in my comment you will have to return a value from the guestList.php, something like this should work:
$checkClient = "SELECT * FROM guestlist
WHERE first_name = ".$fname." AND
last_name = ".$lname;
$result = mysql_query($checkClient);
$count = mysql_num_rows($result);
mysql_close($link);
// output 1 or 0 stating if the user is on the list or not
echo ($count ? 1 : 0);
exit();
Then in your ajax callback you would do a check like:
success:function(e) {
alert((e == 1 ? "User is on list" : "User isn't on list"));

According to the REST principle, responding to a POST request with HTTP 200 means that the resource is successfully created. You can respond with a HTTP 400 and also provide detailed information about the error in text/html/json/xml format.
Try doing this,
Add the folowing code,
$query = mysql_query($addClient) or die(mysql_error());
if(mysql_num_rows($query) > 0)
{
header('HTTP/1.1 500 Internal Server Error');
echo 'this is an error message';
}

The php script will never throw an error at least you try to execute an invalid query. The query is executed without any error because it is well formatted so and error won't be throw because you are not getting rows from the database.

Related

Trying to get data from textbox and inserting it into a database

I have a form that is to be used to input information and register an account. The information is entered on the website and when the button 'register' is pressed it is validated by an external JavaScript method and afterwards, a PHP method is called using ajax which should take the information from the text boxes and enter it into the database. I can't seem to get the PHP getting the information working.
<?php
$mysqli = new mysqli('localhost:8080', 'root', null, 'salmonhouse');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "INSERT INTO clients (name, surname, email, address, password)
VALUES (?,?,?,?,?)";
$name = $_POST['name'];
$surname = $_POST['surname'];
$email= $_POST['email'];
$address= $_POST['Address'];
$pass= $_POST['Password'];
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("sssss", $name, $surname, $email, $address, $pass);
$stmt->execute();
?>
HTML textboxes
<form class="quote">
<div class = inliner>
<label>Name</label>
<input id="name" type="text" placeholder="Name">
</div>
<div class = inliner>
<label>Surname</label>
<input id="surname" type="text" placeholder="Surname">
</div>
<div>
<label>Email</label><br>
<input id="email" type="email" placeholder="Email Address"><br>
</div>
<div>
<label>Address</label><br>
<input id="Address" type="email" placeholder="Home Address"><br>
</div>
<div class = inliner>
<label>Password</label>
<input id="Password" type="text" placeholder="Password">
</div>
<div class = inliner>
<label>Verify Password</label>
<input id="vPassword" type="text" placeholder="Password">
</div>
<br><button class="button_1" type="button" onclick="Validate()">Register</button>
</form>
Calling javascript file from html page
<script type= "text/javascript">
var name = document.getElementById("name").value;
var surname =document.getElementById("surname").value;
var email =document.getElementById("email").value;
var pass=document.getElementById("Password").value;
var passV =document.getElementById("vPassword").value;
var address=document.getElementById("Address").value;
</script>
<script type= "text/javascript" src="asset/js/my_javascript.js"></script>
Actual javascript file
/* eslint-env browser */
/*jslint devel: true */
/* eslint-disable */
function Validate(){
name = document.getElementById("name").value;
surname =document.getElementById("surname").value;
email =document.getElementById("email").value;
pass=document.getElementById("Password").value;
passV =document.getElementById("vPassword").value;
var error = "";
document.getElementById("name").style.borderColor = "white";
document.getElementById("surname").style.borderColor = "white";
document.getElementById("email").style.borderColor = "white";
document.getElementById("Password").style.borderColor = "white";
document.getElementById("vPassword").style.borderColor = "white";
var count= 0;
if(name.length == 0){
document.getElementById("name").style.borderColor = "red";
count =1;
error = error + "Name cannot be empty\n"
}
if(surname.length == 0 ){
document.getElementById("surname").style.borderColor = "red";
count =1;
error = error + "Surname cannot be empty\n"
}
if(email.length == 0 ){
document.getElementById("email").style.borderColor = "red";
count =1;
error = error + "Email cannot be empty\n"
}
if(!(email.includes("#"))){
document.getElementById("email").style.borderColor = "red";
count =1;
error = error + "Email needs to contain an # symbol\n"
}
if(!(email.includes("."))){
document.getElementById("email").style.borderColor = "red";
count =1;
error = error + "Email needs to comtain a .com or similar\n"
}
if(pass!==passV){
document.getElementById("Password").style.borderColor = "red";
document.getElementById("vPassword").style.borderColor = "red";
count =1;
error = error + "Passwords do not match\n"
}
if(!(pass.match(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##$%&*()])[0-9a-zA-Z!##$%&*()]{8,}$/))){
document.getElementById("Password").style.borderColor = "red";
document.getElementById("vPassword").style.borderColor = "red";
count =1;
error = error + "Password must be atleat 8 long and contain a LowerCase, UpperCase, Number and a symbol."
}
if(false){
alert("Please correct the following errors highlighted in red\n"+error);
}
else{
alert("Name: " + name + "\nSurname: "+ surname + "\nEmail: "+ email+"\nPassword: "+pass+"\n Succesful Registration");
xmlhttp = new XMLHttpRequest();
var url = "asset/php/inserting.php";
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
}
/* eslint-enable */
This PHP file is a separate file with just this code. I have tested and if I manually set the variables instead of trying to retrieve them the data is successfully inserted into the database. So from my testing it is simply the retrieval not working. I also tried $_REQUEST['name']
This is the ajax/xmlhttprequest code.
xmlhttp = new XMLHttpRequest();
var url = "asset/php/inserting.php";
xmlhttp.open("POST",url,true);
xmlhttp.send();
My advice would be to use the jQuery library rather than XMLHttpRequest. You will need to include in the <head> section of your HTML a <script> tag to load the jQuery library from some CDN (Content Delivery Network). Also add id="f" to your <form> tag. Then your Ajax call can be as simple as:
$.ajax({
type: "POST",
url: 'asset/php/inserting.php',
data: $('#f').serialize(), // serializes the form's elements.
success: function(msg)
{
alert(msg); // show response from the php script.
}
});
You can attached the variable in ajax call, which you need to get in your php page using & for separating variable and = for assigning value .i,e :
//attaching values to pass
var data = "name=" + name + "&email=" + email + "&surname=" + surname + "&Address=" + Address + "&Password=" + Password;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//if success do something here
alert("save");
}
};
var url = "asset/php/inserting.php";
request.open("POST", url, true);
//send data to php page
request.send(data);

How to retrieve PHP column value into Javascript for login validation?

I am writing a simple login validation. (I know people say I shouldn't deal with passwords in plaintext, because it's dangerous, however, I am doing this for a school assignment where we do not need to use any security.) The issue I am having here is that I can't get the message for login to be successful. I am getting a login failure. I inserted a couple of users and passwords into a database table. What I need to do is to get the value from the "name" column and the "pwd" (password) column from my database table and allow a successful login (in Javascript) if the user's input has a match with the user and password in the database table.
Here is my form code:
<form method="post" action="login.php" onsubmit="validateForm()" id="loginForm" name="loginForm">
Name:<br>
<input type="text" name="personName"><br>
Password:<br>
<input type="password" name="pswd"><br>
<input type="submit" name="submit" id="submit" value="Login" />
</form>
Javascript:
<script>
function validateForm()
{
var n = document.loginForm.personName.value;
var p = document.loginForm.pswd.value;
//The var below is what I need help on.
var name = "<?php echo $row['name']; ?>";
//The var below is what I need help on.
var ps = "<?php echo $row['pwd']; ?>";
if ((n == name) && (p == ps))
{
alert ("Login successful!");
return true;
}
else
{
alert ("Login failed! Username or password is incorrect!");
return false;
}
}
</script>
PHP code (I have an empty while statement just in case I need it):
<?php
function validateLogin()
{
//I hid this information from here.
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$dbc = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($dbc->connect_error)
{
die("Connection failed: " . $dbc->connect_error);
}
$n = $_POST["personName"];
$p = $_POST["pswd"];
$query = "SELECT `name`, `pwd` FROM `chatApp`";
$result = $dbc->query($query);
$numRows = mysql_num_rows($result);
$count = 1;
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
}
}
else
{
echo "0 results";
}
$dbc->close();
}
if(array_key_exists('loginForm',$_POST))
{
validateLogin();
}
?>

JavaScript sending empty parameters to PHP

I am attempting to create a user area for a website that is accessed by using a username and password. I am using HTML for the front end, JavaScript for the back end and PHP for the server side. I am using Xampp to run a local server and PHPMyAdmin to host the database.
The HTML Code:
<!-- the Login Section -->
<input type="text" name="userName" placeholder="username" id="usernameBar">
<input type="password" name="passWord" placeholder="password" id="passwordBar">
<button id="loginButton" onclick="Login();">Login</button>
<p id="IncorrectP" title="Incorrect Username or Password" style="display: none">Invalid</p>
JavaScript:
function Login(){
//Connect to the PHP:
var urlConnect = "checkLogin1.php";
//Get the username and password:
var usrUsername = document.getElementById("usernameBar").value;
var usrPassword = document.getElementById("passwordBar").value;
//Define the parameters to send to php
var strParameters = "usrUsername="+usrUsername + "usrPassword="+usrPassword + "&sid=" + Math.random();
//Define the options for the AJAX request
var objOptions = {
method: "post",
parameters: strParameters,
onSuccess: function(objXHR) {
//If objXHR. responseText = Tenant:
if(objXHR.responseText=='Tenant'){
//Go to tenant space:
alert("Success! (Tenant)");
OpenTenantPage();
}
//Else if objXHR.responseText = Staff:
else if(objXHR.responseText=='Staff'){
//Go to staff space:
alert("Success! (Staff)");
OpenStaffPage();
}
//Else if objXHR.responseText = Admin:
else if(objXHR.responseText=='Admin'){
//Go to admin space:
alert("Success! (Admin)");
OpenAdminPage();
}
else{
//Run IncorrectLogin:
alert("Error! No User Account Found!");
IncorrectLogin();
}
}
}
// define the AJAX request object
var objRequest = new Ajax.Request(urlConnect,objOptions);
}
PHP:
<?php
//Link the username and password:
$connect = mysqli_connect("localhost", "admin", "12345", "realestate") or die ('Connection to database failed: ' . mysql_error());
//Extract variables for request parameters:
extract($_REQUEST);
//Try to log in as a tentant:
$resTenantUser = mysqli_query($connect, "SELECT * FROM tenants WHERE Username='$usrUsername' AND Password='$usrPassword'") or die(mysql_error());
//$resTenantUser = mysqli_query($connect, "SELECT * FROM tenants WHERE Username='Charb1' AND Password='123456' ") or die(mysql_error());
//Set intCount to number of rows in result:
$intCount = mysqli_num_rows($resTenantUser);
if($intCount == 0){
echo "Error!";
}
else{
echo "Tenant";
}
?>
I think that the error my be that the JS is not sending the parameters to the PHP or it is sending empty parameters. I cannot seam to find my mistake though.
parameters must be in JSON format not in query string format.something like this:
parameters:{usrUsername: usrUsername , usrPassword:usrPassword , sid : Math.random()}
Problem is in the query params. You missed &. Try this way.
var strParameters = "usrUsername="+usrUsername + "&usrPassword="+usrPassword + "&sid=" + Math.random();
Or
var strParameters = {"usrUsername" : usrUsername, "usrPassword" : usrPassword, "sid" : Math.random()}

PHP & Javascript: Dynamic search with 2 textbox

Is there any way to have a dynamic search with 2 textbox to filter 2 different fields?
for example i have a table like:
and i have created somethin like this:
it already works in the LASTNAME textbox.
i want is that when i enter a lastname with same lastnames like this:
i want to add another filter by firstname, so that when i enter a firstname on the FIRSTNAME textbox example i enter PEDRO in the FIRSTNAME textbox only PEDRO A. Dela Cruz will show up.
This is my Codes
Index.php
<script type="text/javascript">
$(function(){
$(".lname").keyup(function()
{
var value = $(this).val();
var dataString = 'lname='+ value;
if(searchlname!='')
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
jQuery("#result").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#searchlname').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$('#searchlname').click(function(){
jQuery("#result").fadeIn();
});
});
</script>
<div class="content">
Lastname:
<input type="text" class="lname" id="searchlname" placeholder="Search for people" /><br />
Firstname:
<input type="text" class="search" id="" placeholder="Search for people" /><br />
<div id="result">
</div>
search.php
<table width="80%">
<th width="5%">ID</th>
<th width="40%">Name</th>
<th width="10%">Action</th>
</table>
<?php
$connection = mysql_connect('localhost','root','admin') or die(mysql_error());
$database = mysql_select_db('dbvincent') or die(mysql_error());
if($_POST)
{
$search_name=$_POST['lname'];
$sql_res=mysql_query("SELECT * FROM `tblpatients` WHERE `lname` LIKE '%$search_name%' order by `patient_id` LIMIT 15");
while($row=mysql_fetch_array($sql_res))
{
$id = $row['patient_id'];
$fname = $row['fname'];
$mname = $row['mname'];
$lname = $row['lname'];
?>
<table width="80%">
<td width="5%"><?php echo $id ; ?></td>
<td width="40%"><?php echo $fname.' '.$mname.' '.$lname; ?></td>
<td width="10%"><button formaction="echoid.php?id=<?php echo $id ?>">Add</button></td>
</table>
<?php
thanks you.
There are cleaner ways of doing this, but instead if changing all your code, I've updated it to fit your needs. I've already nagged about the security aspect and about not using those old, deprecated mysql_*-functions, but rather Prepared Statements with MySQLi or PDO.
It just needs to be pointed out in case someone else comes here later.
First, I would give both input fields a new extra css class, example: people-search-filter,
I'm also giving the field for last name an ID :
<input type="text" class="lname people-search-filter" id="searchlname" ...
<input type="text" class="search people-search-filter" id="searchfname" ...
This allowes us the create the same event on both input fields:
$(function(){
// We add the event on the class, which both inputs have
$(".people-search-filter").keyup(function() {
// Now we get the values from both inputs, using their ID's
var lname = $("#searchlname").val();
var fname = $("#searchfname").val();
// Add both to the dataString (and URI encode the strings)
var dataString = {lname: lname, fname: fname}
// Check that at least one has any content
if(lname != '' || fname != '')
// Your ajax query
In your PHP code, you just add the new parameter into your query:
$lname = $_POST['lname'];
$fname = $_POST['fname'];
// Now we will build the search string
$search_str = '';
if ($lname) {
$search_str = "WHERE lname LIKE '%" . mysql_real_escape_string($lname) . "%'";
}
if ($fname) {
// Check if we have something in the search string,
// if we do, add an AND to the statement.
// If we don't have one, we'll add the WHERE instead.
$search_str .= $search_str ? ' AND ' : 'WHERE ';
$search_str .= "fname LIKE '%" . mysql_real_escape_string($fname) . "%'";
}
// If neither $lname or $fname contains any data, the query will return all patiens
$sql_res = mysql_query("SELECT * FROM `tblpatients` {$search_str} order by `patient_id` LIMIT 15");
// ... the rest of your code.
You could try something like this perhaps where you build the query based upon the existence of first/lastnames - not tested but might give an idea
$search_name = !empty( $_POST['lname'] ) ? $_POST['lname'] : false;
$firstname = !empty( $_POST['fname'] ) ? $_POST['fname'] : false;
if( $search_name ){
$clauses=array();
$clauses[]="`lname` like '%$search_name%'";
if( $firstname ) $clauses[]="`fname` like '%$firstname%'";
$search = implode( ' AND ', $clauses );
$sql_res=mysql_query("SELECT * FROM `tblpatients` WHERE {$search} order by `patient_id` LIMIT 15");
/* rest of the commands...*/
}

jQuery XMLHttpRequest calling External PHP form not submiting

I recently had a friend who specializes in ladder logic and not web programming, come to me requesting help with a project from her employer. While I use more traditional coding languages, I am far from an expert in jquery and php myself. The problem that we are having is that a php page with a jquery / html form inserted into a parent page via XMLHttpRequest, is not executing its "post" action from the parent page. The thing that makes this problem more difficult is that when page is run by itself outside of the parent page (loaded directly into the browser), it executes its "post" action fine. I have done many hours of searching and trial and error at this point but am stumped and now come to you for help. Below are the relevant bits of code. Any help you could provide would be greatly appreciated as nothing we've tried seems to work when it comes to executing the submit of the form when it is inserted via XMLHttpRequest.
Javascript Code From Parent Page inserting external form:
function showUser(str)
{
if (str=="")
{
document.getElementById("insertUserHere").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp.status==200)
{
document.getElementById("insertUserHere").innerHTML=xmlhttp2.responseText;
}
}
xmlhttp2.open("GET","ajax-userForm.php?q="+str,true);
xmlhttp2.send();
}
Code of External PHP page Inserted By xhmlhttprequest (ajax-userForm.php):
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
// JQUERY: Plugin "autoSubmit"
(function($) {
$.fn.autoSubmit = function(options) {
return $.each(this, function() {
// VARIABLES: Input-specific
var input = $(this);
var column = input.attr('name');
// VARIABLES: Form-specific
var form = input.parents('form');
var method = form.attr('method');
var action = form.attr('action');
// VARIABLES: Where to update in database
var where_val = form.find('#where').val();
var where_col = form.find('#where').attr('name');
// ONBLUR: Dynamic value send through Ajax
input.bind('blur', function(event) {
// Get latest value
var value = input.val();
if (input.attr('type') == "checkbox")
{
if (input.attr('checked') )
{
value = 1;
}
else
{
value = 0;
}
}
// AJAX: Send values
$.ajax({
url: action,
type: method,
data: {
val: value,
col: column,
w_col: where_col,
w_val: where_val
},
cache: false,
timeout: 10000,
success: function(data) {
// Alert if update failed
if (data) {
alert(data);
}
// Load output into a P
else {
$('#notice').text('Updated');
$('#notice').fadeOut().fadeIn();
}
}
});
// Prevent normal submission of form
return false;
})
});
}
})(jQuery);
// JQUERY: Run .autoSubmit() on all INPUT fields within form
$(function(){
$('#ajax-userForm INPUT').autoSubmit();
});
</script>
<!-- STYLE -->
<style type="text/css">
INPUT { margin-right: 1em }
</style>
</head>
<body>
<!-- CONTENT -->
<?php
$q = intval($_GET['q']);
/*
* DATABASE CONNECTION
*/
// DATABASE: Connection variables
$db_host = "localhost";
$db_name = "DBNAME";
$db_username = "root";
$db_password = "DBPWD";
// DATABASE: Try to connect
if (!$db_connect = mysql_connect($db_host, $db_username, $db_password))
die('Unable to connect to MySQL from ajax-form.');
if (!$db_select = mysql_select_db($db_name, $db_connect))
die('Unable to select database');
/*
* DATABASE QUERY
*/
// DATABASE: Get current row
//$result = mysql_query("SELECT * FROM user");
$result = mysql_query("SELECT * FROM user where Project_ID = '".$q."' ");
$row = mysql_fetch_assoc($result);
?>
<form id="ajax-userForm" class="autosubmit" method="post" action="ajax-updateUser.php">
<fieldset>
<legend>Update user information</legend>
<label>First Name:</label>
<input name="FirstName" value="<?php echo $row['FirstName'] ?>" />
<label>Last Name:</label>
<input name="LastName" value="<?php echo $row['LastName'] ?>" />
<label>Hometown</label>
<input name="Hometown" value="<?php echo $row['Hometown'] ?>" />
<label>Married</label>
<input type = "checkbox" id = "chkMarried" name="Married" <?php echo $row['Married'] == 1 ? 'checked':'unchecked' ?>/>
<label>Employed</label>
<input type = "checkbox" id = "chkEmployed" name="Employed" <?php echo $row['Employed'] == 1 ? 'checked':'unchecked' ?> />
<input id="where" type="hidden" name="Project_ID" value="<?php echo $row['Project_ID'] ?>" />
</fieldset>
</form>
<p id="notice"></p>
</body>
</html>
Code for Page (ajax-updateUser.php) Called by "post" Action in Code Above (ajax-userForm.php):
/*
* DATABASE CONNECTION
*/
// DATABASE: Connection variables
$db_host = "localhost";
$db_name = "DBNAME";
$db_username = "root";
$db_password = "DBPWD";
// DATABASE: Try to connect
if (!$db_connect = mysql_connect($db_host, $db_username, $db_password))
die('Unable to connect to MySQL from ajax-update.');
if (!$db_select = mysql_select_db($db_name, $db_connect))
die('Unable to select database');
$message = "Connection Successful";
//echo "<script type='text/javascript'>alert('$message');</script>";
// DATABASE: Clean data before use
function clean($value)
{
return mysql_real_escape_string($value);
}
/*
* FORM PARSING
*/
// FORM: Variables were posted
if (count($_POST) > 0)
{
$message = count($_POST);
//echo "<script type='text/javascript'>alert('$message');</script>";
// Prepare form variables for database
foreach($_POST as $column => $value)
${$column} = clean($value);
// Perform MySQL UPDATE
$result = mysql_query("UPDATE user SET ".$col."='".$val."'
WHERE ".$w_col."='".$w_val."'")
or die ('Unable to update row.');
}
else
{
$message = "Nothing in Post";
echo "<script type='text/javascript'>alert('$message');</script>";
}
?>
Couple things:
Missing a close quote on your
DBPWD
Your check for status 200 uses:
xmlhttp // whereas the rest is xmlhttp2
My theory, without more context -
You're not using a var keyword when declaring:
xmlhttp2=new XMLHttpRequest();
Which means that the request is attached to the window like this: window.xmlhttp2 = ... - could you be accidentally modifying the same identifiers elsewhere on the "parent" page? That would explain a shared state error and why it works only in isolation (you would have no other code implicitly modding window.xmlhttp2)
You could also be doing bad things with:
xmlhttp2.open("GET","ajax-userForm.php?q="+str,true);
Since I don't know what this path means.
Another one could be, do you have CORS headers set for the request from the external domain?
Cheers,
Andrew

Categories