$_POST empty when using $.post - php

Here is my problem:
I want to make a database search using PHP form. I have my form and I want it to work even if there are some empty fields (as like more fields u fill, the more specific answer u get). I am using Jquery to first get values from my form and then send it by $.post to my actual php file which connects with database and do the search. I am simply giving empty fields some specific value which is recognized in my php file as 'empty' field so i can make a proper sql query. The problem is I find my $_post variables empty, even though variables in Jquesry script are set properly. I am using this method in other cases and it works fine. I have no idea if this matter but I am loading my form inside my main div using Jquery as well. The alert(data) function does its job: in prompt window i can see my results of search but reloading profile.php gives me nothing. Here is my code:
form:
<script type="text/javascript" src="scripts/admin.js"></script>
<form id="form_admin">
<table cellpadding="0" cellspacing="0" width="180">
<p style="line-height: 2cm; ">
<tr>
<td width="50" class="label1">Imię:</td>
<td>
<input id="imie" type="text" value="">
</td>
</tr>
<tr>
<td width="50" class="label1">Nazwisko:</td>
<td>
<input id="nazwisko" type="text" value="">
</td>
</tr>
<tr>
<td width="50" class="label1">Numer telefonu:</td>
<td>
<input id="telefon" type="text" value="">
</td>
</tr>
<tr>
<td align="center" colspan="2">
<input type="button" id="register" value="Pokaż!">
<br>
</td>
</tr>
</p>
</table>
</form>
admin.js
$(document).ready(function () {
$("#register").click(function () {
if ($("#imie").val() != "") {
var imie = $("#imie").val();
} else {
var imie = 'nic';
}
if ($("#nazwisko").val() != "") {
var nazwisko = $("#nazwisko").val();
} else {
var nazwisko = 'nic';
}
if ($("#telefon").val() != "") {
var telefon = $("#telefon").val();
} else {
var telefon = 'nic';
}
$.post("profile.php", {
name: imie,
surname: nazwisko,
telephone: telefon
}, function (data) {
alert(data);
});
$("#main").load('profile.php');
});
});
profile.php
<? php
include('config.php');#logging into database
if (isset($_POST['name']) && isset($_POST['surname']) && isset($_POST['telephone'])) {
$IMIE = $_POST['name'];
$NAZWISKO = $_POST['surname'];
$TELEFON = $_POST['telephone'];#then my sql queries go...
while ($user = mysql_fetch_assoc($select)) {
echo 'ORDER_ID zamówienia: '.$user['ORDERINFO_ID'];
echo 'DATA zamówienia: '.$user['DATE_PLACED'];
}
while ($user = mysql_fetch_assoc($select2)) {
echo 'SUBORDER_ID: '.$user['SUBITEM_ID'];
echo 'Ilość: '.$user['QUANTITY'];
echo 'Koszt zamówienia: '.$user['COST'];
}
} else {
echo "$_POST variables aren't set";
}
?>
Edit:
I have installed Firebug and checked POST profile.php after submitted data and it contains all variables as expected.

Try changing your $.post function to:
$.post("profile.php", {
data: "&name=" + imie + "&surname=" + nazwisko + "&telephone=" + telefon
}, function (data) {
alert(data);
});

Your inputs do not have any name
for example:
<input id="imie" type="text" value="" name="imie">

Related

Fetch result from Database using Ajax

I want to display info and disable a process button if a certain condition is not met at the point of entering the value(onblur or onkeyup event). I have tried many example but none has given me result. Can someone help me out
The Ajax code:
<script type="text/javascript" src="includes/scripts/newJquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("select.custid").change(function () {
var selectedCustomer = $("#amt").val();
var selectedCustId = $("#custid").val();
$.ajax({
type: "POST",
url: "process-loan.php",
data: {
custQual: selectedCustomer,
custid: selectedCustId
}
}).done(function (data) {
$("#qualify").html(data);
});
});
});
</script>
Below is the php page
<th>Customer No:</th>
<td>
<select name="custid" class="custid" id="custid">
<option>Select Customer No</option>
<?php while ($rw = mysqli_fetch_array($get)) { ?>
<option value="<?php echo $rw['custid'] ?>"><?php echo $rw['custid'] ?></option>
<?php } ?>
</select>
</td>
<tr>
<th>Requesting Amount:</th>
<td><input type="number" name="amount" value="0.00" id="amt"/></td>
</tr>
<tr>
<td id="qualify"> </td>
<td id="qualify"> </td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="save" value="Process Loan" class="btn btn-success" id="pButton"/>
The process-loan.php script that will respond to the ajax call:
<?php
if (isset($_POST["amt"])) {
include 'includes/session.php';
include 'includes/db_connection.php';
$amt = $_GET["amt"];
$custid = $_POST["custid"];
// Query the Databased based on the amount and the UserId
if ($amt !== NULL) {
$gets = "SELECT * FROM tab_customer_dailycontribution WHERE custid='" . $custid . "' AND transactionDate BETWEEN '2015-09-01' AND '2015-09-30'";
$get = mysqli_query($connection, $gets);
$sum = 0.00;
while ($row = mysqli_fetch_array($get)) {
$sum += $row['amountContribute'];
}
if ($sum >= $amt) {
//qualify for loan $ enable the Process Button to save
echo "You are Qualify to Apply";
} else {
//disqualify for loan $ disable the process button until condition is meant.
echo "Insufficient Fund: Unqualify to Apply";
}
//end if condition
}
}
?>
this is for demo so i have commented tour mysql related things:first change your keys in process-loan.php.
your view page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#pButton").hide();
$("#amt").on("blur",function(){
var selectedCustomer = $("#amt").val();
var selectedCustId = $("#custid").val();
$.ajax({
type: "POST",
url:"process-loan.php",
data:{custQual:selectedCustomer,custid:selectedCustId},
success:function(data){
var data=JSON.parse(data);
$("#qualify").html(data.msg);//your message
if(data.status == 0){
$("#pButton").show();//showing button if qualified
}else{
$("#pButton").hide();
}
}
});
});
});
</script>
<th>Customer No:</th>
<td><select name="custid" class="custid" id="custid">
<option>Select Customer No</option>
<?php $i =0; while($i <4){?>
<option value="<?php echo $i?>"><?php echo $i?></option>
<?php $i++;}?></select></td>
<tr>
<th>Requesting Amount:</th>
<td><input type="number" name="amount" value="0.00" id="amt"/></td>
</tr>
<tr>
<td ><div id="qualify"></div></td><!-- added div in td to show message it can be outside of your table !-->
<td> </td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="save" value="Process Loan" class="btn btn-success" id="pButton"/>
process-loan.php
<?php
if(isset($_POST["custQual"])){
// include 'includes/session.php';
// include 'includes/db_connection.php';
$amt = $_POST["custQual"];//here use $_POST not $_GET
$custid = $_POST["custid"];
// Query the Databased based on the amount and the UserId
if($amt !== NULL){
$sum=100000;//static value for demo
if($sum >= $amt){
//qualify for loan $ enable the Process Button to save
$res["status"]=0;
$res["msg"]="You are Qualify to Apply";
}else{
//disqualify for loan $ disable the process button until condition is meant.
$res["status"]=1;
$res["msg"]= "Insufficient Fund: Unqualify to Apply";
}//end if condition
}else{
$res["status"]=1;
$res["msg"]= "put some amount first";
}
echo json_encode($res);
}

multiple submit on same page with php ajax

<div id="home">
<div class="container">
<form action="" method="post">
<b><font color = "000099"><select name="category" id="category">
<option>Name </option>
<option>Email</option>
<option>Employee</option>
<option>Customer</option>
</select></font></b>
<b><font color = "000099"><select name="read" id="read">
<option>New</option>
<option>Archive</option>
</select></b>
<font color = "339933"><b><input name="value" type="text" placeholder="Value" /> </b>
<input type="submit" value="GO"/></font><br>
</form>
<font color = "339933"><b>
</b></font>
<p><div id="body">
<table width="98%" border="1">
<tr></tr>
<tr>
<td><font color = "339933"><b>Name</td>
<td><font color = "339933"><b>E-Mail </td>
<td><font color = "339933"><b>Access</td>
<td><font color = "339933"><b>Update </td>
</tr>
<?php
$read = $_POST['read'];
If($read == 'New'){
$read = '0';
}
If($read == 'Archive'){
$read = '1';
$arc = 'AND date < CURDATE() - INTERVAL 90 DAY';
}
$category = $_POST['category'];
$value = $_POST['value'];
if($category == 'Name'){
$where = " where name like '%$value%' ";
}else if($category == 'E-mail'){
$where = " where Email like '%$value%' ";
}else if($category == 'Employee'){
$where = " where Email like '%$value%' ";
}else if($category == 'Customer'){
$where = " where Email not like '%$value%' ";
}
$select = 'SELECT *';
$from = ' FROM users';
if($where == ''){
$where = ' WHERE TRUE ';
}
$order = " order by id desc limit 100";
if($read == '0'){
$sql = $select . $from . $where . $order ;
}else{
$sql = $select . $from . $where . $arc . $order ;
}
$result_set=mysql_query($sql);
while($row=mysql_fetch_array($result_set)) {
?>
<tr>
<form method="post" name="forms" action="">
<td><font color = Black><?php echo $row['name']; ?></td>
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
<td><input type="text" name="access_rights" class="form-control" value="<?php echo $row['access']; ?>" required="required" ></td>
<td><input type="submit" class="submit_button" id="submit_button" name="submit_button" value="Update"/></td>
</form>
<?php } ?>
</table>
</div>
</body>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
alert('asfsfsds');
var ID = $(this).attr("id");
var dataString1 = 'msg_id='+ ID;
var mail = $("#remail").val();
var mailid = 'remail='+ mail;
var textcontent = $("#access_rights").val();
var dataString = 'access_rights='+ textcontent;
if(textcontent==''){
alert("Enter some Value..");
$("#access_rights").focus();
} else {
$.ajax({
type: "POST",
url: "action.php",
data: dataString,mailid,dataString1,
cache: true,
success: function(html){
document.getElementById('access_rights').value='';
$("#access_rights").focus();
}
});
}
return false;
});
});
</script>
</html>
Above is my php ajax code. I want to one field in mysql database by ajax.
There are multiple submit button on the page. Let me explain you properly.
Below code is used for sorting the value on the page. This value retrieve from database. This is working fine. I can get the data from database and it is showing in the same page.
<form action="" method="post">
<b><font color = "000099">
<select name="category" id="category">
<option>Name </option>
<option>Email</option>
<option>Employee</option>
<option>Customer</option>
</select>
</font></b>
<b><font color = "000099">
<select name="read" id="read">
<option>New</option>
<option>Archive</option>
</select>
</b>
<font color = "339933"><b><input name="value" type="text" placeholder="Value" /></b>
<input type="submit" value="GO"/></font><br>
</form>
In below code data is showing from database and one text box and submit button will display in table.
<form method="post" name="forms" action="">
<tr>
<td><font color = Black><?php echo $row['name']; ?></td>
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
<td><input type="text" name="access_rights" class="form-control" value="<?php echo $row['access'];?>" required="required" ></td>
<td><input type="submit" class="submit_button" id="submit_button" name="submit_button" value="Update"/></td>
</tr>
</form>
I want user with special permission can update the value by ajax because there could be multiple rows and it is not good to page get refreshed each time.
At the moment after clicking on update button ajax event not firing.
Can anybody advise me on this. I am not good in ajax.
There may be other issues, but the following line is syntactically incorrect:
data: dataString,mailid,dataString1,
That is not how you concatenate a string in Javascript. Plus, you would need to separate the name=value pairs with ampersands.
Instead of concatenating a string, you can use an object and let JQuery do the concatenating:
data: {
'access_rights': $("#access_rights").val(),
'remail': $("#remail").val(),
'msg_id': $(this).attr("id")
},
UPDATE:
You don't have an element with id="access_rights. You do have an element with id="remail", but you create that element in a loop, so you will have multiple elements with that id.
You need to get the values of the elements that are in the same row as the clicked submit button. You can't do that using id values. Instead, you use .closest('tr') on the button element to get the surrounding row. You can then use .find() on the row element to get the values in that row.
Change:
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
To:
<td><font color="Black" class="remail"><?php echo $row['Email']; ?></td>
Then you can have:
$(".submit_button").click(function() {
var $submitBtn = $(this),
$row = $(this).closest('tr'),
$accessRights = $row.find("input[name=access_rights]"),
accessRights = $accessRights.val();
if (accessRights == ''){
alert("Enter some Value..");
$accessRights.focus();
} else {
$.ajax({
type: "POST",
url: "action.php",
data: {
'access_rights': accessRights,
'remail': $row.find(".remail").text(),
'msg_id': $submitBtn.attr("id")
},
cache: true,
success: function(html){
$accessRights.val('').focus();
}
});
}
return false;
});
You are also missing the closing </tr> tag.

How to get rid from spam MySQL insert?

I really wonder that how someone adding records to my existing blog comment table. I am using my own custom blog script where user add comment on any particular blog. I have a separate comment table with blog id. I have tried several CAPTCHA technique but nothing works. I am using PDO for mysql. I am also doing JavaScript validation before submitting the form. I am not sure if he/she is real people or some bots are doing that. Within 1 hour thousands of records being added.
I am posing my code below. Can someone help me please?
<?php
if(isset($_POST['user_comment']))
{
if ($_SESSION['answer'] == $_POST['answer'] )
{
$name = $_POST['name'];
$email = $_POST['email'];
$website = $_POST['website'];
$web = $website;
$comment = addslashes(nl2br($_POST['comment_text']));
$comment =strip_tags($comment);
$id = $article_id;
$ref = $_SERVER["HTTP_REFERER"];
$userip = $_SERVER['REMOTE_ADDR'];
$useragent = $_SERVER['HTTP_USER_AGENT'];
$submit_date = date('Y-m-d H:i:s');
if ((($name) && ($email) && ($comment))) {
$conn = new PDO("mysql:host=$hostname;dbname=$database",$username,$password);
$sql = "INSERT INTO blog_comments (user,email,website,message,date,storyid,userip,useragent,block) VALUES (:user,:email,:website,:message,:date,:storyid,:userip,:useragent,:block)";
$q = $conn->prepare($sql);
$q->execute(array(':user'=>$name, ':email'=>$email, ':website'=>$website, ':message'=>$title, ':date'=>$submit_date, ':storyid'=>$id, ':userip'=>$userip, ':useragent'=>$useragent,':block'=>'1'));
}
}
else
{
?>
<tr><td>
<p style="text-align:center; color:#CC0000; font-size:14px; font-weight:bold; padding-bottom:10px;">Wrong Answer! Please try again!!</p>
</td>
</tr>
<?php
}
}
?>
THIS IS MY CAPTCHA CODE:
<?php
session_start();
$digit1 = mt_rand(1,20);
$digit2 = mt_rand(1,20);
if( mt_rand(0,1) === 1 ) {
$math = "$digit1 + $digit2";
$_SESSION['answer'] = $digit1 + $digit2;
} else {
$math = "$digit1 - $digit2";
$_SESSION['answer'] = $digit1 - $digit2;
}
?>
THIS IS JS VALIDATION:
<script type="text/javascript" language="javascript">
function validate()
{
if( document.getElementById( "name" ).value == ""){
alert("Please enter your name.");
document.getElementById( "name" ).focus();
return false;
}
if( document.getElementById( "email" ).value == ""){
alert("Please enter Your email ID.");
document.getElementById( "email" ).focus();
return false;
}
if( document.getElementById( "comment_text" ).value == ""){
alert("Please enter your comment.");
document.getElementById( "comment_text" ).focus();
return false;
}
if( document.getElementById( "answer" ).value == ""){
alert("Please solve this math.");
document.getElementById("answer").focus();
return false;
}
}
</script>
THIS IS MY FORM:
<form action="" method="POST" onSubmit="return validate();">
<table cellpadding="5" cellspacing="5" width="100%">
<tr><td colspan="3">
<input type="hidden" name="id" value="<? print($id);?>">
</td></tr>
<tr>
<td style="font-size:12px; font-weight:bold; width:150px;">Your Name</td>
<td style="width:260px;"><input type="text" name="name" id="name" style="width:250px; height:20px;"></td>
<td style="text-align:left;">Required</td>
</tr>
<tr>
<td style="font-size:12px; font-weight:bold; width:150px;">Your E-mail</td>
<td style="width:260px;"><input type="text" name="email" id="email" style="width:250px; height:20px;"></td>
<td style="text-align:left;">Required</td>
</tr>
<tr>
<td style="font-size:12px; font-weight:bold; width:150px;">Your Website</td>
<td style="width:260px;"><input type="text" name="website" style="width:250px; height:20px;"></td>
<td style="text-align:left;">Optional</td>
</tr>
<tr>
<td style="font-size:12px; font-weight:bold; width:150px;">Your Comment</td>
<td style="width:260px;"><textarea name="comment_text" id="comment_text" style="width:250px; height:100px;"></textarea></td>
<td style="text-align:left;">Required</td>
</tr>
<tr>
<td style="font-size:12px; font-weight:bold; width:150px;">What's <?php echo $math; ?> = </td>
<td style="width:260px;"><input type="text" name="answer" id="answer" style="width:250px; height:20px;"></td>
<td style="text-align:left;">Required</td>
</tr>
<tr>
<td colspan="3" style="text-align:center;">
<input type="submit" class="submit" value="Submit" name="user_comment">
</td></tr>
</table>
</form>
I would suggest you to select from db previous record of a user with posted email and compare the content or the date with posted data. If the content is the same or date range is very small, than show approving message for posting or do something like that.
Your Captcha is not very safe. Any Bot can give you the answere.
What's <?php echo $math; ?> =
This will only shown as Text What's x + y = answer is z.
Every Bot and every self written Javascript can fill all requireds fields and get the "question" and fill it in the answer field.
And i guess that if you hit F5 in your browser after you post a comment, the php script will also save it in your DB, because the answer in your session is not deleted after one try.
Try to print an image with the question instead of a text and delete the answer in your Session after first try.
This should solve the problem.
After all I have found the solution myself. Now I am showing the last commented date time instead of CAPTCHA and asking user to input that value as it is in input box. All captcha techniques failed whereas this technique works perfectly and i am not getting spam any more.
Thanks you so much to all you experts for giving your valuable suggestions.

Why the form submitted using AJAX is redirecting to next page and the error/success messages are not displayed into alert on the same page?

I'm using PHP, Smarty, jQuery, AJAX, etc. for my website.Following is HTML code of my form which I'm submitting using AJAX:
<form name="question_issue_form" id="question_issue_form" action="http://localhost/xyz/pqr/web/control/modules/questions/question_issue.php">
<input type="hidden" name="form_submitted" id="form_submitted" value="yes"/>
<input type="hidden" name="op" id="op" value="question_issue"/>
<input type="hidden" name="question_id" id="question_id" value="35718"/>
<table class="trnsction_details" width="100%" cellpadding="5">
<tbody>
<tr>
<td></td>
<td>
<input type="checkbox" name = "que_issue[]" value = "Question is wrong" id ="chkQueWrong">Question is wrong</input>
</td>
</tr>
<tr>
<td></td>
<td><input type="checkbox" name = "que_issue[]" value = "Answers are wrong" id ="chkAnsWrong">Answers are wrong</input></td>
</tr>
<tr>
<td></td>
<td><input type="checkbox" name = "que_issue[]" value = "Question direction is incorrect" id ="chkDirIncorrect">Question direction is incorrecct</input></td>
</tr>
<tr>
<td></td>
<td><input type="checkbox" name = "que_issue[]" value = "Other" id ="chkOther">Other</input></td>
</tr>
<tr>
<td></td>
<td class="set_message" style="display:none;"><textarea name="que_issue_comment" id = "que_issue_comment" rows="4" cols="25" maxlength="100"></textarea></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Submit" id="report_question_issue" class="c-btn submit_form"/></td>
</tr>
</tbody>
</table>
</form>
The AJAX code for submitting the form is as follows:
$(document).ready(function() {
$('#question_issue_form').submit(function() {
var ans = confirm("Are you sure to report the question issue?");
if (!ans) {
return false;
}
var post_url = $(this).attr('action');
$.ajax({
type: "POST",
url: post_url,
data: $('#question_issue_form').serialize(),
dataType: 'json',
success: function(data) { alert(data);
var error = data.error_message;
if(error)
alert(error);
else {
alert("Question issue has been reported successfully.");
$.colorbox.close();
}
}
});
});
});
The PHP code of a file(question_issue.php) where I'm submitting this form is as follows:
<?php
require_once("../../includes/application-header.php");
$objQuestionIssue = new QuestionIssue();
prepare_request();
$request = $_POST ;
$user_type = $_SESSION[SESSION_NAME_CONTROL][STAFF_TYPE];
if($user_type == 'super_admin' || $user_type == 'admin' || $user_type == 'data_entry_operator' || $user_type == 'owner' || $user_type == 'faculty' || $user_type == 'content_development_head' || $user_type == 'test_admin' || $user_type == 'student_admin')
$requested_user_type = 'staff';
else
$requested_user_type = 'student';
$form_data = array();
$form_data['question_id'] = $request['question_id'];
$form_data['reported_site_id'] = SITE_ID;
$form_data['reported_user_type'] = $requested_user_type;
$form_data['reported_user_id'] = $_SESSION[SESSION_NAME_CONTROL][STAFF_ID];
$form_data['que_issue'] = implode(",", $request['que_issue']);
$form_data['que_issue_comment'] = $request['que_issue_comment'];
$form_data['que_issue_date'] = time();
switch( $op ) {
case "question_issue":
if($request['form_submitted']=='yes') {
$ret = $objQuestionIssue->InsertQuetionIssue($form_data, $question_issue_error_messages);
/*If condition : If there are any errors in submission of a report question form*/
if(!$ret) {
$error_msg = $objQuestionIssue->GetAllErrors();
$data = array();
$data['error_message'] = $error_msg['error_msgs'];
$data = json_encode($data);
echo $data;
die;
/*Else condition : If there is no error in submission of a report question form*/
} else {
$data = array();
$data['success_message'] = "success";
$data = json_encode($data);
echo $data;
die;
}
} else {
$smarty->assign('question_id', $request['question_id']);
$file_to_show = 'question-issue.tpl';
}
$smarty->display($file_to_show);
break;
die;
}
?>
The issue I'm facing is when I click on Ok button of confirmation alert, the form gets submit but the error messages or success messages in json format are appearing on a blank screen.
Actually they should be appeared in a pop-up alert and page should not get redirected to other URL. But the error/success messages are printing on a blank white page and page is also redirected to the question_issue.php. Can someone please help me in avoiding these things and showing the error/success messages into an alert box on the same page?
I think you should prevent default behavior of the form, so it won't really submit but only ask for json:
$('#question_issue_form').submit(function(e) {
e.preventDefault();
// your code

Setting value to textbox using PHP with help of Javascript

What I intend to do is a dialog box will prompt and the user will input his username, when clicked OK, the php codes inside the javascript function mySearch will get his details in mysql and display it in the textbox. HELP. T_T It won't work.
<script>
function mySearch()
{ var name = prompt("Search","Enter username");
if (name!=null && name!="")
{
var sentval = document.getElementById("sentval");
sentval.value = name;
<?php
$myLink = mysql_connect('localhost','root', '1234') or die(mysql_error());
$selectDB = mysql_select_db('proj2db', $myLink) or die(mysql_error());
$sql = "SELECT * FROM userTBL WHERE uName ='".$_POST['sentval']."'";
$exec = mysql_query($sql, $myLink);
$row = mysql_fetch_array($exec);
$uname = $row['uName'];
$pwd = $row['pwd'];
$code = $row['sAns'];
$link = $row['path'];
?>
}
}
</script>
</head>
<body>
<form method="post" action="" name="myform" id="myform">
<input type="hidden" id="sentval"/>
<center>
<table>
<tr>
<td><font face="Tahoma" size = "2" color="#0B3861">Username:&nbsp&nbsp</font></td>
<td>
<input type = "text" id = "uname" name = "uname" size="35" value="<?php echo $uname ?>"/>
<button type="button" style="height: 25px; width: 60px" onclick="mySearch()">Search</button>
</td>
</tr>
<tr>
<td><font face="Tahoma" size = "2" color="#0B3861">Password:&nbsp&nbsp</font></td>
<td><input type = "password" id = "pwd" name = "pwd" size="35" value="<?php echo $pwd ?>"/></td>
</tr>
<tr>
<td><font face="Tahoma" size = "2" color="#0B3861">Re-type Password:&nbsp&nbsp</font></td>
<td><input type = "password" id = "repwd" name = "repwd" size="35" value="<?php echo $pwd ?>"/></td>
</tr>
<tr>
<td><font face="Tahoma" size = "2" color="#0B3861">Code:&nbsp&nbsp</font></td>
<td><input type = "text" id = "code" name = "code" size="35" value="<?php echo $code ?>"/></td>
</tr>
<tr>
<td><font face="Tahoma" size = "2" color="#0B3861">Link:&nbsp&nbsp</font></td>
<td><input type = "text" id = "link" name = "link" size="35" value="<?php echo $link ?>"/></td>
</tr>
<tr>
<td colspan=2 align="right">
<font face="Tahoma" size = "2" color="#0B3861">(e.g. http://www.google.com or index.php)</font>
</td>
</tr>
<tr>
<td colspan=2 align="right">
<input type="submit" name="submit" value="Save" style="height: 25px; width: 60px"/>
<button type="button" style="height: 25px; width: 60px" onclick="location.href='adminMain.php'">Cancel</button>
</td>
</tr>
</table>
</center>
</form>
</body>
<?php
if (!empty($_POST['uname']) && !empty($_POST['pwd']) && !empty($_POST['repwd']) && !empty($_POST['code']) && !empty($_POST['link']))
{
if ($_POST['pwd'] == $_POST['repwd'])
{
$myLink = mysql_connect('localhost','root', '1234') or die(mysql_error());
$selectDB = mysql_select_db('proj2db', $myLink) or die(mysql_error());
$sql = "UPDATE `proj2db`.`usertbl` SET pwd='".$_POST['pwd']."', sAns='".$_POST['code']."', path='".$_POST['link']."' WHERE uName='".$_POST['uname']."';";
$exec = mysql_query($sql, $myLink);
}
else
echo "<font face='Tahoma' size = '2' color='red'><center>Error: Password mismatched <br> Press cancel to return to home page </center></font>";
}
?>
You seem to be confused as to the presence of PHP and JavaScript. Javascript is strictly client-side (barring node.JS), and PHP is strictly server-side. You can't inline-combine both of them the way you've done - or at least not in how you expect it to work. Right now, the PHP code will run regardless the moment the user has visited the page.
Here's a solution for you (it relies on jQuery, so you'll need a copy of it). I've also switched you to PDO to make your life a bit easier and show you how to transition away from mysql_query.
Keep your <body> code almost the same. The only difference is the mySearch() function, as follows:
<script type='text/javascript'>
function mySearch() {
var uname = prompt("Search","Enter username");
if (uname !== undefined && uname.length > 0) {
$.ajax({
url: "ajax.form.php",
type: "POST",
dataType: "json",
data: { sentval: uname },
success: function(d) {
if (d.length > 0) {
$("#uname").val(d[0].uName);
$("#pwd").val(d[0].pwd);
$("#code").val(d[0].sAns);
$("#link").val(d[0].path);
}
else {
alert("Not found");
}
}
});
}
}
</script>
To do this, you will also need another PHP script. I named it ajax.form.php. The content:
<?php
try {
$DB = new PDO("mysql:host=localhost;dbname=proj2db","root","1234");
} catch (Exception $e) {
die("Could not connect: ".$e->getMessage());
}
$DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!empty($_POST['sentval'])) {
$q = $DB->prepare("SELECT * FROM userTBL WHERE uName = :username");
$q->bindValue(":username",$_POST['sentval']);
$q->execute();
if (($r = $q->fetch()) !== false) {
echo json_encode(array($r));
}
else {
echo "[]";
}
} ?>
And that's it! It should work, though I have written this on-the-fly and have not tested it. The idea behind it:
JavaScript calls the other PHP script with sentval through $.ajax()
PHP runs
PHP returns an array of rows (in this case, just one, but the script works just as well by changing fetch() to fetch_all() and removing the Array() in json_encode) to JavaScript
JavaScript parses and updates the client's form.

Categories