I'm trying to add a listener into the 'Yes' button which is shown in the code below.I want this function to save this boolean value into approval field in my database like:$query_row['approval']==1; and a message to display on it.But when executing the code nothing happens after clicking on the'Yes button'.
Can someone please show me how to fix this code if there is an error on it?
Thanks in advance!
This is my code:
<html >
<head>
<title></title>
</head>
<body>
<?php
if( !($database=mysql_connect("localhost","root",""))||!(mysql_select_db("st_login",$database)) )
print("Could not connect");
$result = mysql_query("SELECT * FROM `login` WHERE `admin` = 0 AND `approval`=0");
// if($_POST['admin']==0) {//perjashton administratorin
if(mysql_num_rows($result) == 0) {//esht aprovuar llogaria
if(!($result=mysql_query($query,$database)))
{
print("Could not execute query");
die (mysql_error());//ose error
}
//nese esht aprovuar logini i st.
echo "You are approved";
}
else //approval=0
echo"YOU HAVE NEW REQUESTS WAITING FOR APPROVAL IN YOUR WEBSITE!!!<br />";
while($query_row=mysql_fetch_assoc($result)){
$firstname=$query_row['firstname'];
$lastname=$query_row['lastname'];
$username=$query_row['username'];
$password=$query_row['password'];
$email=$query_row['email'];
$cv=$query_row['cv'];
echo $firstname.' '.$lastname.' has this cv:'.$cv.'<br /> Do you want to approve his account?
<button id="but">Yes</button><button>No</button><br />
<p id="demo"></p>';
?>
<script>
document.getElementById("but").addEventListener("click", MyFunction());
function MyFunction() {
$query_row['approval']==1;
document.getElementById("demo").innerHTML = "This account is approved";}
</script>
<?php
}mysql_close($database);
?>
</body>
</html>
And this is my database with the approval field which boolean value I'm trying to change:
Change document...addEventListener("click", MyFunction()); to document...addEventListener("click", MyFunction); otherwise your function executes immediately and only once.
You can't modify a value in the database only with changing value of the output array. You have to create a new php file and call it asynchronuslly. Read more about updating values in the database here and about calling files asynchronuslly here.
First, I will edit your main file because it's a mess (sorry to say that, but don't worry, it was same with me):
<html>
<head>
<title></title>
<script>
function MyFunction(id) {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
if(xhttp.responseText.indexOf("UPDATE WENT OK")!=-1)
document.getElementById(id).nextSibling.innerHTML = "This account is approved";
}
else {
document.getElementById(id).nextSibling.innerHTML = "An error occured while approving this account";
}
}
xhttp.open("GET", "ajax_file.php?id="+id, true);
xhttp.send();
}
</script>
</head>
<body>
<?php
if(!($database = mysql_connect("localhost","root","")) || !(mysql_select_db("st_login",$database)))
print("Could not connect");
else {
$result = mysql_query($database,"SELECT * FROM `login` WHERE `admin` = 0 AND `approval`=0");
if(!$result){
print("Could not execute query");
die (mysql_error());//ose error
}
else{
if(mysql_num_rows($result) == 0) {//esht aprovuar llogaria
//nese esht aprovuar logini i st.
echo "You are approved";
}
else { //approval=0
echo"YOU HAVE NEW REQUESTS WAITING FOR APPROVAL IN YOUR WEBSITE!!!<br/>";
while($query_row=mysql_fetch_assoc($result)){
$firstname=$query_row['firstname'];
$lastname=$query_row['lastname'];
$username=$query_row['username'];
$password=$query_row['password'];
$email=$query_row['email'];
$cv=$query_row['cv'];
echo $firstname.' '.$lastname.' has this cv:'.$cv.'<br /> Do you want to approve his account?';
?><div class="container"><button id="<?php echo $query_row['id'];?>" onclick="MyFunction(this.id)">Yes</button><button>No</button><br />
<p class="demo"></p></div><?php
}
}
}
}
mysql_close($database);
?>
</body>
</html>
Now, create a php file named ajax_file.php (in the same folder):
<?php
if(!($database = mysql_connect("localhost","root","")) || !(mysql_select_db("st_login",$database)))
die("Could not connect");
else {
$id = intval($_GET['id']);
$result = mysql_query($database,"UPDATE table `login` SET approval = 1 WHERE `id` = '".$id."'");
if(!$result){
print("Could not execute query");
die (mysql_error());//ose error
}
else{
echo "UPDATE WENT OK";
}
Do not hesitate to ask me about any detail how this works. Also, this might not be correct because i don't exactly know what you are doing or want to do with the file you provided. But, if you'll give me the details, I will edit it so it will work.
Related
I am having problems creating a PHP session following a successful AJAX call. Here is the AJAX code:
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var id = profile.getId();
var em = profile.getEmail();
var name = profile.getName();
var pic = profile.getImageUrl();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('confirm-login').style.display = 'block';
}
};
xhttp.open("GET", "./assets/inc/profile.php?id="+id+"&e="+em+"&n="+name+"&p="+pic, true);
xhttp.send();
}
This part works perfectly. I only include it for completeness sake.
Here's the contents of profile.php
<?php
$id = $_GET["id"];
$email = $_GET["e"];
$name = $_GET["n"];
$pic = $_GET["p"];
require_once("db.php");
$result = $mysqli->query("SELECT googleid FROM user_tbl WHERE googleid = '$id' LIMIT 1");
if($result->num_rows == 0) {
$sql = "INSERT INTO user_tbl (googleid, email, fullname, pic, loc) VALUES ('$id', '$email', '$name', '$pic', '')";
if (mysqli_query($mysqli, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "" . mysqli_error($mysqli);
}
} else {
echo "already exists";
}
$mysqli->close();
session_start();
$_SESSION['gid'] = $id;
?>
All of this code works except for session_start(); and $_SESSION['gid'] = $id; when I return to another PHP page (which correctly has session_start(); at the very top of the page) the variable has not been created in profile.php
Any help as to what I'm doing wrong would be much appreicated.
You can't start a session after the script has sent output. (There should have been output to that effect; if there wasn't, try changing PHP's warnings.) The session_start() call must come before any echo call that is actually executed.
On an unrelated topic, you will want to learn how to escape your database parameters.
I am trying to change the content of my php web page using ajax as below
the index.php page has input filed that call a function to executed on the button click but my problem is that the page is reload it
so i want to know what I am doing wrong??
Note that i am using the post requests to keep my data secure as w3schools.com recommended
inexd.php file code below
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Site Title</title>
</head>
<body align="left">
<div>
<h4 align="left">Balance Enquiry</h4>
</div>
<form>
<div>
<label>Account Number </label>
<input id="AccNum" type="text" name="AccNumInput">
<button type="button" onclick="SendForm()">Search</button>
</div>
</form>
<script>
function SendForm()
{
alert("Hello! SendForm start");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("AccNum").innerHTML = xmlhttp.responseText;
}
};
alert("Hello! going to send ajax");
var x = xmlhttp.open("POST","AccData.php", true);
xmlhttp.send(document.getElementById("AccNum").value); // you want to pass the Value so u need the .value at the end!!!
alert(document.getElementById("AccNum").value);
alert("Hello! SendForm end");
}
</script>
</body>
</html>
The data.php file code below
<?php
alert("Hello! php start processing");
$AccountNumber = $_POST['AccNum'];
$conn = oci_connect('admin', 'admin', 'localhost/JDT', 'AL32UTF8');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
alert("Hello! connected to oracle");
$sqlstr = 'SELECT CUSTOMER_ID,CUST_NAME,PHONE1 FROM customers where CUSTOMER_ID=:AccNum';
$stid = oci_parse($conn, $sqlstr); // creates the statement
oci_bind_by_name($stid, ':AccNum', $AccountNumber); // binds the parameter
oci_execute($stid); // executes the query
echo $AccountNumber;
/**
* THIS WHILE LOOP CREATES ALL OF YOUR HTML (its no good solution to echo data out like this)
*/
while ($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) {
echo "<tr>";
foreach ($row as $item) {
echo "<td align=center>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid); // releases the statement
oci_close($conn); // closes the conneciton
?>
With the <input type="submit" value="Search"> your sending the form the "old" way to the server not with Ajax!
<form>
<div>
<label>Account Number </label>
<input id="AccNum" type="text" name="AccNuminput">
<button type="button" onclick="sendForm()">Search</button>
</div>
</form>
<script>
function sendForm(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//Execudted when finished and everything its Okay
document.getElementById("AccNum").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("POST", "acc_data.php", true);
xmlhttp.send("accNum="+document.getElementById("AccNum").value); // you want to pass the Value so u need the .value at the end!!!
}
</script>
Then in your data.php you do not need any html you just need to process the the data that you received by the ajax post request(Session is also not needed for that) . In the xmlhttp.responseText you are receiving your answer from the server when the request is finished.
<?php
$accountNumber = $_POST['accNum'];// set a good variable name
$conn = oci_connect('admin', 'admin', 'localhost/JDT', 'AL32UTF8'); //setup connection
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR); // throws an error on connection error
}
$sqlstr = 'SELECT CUSTOMER_ID,CUST_NAME,PHONE1 FROM customers where CUSTOMER_ID=:ACCNUM'; // sql stirng
$stid = oci_parse($conn, $sqlstr); // creates the statement
oci_bind_by_name($stid, ':ACCNUM', $accountNumber); // binds the parameter
oci_execute($stid); // executes the query
/**
* THIS WHILE LOOP CREATES ALL OF YOUR HTML (its no good solution to echo data out like this)
*/
while ($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) {
echo "<tr>";
foreach ($row as $item) {
echo "<td align=center>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid); // releases the statement
oci_close($conn); // closes the conneciton
?>
Basically, what i'm trying to do in pseudo-code is this:
if button_1_press {
if connection_doesnt_exist{
create_connection
echo "connected"
}
else {
echo "still connected"
}
}
if button_2_press{
if connection_exist{
close_connection
echo "disconnected"
}
else {
echo "still disconnected"
}
}
I tryed some approaches, the best i have so far is this:
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type='text/javascript' src='script.js'></script>
<title>PHP AJAX Example</title>
</head>
<body>
<input type='submit' onclick='makeRequest();' value='Connect' id='b1'/>
<input type='submit' onclick='makeRequest();' value='Disconnect' id='b2'/>
<div id='ResponseDiv'>
This is a div to hold the response.
</div>
</body>
</html>
Javascript:
var xmlHttp = createXMLHttpRequest();
function createXMLHttpRequest(){
var xmlHttp;
if (window.ActiveXObject){
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
xmlHttp = false;
}
}
else {
try {
xmlHttp = new XMLHttpRequest();
}
catch(e) {
xmlHttp = false;
}
}
if(!xmlHttp){
alert("Error creating the XMLHttpRequest object.");
}
else{
return xmlHttp;
}
}
function makeRequest(){
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4){
HandleResponse();
}
}
document.getElementById("b1").onclick = function () {xmlHttp.open("GET", "mysql.php?button=1", true); xmlHttp.send(null);}
document.getElementById("b2").onclick = function () {xmlHttp.open("GET", "mysql.php?button=2", true); xmlHttp.send(null);}
}
function HandleResponse(){
response = xmlHttp.responseText;
document.getElementById('ResponseDiv').innerHTML = response;
}
PHP
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$conn = new mysqli($servername, $username, $password);
if ($_GET['button']==1){
if ($conn){
echo "already connected";
}
else {
$conn = new mysqli($servername, $username, $password);
echo " connected";
}
}
if ($_GET['button']==2){
if ($conn){
echo "disconnected";
$conn->close();
}
else {
echo "still disconnected";
}
}
?>
My problems are:
1) When any of the buttons is clicked for the first time, it does nothing; only starts working from the second click.
2) Button "Connected" always shows "already connected".
3) Button "Disconnect" always shows "disconnected"
What I understand is this happen because every time a button is pressed, the makeRequest function makes an AJAX call, which creates a mysqli connection every time, so at the moment of evaluate if its open, it always will be true, but I have no idea how to fix it.
This totally pointless.
By default PHP shuts down/cleans up all open connections when a script exits. So every time you do an AJAX request to test the db connection, you'd be opening a NEW database connection anyways, never testing a previous connection.
You COULD use persistent DB connections, but even with that there's no guarantee you'd get the SAME connection as you got last time. You'd get some randomish connection from a pool of open connections, which against is pointless to test.
And going with persistent connections opens a huge pile of problems as well. The microscopic benefits of going persistent is vastly dwarved by all the problems it'll cause.
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
This is a follow up of another question I asked last night. My problem now is not that the script doesn't works, but that I'm getting some very strange repeat of an HTML input element when my xmlhttprequest object returns the response text. Here's the code:
<!DOCTYPE HTML>
<?php
if(!empty($_GET['uName']))
{
$r = mysql_connect("localhost", "root", "pass") or die("Couldn't connect to db");
mysql_select_db("db", $r) or die ("Couldn't select db");
$q = mysql_query("select * from users where uName = '{$_GET['uName']}'") or die("Couldn't query table");
$data = mysql_fetch_assoc($q);
mysql_close($r);
}
?>
<html>
<head>
</head>
<body>
<form>
<input type="text" name="fUName" onchange="ShowUser(fUName.value);" value="name" style="width:125px;">
</form>
<div id="display"><?php print "ID = {$data['id']}"; ?></div>
</body>
</html>
<script type='text/javascript'>
function ShowUser(name)
{
if(name.length == 0)
{
document.getElementById("display").innerHTML = "Please enter a username to check";
return;
}
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("display").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "index.php?uName=" + name, true);
xmlhttp.send();
}
</script>
Here's the strange problem:
There should only be one input field, and is orginally, however when I enter text into it and it loses focus, the JS is triggered and also prints out another input field.
Please ignore the bad practice of PHP, JS and HTML/CSS in one script, this was supposed to be a quick test that has turned for the worse :)
I'm baffled!
Thanks for any help.
The problem lies in the fact that all of your code is in one page. Consider this: you load up index.php. After it's all displaying then you call this same page again (for your AJAX request) so you're essentially saying "Hey, I want you to try and load this page again," hence why you're ending up with duplicate fields.
Try separating out your files in to something like index.php and getuser.php or something of the sort.