I have two appointment forms for new patients and already registered patients respectively,
mobile number is used as primary key.
So in the new patient registration we check if that mobile is already present, if yes then shows an error otherwise enter the new data into the tables.
However at present even when I enter a new mobile number it shows "already present" error and also enters the data into db.
so I thought the form was submitting 2 times, but i can't figure out at where this is happening.
my php file code snippet is:
if ($_POST['isnewpatient'] == "true") {
#$name = mysql_real_escape_string(trim($_POST['aaptntname']));
#$email = mysql_real_escape_string(trim($_POST['emlid']));
#$mobile = mysql_real_escape_string(trim($_POST['mobile']));
$qqcSql = "select * from " . WP_eemail_TABLE_SUB
. " where eemail_mobile_sub ='" . trim($_POST['mobile'])
. "' OR eemail_patient_id ='" . trim($_POST['mobile']) . "'";
$qqdata1 = $wpdb->get_results($qqcSql);
var_dump($qqdata1);
if (!empty($qqdata1)) {
$err = 1;
echo "<div id='message' class='aerror'>Already patient details exists. Use your existing patient ID !</div>\n";
}
else {
$pt_id = mysql_real_escape_string(trim($_POST['mobile']));
$sql = "insert query to WP_Appointment";
$wpdb->get_results($sql);
$sqls = "insert query to WP_Appointment_Contact";
$wpdb->get_results($sqls);
$sqql = " insert query to table WP_eemail_Table_Sub";
$wpdb->get_results($sqql);
echo "<div id='message' class='asuccess'>Request has been sent for appointment </div>";
}
}
else {
// Already registered patient form
}
<form name="FormEdit" action="<?php echo the_permalink(); ?>" method="post" onsubmit="return p_appointment()" class="aform">
/* Form part */
</form>
The javascript part
function p_appointment()
{
if($('input:radio[name=new_patient]:checked').val() == "new")
document.FormEdit.isnewpatient.value = "true";
if($('input:radio[name=new_patient]:checked').val() == "old")
document.FormEdit.isnewpatient.value = "false";
document.FormEdit.appsmssend.value = "true";
document.FormEdit.appemailsend.value = "true";
}
change your js method to this:
function p_appointment()
{
if($('input:radio[name=new_patient]:checked').val() == "new")
document.FormEdit.isnewpatient.value = true;
if($('input:radio[name=new_patient]:checked').val() == "old")
document.FormEdit.isnewpatient.value = false;
// document.FormEdit.appsmssend.value = "true";
// document.FormEdit.appemailsend.value = "true"; commented because i did not added these field while testing.
return document.FormEdit.isnewpatient.value;
}
this is what i used as form:
<form name="FormEdit" method="post" onsubmit="return p_appointment()" class="aform">
<input type="text" name="name"/>
<input type="submit" value="submit"/>
</form>
do not use:
if ($_POST['isnewpatient'] == "true") {
}
if ($_POST['isnewpatient'] == "false") {
}
use:
if($_POST['isnewpatient']) {
}else {
}
Related
I am developing a survey form for recreational activities. The user is required to input a location which is then searched in a MYSQL database to ensure that the name entered matches the standard names for locations. The results are to be displayed in a select form to allow the user to choose the specific location.
The query appears to be working correctly. I have verified the return string via an alert window. However, the form appears for a brief second then disappears. I have tried writing the innerHTML string to both a tag and directly to the form. Other posts on this topic that I have found indicated that a form tag is not closed properly. This does not appear to be my problem.
When I run the php script from a test page using hard coded locations, and no other elements on the page, it works just fine.
My js script:
<script> function getLoc(){
var dataRequest;
try {
// Opera 8.0+, Firefox, Safari
dataRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
dataRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
dataRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser needs to be updated to run this
application!");
return false;
}
}
}
dataRequest.onreadystatechange = function() {
if(dataRequest.readyState == 4) {
if (dataRequest.status==200 ||
window.location.href.indexOf("http")==-1){
document.getElementById("locDropDown").innerHTML =
dataRequest.responseText;
}
else{
alert("An error has occured making the request");
}
}
}
var queryString = "";
queryString =
encodeURIComponent(document.getElementById('locStr').value.toUpperCase());
dataRequest.open("POST", "retrieveLoc.php", true);
dataRequest.setRequestHeader("Content-type", "application/x-www-form-
urlencoded");
dataRequest.send("searchValue=" + queryString);
}
</script>
<div>
<form id="floc">
<strong>Where Did You Go:</strong> <input type="text" id = "locStr"
placeholder="location">
<input type="submit" value="Search" onclick="getLoc()">
</form>
</div>
<!-- <div id="dataDiv"> -->
<form id="locDropDown">
</form>
<!-- </div> -->
The relevant portion of my php script:
<?php
$queryStr = htmlspecialchars($_POST['searchValue']);
$queryStr .= "%";
// Check sql
$locSql = "SELECT location FROM `location_lkup` \n"
. "WHERE location LIKE '" .$queryStr. "' \n"
. "ORDER BY `location_lkup`.`location` ASC";
$locRslt = $conn->query($locSql);
//Build Result String
/* $display_string = "<form id = 'locDropDown'>"; */
$display_string .= "<select name = 'locChoices'>";
// If returned records >0 insert a new row in the select form for each loc
returned
if ($locRslt -> num_rows > 0) {
$rowcounter = 1;
while($row = $locRslt -> fetch_array(MYSQLI_ASSOC)) {
$display_string .= "<option value = " . $rowcounter . ">" . $row['location']
. "</option>";
$rowcounter++;
}
}
else {
$display_string .= "<option value = '1'> NO DATA </option>" ;
}
$display_string .= "</select>";
$display_string .= "<input type = 'button' value= 'Select' onclick=
'getSelectedloc()'>";
/* $display_string .= "</form>"; */
echo $display_string;
?>
Any suggestions would be greatly appreciated. Thanks.
Right now, I have a dialog box that pops up when an Add button is clicked. There are 2 inputs inside that will be inserted into the database upon submit. There is a dropdown list and an input box. I do not want the submit on the dialog box to be able to work if a value that is already existing in the database, is entered into the input box. So basically, I do not want there to be any duplicate records in the Supp_ID columns. How can I do this? Here is what I have so far.
Dialog Form:
<div id="dialog-form" title="Add Supplier ID">
<p class="validateTips">All form fields are required.</p>
<!-- Dialog box displayed after add row button is clicked -->
<form >
<fieldset>
<label for="mr_id">MR_ID</label>
<select name="mr_id" id="mr_id_dialog" class="text ui-widget-content ui-corner-all" value="300">
<?php foreach($user1->fetchAll() as $user2) { ?>
<option>
<?php echo $user2['MR_ID'];?>
</option>
<?php } ?>
</select><br><br>
<label for="supplier_id">Supplier ID</label>
<input type="text" name="supp_id" id="supplier_id" class="text ui-widget-content ui-corner-all" value="99">
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" id="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
JavaScript:
$("document").ready(function() {
$('#submit').submit(function() {
processDetails();
return false;
});
});
function processDetails() {
var errors = '';
// Validate Supp ID
var supplier = $("#supplier_id [name='supp_id']").val();
if (supplier == "null" || supplier == "") { // check for empty value
errors += ' - Please enter a different Supplier ID\n';
}
// MORE FORM VALIDATIONS
if (errors) {
errors = 'The following errors occurred:\n' + errors;
alert(errors);
return false;
} else {
// Submit form via Ajax and then reset the form
$("#submit").ajaxSubmit({success:showResult}).resetForm();
return false;
}
}
function showResult(data) {
if (data == 'save_failed') {
alert('ERROR. Your input was not saved.');
return false;
} else if (data == 'save_failed_duplicate') {
alert('ERROR. Input data already exists.');
return false;
} else {
alert('SUCCESS. Your input data has been saved.');
return false;
}
}
Insert.php
<?php
$MR_ID = $_POST['MR_ID'];
$Supp_ID = $_POST['Supp_ID'];
$host="xxxxxxxx";
$dbName="xxxx";
$dbUser="xxxxxxxxxxx";
$dbPass="xxxxxxxxx";
$pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$check_sql = "SELECT Supp_ID FROM Stage_Rebate_Index WHERE Supp_ID = '$Supp_ID'";
$check_sql_query = sqlsrv_query($check_sql, $dbh);
if (sqlsrv_num_rows($check_sql_query) > 0) {
echo "save_failed_duplicate";
#sqlsrv_close($dbh);
return;
} else {
if (sqlsrv_num_rows($check_sql_query) == 0) {
$sql = "INSERT INTO Stage_Rebate_Index (MR_ID, Supp_ID) VALUES (?, '$Supp_ID')";
if (#sqlsrv_query($sql, $dbh)) {
echo "success";
#sqlsrv_close($dbh);
return;
} else {
echo "save_failed";
#sqlsrv_close($dbh);
return;
}
}
}
$stmt = $pdo->prepare($sql);
$result = $stmt->execute(array($MR_ID, $Supp_ID));
echo json_encode($result);
?>
I always use ON DUPLICATE KEY UPDATE in case I want to update a timestamp or something.
$sql = "INSERT INTO Stage_Rebate_Index (MR_ID, Supp_ID) VALUES (?, '$Supp_ID') ON DUPLICATE KEY UPDATE `MR_ID` = `MR_ID`";
Basically, it attempts to insert the record, but if the key exists, it updates whatever data you need. In the above example, it simply updates the MR_ID with the original MR_ID.
Here is a previous question similar to this one: Link
Here is the link the Mysql manual: Link
Use the IGNORE keyword in your SQL statement.
$sql = "INSERT IGNORE INTO Stage_Rebate_Index (MR_ID, Supp_ID) VALUES (?, '$Supp_ID')";
You will need to modify your response to check the number of rows affected instead of whether the query failed.
See: http://php.net/manual/en/pdostatement.rowcount.php
I have a permissions table and I want the ability to check each multiple boxes and a modal window opens with the input fields to edit the permission name. Once I submit I want to update the database with the new names of each input.
Here is what I have so far...
For each box checked I out put this in the modal:
<div class="form-group">
<label>Permission Name</label>
<input class="del-'+row.id+' form-control" id="name['+row.name+']" type="text" name="name['+row.id+']" value="'+row.name+'" >
<input class="del-'+row.id+' form-control" id="id['+row.name+']" type="hidden" name="id['+row.id+']" value="'+row.id+'" >
</div>
Here is what the JS code looks like for the above:
$("#editModalForm").append('<div class="form-group"><label>Permission Name</label><input class="del-'+row.id+' form-control" id="name['+row.name+']" type="text" name="name['+row.id+']" value="'+row.name+'" ><input class="del-'+row.id+' form-control" id="id['+row.name+']" type="hidden" name="id['+row.id+']" value="'+row.id+'" ></div>');
Here is the PHP code when I submit the form:
//Update permission level names
$permissionId = $_POST['id'];
if($permissionDetails['name'] != $_POST['name']) {
$permission = trim($_POST['name']);
$previousName = $permissionDetails['name'];
//Validate new name
if (permissionNameExists($permission)) {
$errors[] = lang("ACCOUNT_PERMISSIONNAME_IN_USE", array($permission));
} elseif (minMaxRange(1, 50, $permission)) {
$errors[] = lang("ACCOUNT_PERMISSION_CHAR_LIMIT", array(1, 50));
} else {
if (updatePermissionNames($permissionId, $permission)) {
$successes[] = lang("PERMISSION_NAME_UPDATE", array($previousName, $permission));
} else {
$errors[] = lang("SQL_ERROR");
}
}
}
Here is the function that updates the database:
//Change a multiple permission level names
function updatePermissionNames($id, $name) {
global $mysqli,$db_table_prefix;
$i = 0;
$stmt = $mysqli->prepare("UPDATE ".$db_table_prefix."permissions
SET name = ?
WHERE
id = ?
LIMIT 1");
foreach($id as $ids) {
$stmt->bind_param("si", $name, $ids);
$result = $stmt->execute();
}
$stmt->close();
return $result;
}
I am not really sure what I am doing wrong here so I am hoping someone can help me out. If you have any examples that would be great. Again, I want to know how I can update each value?
if you want to get value of input with name="id['+row.id+']"
you should do use
$arrID = $_POST['id']
foreach($arrID as $key => $value){
echo $key;
echo $value;
}
because input id[1] is array when post to server, itn't string.
I can't seem to work this one out. Been a few days and still no progress after re-writing it more times than I can count on my hands.
Here is the Javascript (On same page as html)
Summary: User types text into the input box. That gets sent off to be processed, which then gets sent back and displayed on the screen in the box ID'd as DisplayText on the html page.
<script type="text/javascript">
function SendText() {
if (document.getElementById("Text").innerHTML == "") {
return;
} else
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("DisplayText").innerHTML = xmlhttp.responseText;
}
}
Text = document.getElementById("Text").value;
xmlhttp.open("GET", "php/Test.php?Chat=" + Text, true);
xmlhttp.send();
}
}
</script>
Here is the HTML (Same page as the script)
<div>
<p>
<span id="DisplayText">
TEXT GOES HERE
</span>
</p>
</div>
<form action="" onsubmit="SendText();">
<input type="" name="" id="Text" />
<input type="submit" value="Send" name="Send" />
</form>
The PHP code is here
<?php
session_start();
include ("Connect.php");
$Connection = mysqli_connect("localhost", "root", "", "chatsystem");
$Create = "CREATE TABLE " . $_SESSION["Username"] . "Chat(Username VARCHAR(255), Chat VARCHAR(255))";
////////////////////////////////////////////////////////////////////////////////
$DatabaseExist = $Connection->query("SELECT 1 FROM " . $_SESSION["Username"] . "Chat");
if ($DatabaseExist !== false) {
echo "Database exists";
doSomething();
} else {
echo "Database does not exist";
mysqli_query($Connection, $Create);
doSomething();
}
////////////////////////////////////////////////////////////////////////////////
function doSomething() {
// Get the sent chat
$Input = $_REQUEST["Chat"];
// Insert into the database the new chat sent
mysqli_query($Connection, "INSERT INTO " . $_SESSION["Username"] . "chat (`Username`, `Chat`) VALUES ('$_SESSION[Username], '$Input')");
// Select everything from the database
$Result = $Connection->query("SELECT * FROM " . $_SESSION["Username"] . "Chat");
// Display everything from the database in an orderly fashion
// --
// For the length of the database
// Append to a variable the next table row
// --
while ($Row = $Result->fetch_array()) {
// Make Variable accessable
global $Input;
// Append username to the return value
$Input = $Input . $Row["Username"] . " : ";
// Append chat to the return value
$Input = $Input . $Row["Chat"] . "<br />";
}
}
// Will return the value
echo $Input;
?>
My connection to the Database is fine. I'm using it on other pages that work.
So lets assume that's not the problem. :P
Any help or insight from anyone who knows or can think of something that is wrong, I would be very grateful for.
I'm new to AJAX.
You do a wrong test with
if (document.getElementById("Text").innerHTML == "")
It should be the same way you use to get the text for sending in the AJAX
if (document.getElementById("Text").value == "")
So check its value property and not its innerHTML as input elements do not have html content..
Be careful though because your code is wide-open to SQL injection attacks.
1st : use input's value property instead innerHTML
eg. use
if (document.getElementById("Text").value == "")
instead of
if (document.getElementById("Text").innerHTML == "")
2nd : use return false; at the form's onsubmit event; to prevent current page to be refreshed as you are using ajax. Otherwise the page will get refreshed and it wont display the php page's output,
eg. use
onsubmit="SendText(); return false;"
instead of just
onsubmit="SendText();"
Try AJAX Long Polling technique for chat application. Here is example
http://portal.bluejack.binus.ac.id/tutorials/webchatapplicationusinglong-pollingtechnologywithphpandajax
So I've been spending hours on finding something specific to my issue, but I can't seem to find any.
I'm in the middle of creating a small CMS. My problem is that I don't know how to make a submitted form in a UI dialog to do the action of PHP_SELF inside of the UI dialog. I have a list of user which can be selected by a radio button. There is a delete button which has some javascript attached:
$('#delete_user').on('click', function(e) {
if (id != null ) {
var url = "delete_user.php?id=" + id;
$('#dialog-placeholder').dialog().load(url);
$('.ui-dialog :button').blur();
}
e.preventDefault();
return false;
});
Now, my problem is that I have made it to the UI dialog where i get the ID sent with the url, but I have no idea how to send a form and still keep it in the dialog with the underneath PHP:
<?php
if ((isset($_GET['id'])) && is_numeric($_GET['id'])) {
$id = $_GET['id'];
} elseif ((isset($_POST['id'])) && is_numeric($_POST['id'])) {
$id = $_POST['id'];
} else {
echo "<p>An error has occurred. Please try again.</p>";
echo "Close";
$jQuery_close = <<<msg
<script>
$('.close_dialog').on('click', function(){
location.reload();
dialog("close");
});
</script>
msg;
echo $jQuery_close;
exit();
}
require('includes/db_con.php'); //making a connection to the database
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($_POST['sure'] == 'Yes') {
$q = "DELETE FROM users WHERE user_id=$id LIMIT 1";
$r = #mysqli_query($dbc, $q);
if (mysqli_affected_rows($dbc) == 1) {
echo "<p>The user has been deleted</p>";
} else {
echo "<p>The user could not be deleted due to system error. Please try again.</p>";
}
} else {
echo "The user has NOT been deleted!";
}
} else {
$q = "SELECT email, CONCAT(firstname, ' ',lastname) AS name FROM users WHERE user_id='$id'";
$r = #mysqli_query($dbc, $q);
$num = mysqli_num_rows($r);
if ($num = 1) {
while ($row = mysqli_fetch_array($r, MYSQL_ASSOC)) {
echo "<p>Are you sure you want to delete this user?</p>";
echo $row['email'] . '<br />';
echo $row['name'];
}
echo '<form action="' . $_SERVER["PHP_SELF"] . '" method="post">
<input type="HIDDEN" name="id" value="' . $id .'" />
<input type="submit" name="sure" value="Yes" />
<input type="submit" name="sure" value="No" />
</form>';
} else {
echo "This page has been accessed in error";
}
}
mysqli_close($dbc);
?>
When pressing "yes" or "no" in the form, it just directly goes to a new page.
My question is, how do I fire the php and send the form within the dialog?
Place your e.preventDefault() at the start of the delete click handler, not at the end where you currently have it, it should be like this:
$('#delete_user').on('click', function(e) {
e.preventDefault();
if (id != null ) {
var url = "delete_user.php?id=" + id;
$('#dialog-placeholder').dialog().load(url);
$('.ui-dialog :button').blur();
}
return false;
});