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:  </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:  </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:  </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:  </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:  </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.
Related
I'm developing a Wordpress plugin using PHP and jQuery, the function below is called when the <select> input is changed, so far it works as intended and the inputs are generated properly but when I submit the form, the generated elements are undefined when called in $_POST.
<?php
function random_event() {
global $wpdb;
//Table for all the event details
$tablename = $wpdb->prefix."random_event";
// Table to store all banner stores
$tablename2 = $wpdb->prefix."random_event_banner_stores";
//Table for store all poster
$tablename4 = $wpdb->prefix."random_event_poster";
// Table storing all user registrations
$tablename3 = $wpdb->prefix."random_event_winners";
//Junction table to map the poster to banner store
$tablename5 = $wpdb->prefix."random_event_poster_banner";
//Junction table to map the poster to event
$tablename6 = $wpdb->prefix."random_event_poster_event";
$tablename5 = $wpdb->prefix."random_event_poster_banner";
$sql = "select event.*, banner.name as banner_name, banner.id as banner_id from $tablename as event left join $tablename2 as banner on banner.id = event.store_id";
$results = $wpdb->get_results($sql);
$update_this_event = -1;
$banner_stores = [];
//Deletion
if(isset($_POST['delete_event'])) {
$event_id = esc_sql($_POST['event_id']);
$sql = "DELETE from $tablename WHERE id= '" . $event_id . "'";
try{
$event = $wpdb->query($sql);
}
catch (Exception $e) {
echo "<script>console.log($e);</script>";
}
} else if(isset($_POST['update_event'])){
$update_this_event = intval(esc_sql($_POST['event_id']));
$banner_store_id = esc_sql($_POST['banner_id']);
$name = esc_sql($_POST['banner_store_name']);
$description = esc_sql($_POST['banner_store_description']);
$location_note = esc_sql($_POST['banner_store_location_note']);
$address = esc_sql($_POST['banner_store_address']);
$status = esc_sql($_POST['banner_store_status']);
$sql = "UPDATE $tablename SET name = '" . $name . "'
, description = '" . $description . "'
, location_note = '" . $location_note . "'
, address = '" . $address . "'
, status = '" . $status . "' WHERE id = '" . $banner_store_id . "'";
try{
$participants = $wpdb->query($sql);
}
catch (Exception $e) {
echo "<script>console.log($e);</script>";
}
} else if(isset($_POST['select_update_event'])){
$update_this_event = intval(esc_sql($_POST['event_id']));
// $pssql = "select * from $tablename2";
// $banner_stores = $wpdb->get_results($pssql);
$pssql = "select $tablename2.* from $tablename2 left join $tablename on $tablename2.id = $tablename.store_id where $tablename.store_id is null";
// $pssql = "select * from $tablename2";
$banner_stores = $wpdb->get_results($pssql);
$pssql2 = "select $tablename2.* from $tablename2 left join $tablename on $tablename2.id = $tablename.store_id where $tablename.id = '".$update_this_event."'";
$current_banner_store = $wpdb->get_results($pssql2);
if(count($current_banner_store) != 0) {
array_push($banner_stores, $current_banner_store[0]);
}
$poster_sql = "select ap.*, a.name as poster_name, ap.qty as qty from $tablename6 as ap inner join $tablename4 as a on a.id = ap.poster_id where ap.event_id = $update_this_event";
$poster_event = $wpdb->get_results($poster_sql);
$poster_petone = [];
foreach($results as $result) {
if($result->id == $update_this_event) {
$poster_sql = "select a.* from $tablename5 as ap inner join $tablename4 as a on a.id = ap.poster_id where banner_store_id = ".$result->store_id;
$poster_petone = $wpdb->get_results($poster_sql);
}
}
}else if(isset($_POST['cancel_update_event'])){
$update_this_event = -1;
}else if (isset($_POST['save_update_event'])) {
$update_this_event = intval(esc_sql($_POST['event_id']));
$title = esc_sql($_POST['title']);
$qty = 0;
$description = esc_sql($_POST['description']);
$prize = esc_sql($_POST['prize']);
$event_code = esc_sql($_POST['event_code']);
$event_from = esc_sql($_POST['event_from']);
$event_to = esc_sql($_POST['event_to']);
$banner_store_id = esc_sql($_POST['banner_store_id']);
if(isset($_POST['poster_ids'])){
$poster_ids = $_POST['poster_ids'];
$poster_qtys = $_POST['poster_qty'];
}
$query = "UPDATE $tablename set title='$title',description='$description',event_code='$event_code',valid_from='$event_from',valid_to='$event_to',store_id='$banner_store_id', prize = '$prize' ";
$query .= "where id = $update_this_event";
$result_insert = $wpdb->query($query);
$delete_query = "delete from $tablename6 where event_id = $update_this_event";
$wpdb->query($delete_query);
for($i = 0; $i < count($poster_ids); $i++) {
$poster_id = esc_sql($poster_ids[$i]);
$poster_qty = esc_sql($poster_qtys[$i]);
$poster_query = "INSERT INTO $tablename6 (event_id,poster_id, qty) values ";
$poster_query .= "('$update_this_event','$poster_id','$poster_qty');";
$poster_insert = $wpdb->get_results($poster_query);
$poster_result = $wpdb->insert_id;
}
$update_this_event = -1;
$sql = "select event.*, banner.name as banner_name, banner.id as banner_id from $tablename as event left join $tablename2 as banner on banner.id = event.store_id";
$results = $wpdb->get_results($sql);
}
?>
<style type="text/css" emb-not-inline="">
.table-container {
width: 100%;
max-width: 100%;
overflow-x: auto;
}
.hidden {
display: none;
}
.banner-button {
background-color: #ffffff;
border-radius: 5px;
padding: 5px;
font-size: 13px;
min-width: 75px;
}
table {
border: none;
text-align: center;
}
table tr:nth-child(even) {
background-color: #dddddd;
}
table tr:nth-child(odd) {
background-color: #ffffff;
}
table th {
background-color: #23282d;
color: #ffffff;
}
table th:first-child{
border-radius: 20px 0px 0px 0px;
}
table th:last-child{
border-radius: 0px 20px 0px 0px;
}
table {
border-radius: 20px 20px 0px 0px;
}
</style>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<h1>View All events</h1>
<br/>
<div class="table-container" style="
width: 100%;
max-width: 100%;
overflow-x: auto;
">
<table cellpadding="10" border=1 style="border-style: solid #AAA">
<tr>
<th>Title</th>
<th>Description</th>
<th>Prize</th>
<th>event Code</th>
<th>banner Store</th>
<th>poster Qty</th>
<th>Validity</th>
<th>QR code</th>
<th>Action</th>
</tr>
<?php
foreach($results as $result) {
if($update_this_event == $result->id) { ?>
<tr>
<form method="post" name="formtest1" id="formtest1">
<td valign="top"><input type="text" name="title" value="<?php echo $result->title ?>"/> </td>
<td valign="top"><input type="text" name="description" value="<?php echo $result->description ?>"/> </td>
<td valign="top"><input type="text" name="prize" value="<?php echo $result->prize ?>"/> </td>
<td valign="top"><input type="text" name="event_code" value="<?php echo $result->event_code ?>"/> </td>
<td valign="top">
<!-- <select onChange="changebanner(this)" id="banner_store_id" name="banner_store_id"> -->
<select id="banner_store_id" name="banner_store_id">
<?php
foreach($banner_stores as $pstore) {
if($result->banner_id == $pstore->id) {
?>
<option SELECTED value="<?php echo $pstore->id?>"> <?php echo $pstore->name ?></option>
<?php
}else {
?>
<option value="<?php echo $pstore->id?>"> <?php echo $pstore->name ?></option>
<?php
}
}
?>
</select>
</td>
<td valign="top">
<div id="poster_div">
<table border="0" cellpadding=5>
<?php
if(count($poster_event) == 0) {
for($i = 0; $i < count($poster_petone); $i++)
{
?>
<tr>
<td>
<input type="hidden" name="poster_ids[]" value="<?php echo $poster_petone[$i]->id?>"><?php echo $poster_petone[$i]->name?>
</td>
<td>
<input type="text" name="poster_qty[]" placeholder= "Qty Allocation" value="<?php echo $poster_petone[$i]->qty ?>">
</td>
</tr>
<?php
}
}else {
for($i = 0; $i < count($poster_event); $i++)
{
?>
<tr>
<td><input type="hidden" name="poster_ids[]" value="<?php echo $poster_event[$i]->poster_id?>"><?php echo $poster_event[$i]->poster_name?></td>
<td><input type="text" name="poster_qty[]" placeholder= "Qty Allocation" value="<?php echo $poster_event[$i]->qty?>"></td>
</tr>
<?php
}
}?>
</table>
</div>
</td>
<td valign="top"><input id="event_from" name="event_from" type="text" value="<?php echo $result->valid_from ?>"/> - <input name="event_to" id="event_to" type="text" value="<?php echo $result->valid_to ?>"/> </td>
<td valign="top"></td>
<td valign="top">
<input type="hidden" name="event_id" value="<?php echo $result->id ?> ">
<input type="submit" name="save_update_event" value="save" class="banner-button">
<input type="submit" name="cancel_update_event" value="cancel" class="banner-button">
</td>
</form>
</tr>
<?php
} else {
?>
<tr>
<td valign="top"><?php echo $result->title ?> </td>
<td valign="top"><?php echo $result->description ?> </td>
<td valign="top"><?php echo $result->prize ?> </td>
<td valign="top"><?php echo $result->event_code ?> </td>
<td valign="top"><?php echo $result->banner_name ?> </td>
<td valign="top"><?php get_poster_of_event($result->id ) ?> </td>
<td valign="top"><?php echo $result->valid_from ?> - <?php echo $result->valid_to ?></td>
<td valign="top"><?php generate_random("https://generic.com/event/?random=".$result->event_code, $result->title) ?> </td>
<td valign="top">
<form method="post" name="formtest" id="formtest">
<input type="hidden" name="event_id" value="<?php echo $result->id ?> "/>
<input type="submit" name="delete_event" value="delete" class="banner-button"/>
</form>
<form method="post" name="formtest" id="formtest">
<input type="hidden" name="event_id" value="<?php echo $result->id ?> "/>
<input type="submit" name="select_update_event" value="update" class="banner-button"/>
</form>
</td>
</tr>
<?php
}
}
?>
</table>
</div>
<script>
let jQueryNC = jQuery.noConflict();
jQueryNC( function() {
jQueryNC( "#event_to" ).datepicker({ dateFormat: 'yy-mm-dd' });
jQueryNC( "#event_from" ).datepicker({ dateFormat: 'yy-mm-dd' });
} );
jQueryNC("body").on("change", "#banner_store_id", function() {
changebanner(jQueryNC(this));
});
function changebanner(e){
let jQueryNC = jQuery.noConflict();
jQueryNC( "#poster_div" ).html("Loading...");
let formData = new FormData(); // creates an object, optionally fill from <form>
let value = jQueryNC("#banner_store_id").val();
console.log(e.value);
formData.append('poster_id', value);
formData.append('action', 'get_poster');
let xhr = new XMLHttpRequest();
xhr.open("POST", "/admin/admin-post.php");
xhr.send(formData);
xhr.onload = () => {
let posters = JSON.parse(xhr.response);
let htmldiv = '<table border=0 cellpadding=5>';
for(let i = 0; i < posters.length; i++)
{
htmldiv += '<tr>';
htmldiv += '<td><input type="hidden" name="poster_ids[]" value="'+posters[i].id+'">'+posters[i].name+'</td>';
htmldiv += '<td><input type="text" name="poster_qty[]" placeholder= "Qty Allocation" value="'+posters[i].qty+'"></td>';
htmldiv += '</tr>';
}
htmldiv += '</table>';
jQueryNC("#poster_div").html(htmldiv);
}
}
</script>
<?php
} ?>
Clarification: when the select input is not changed, the inputs inside container div are recognized upon submitting without any errors, but when the contents of container div are changed via changebanner; the new inputs and tables are created but if it is submitted, the inputs like poster_ids[] is not recognized by $_POST['poster_ids']
EDIT added the entire code in hopes of clarifying the problem
I tried to explain the issue in my comments but maybe it will be easier to see here.
Your initial form on page load has a bunch of inputs etc in it, including some poster_ids and poster_qty.
If you submit that form, by clicking the submit button, a standard HTML form submission via POST happens. All the inputs that exist in the form on page load will be sent in the request, and your PHP will get all of them.
But if you don't submit the form, and instead change the selected #banner_store_id option, some Javascript takes over. That JS will do a few things:
Create an empty formData object, ignoring everything currently in your form;
Add 2 new key/value pairs to that formData
POST those 2 values to your PHP. Note this is not a standard HTML POST like the one that happens when you click submit, it is an AJAX POST. It is essentially independent of the <form> on the page, and it will only POST the fields from the form if you specifically add them. The code you have does not do that, and so does not include any of your existing form fields.
If you try to use $_POST['poster_ids'] in the PHP which receives this JS POST, it will fail, because those fields were not in the request. The only things there are a poster_id and an action.
If you do want to include all the fields in your form in the data you POST via JS when changing #banner_store_id, you need to create a formData with the form itself, as shown in the docs:
let myForm = document.getElementById('formtest1');
let formData = new FormData(myForm);
If you do this, then all the inputs on your form are bundled up and included in that formData, and just like with the normal POST will all be sent to your PHP.
Here's the relevant part of your code, commented to explain it further:
function changebanner(e) {
// Create a new FormData object - **NOTE** it is empty! You have not passed
// in your existing form, so none of the form inputs already on the page are
// in FormData. If you POSTed it right away $_POST would be completely empty.
let formData = new FormData();
// Now add 2 items to it
formData.append('poster_id', value);
formData.append('action', 'get_poster');
// Now make your POST, and send formData, which has just those 2 items
let xhr = new XMLHttpRequest();
xhr.open("POST", "/admin/admin-post.php");
xhr.send(formData);
// The POST is done, you sent poster_id and action and nothing else to your PHP
}
Try taking out the onchange(this) in the select and instead use the jQuery on.("change").
Without seeing the exact error or what you have tried it is hard to say exactly but trying to access a variable that has not be created yet often gives an undefined because you are trying to access it before it exists. By using the jQuery on function you can find things added after DOM has loaded.
Good luck.
$("body").on("change", "#data_store_id", function() {
changeSELECTED($(this));
});
function changeSELECTED(e) {
let jQueryNC = jQuery.noConflict();
jQueryNC("#container_div").html("Loading...");
let formData = new FormData(); // creates an object, optionally fill from <form>
formData.append('data_id', e.value);
formData.append('action', 'get_data');
let xhr = new XMLHttpRequest();
xhr.open("POST", "/adminfolder/admin-post.php");
xhr.send(formData);
xhr.onload = () => {
let datas = JSON.parse(xhr.response);
let htmldiv = '<table border=0 cellpadding=5>';
for (let i = 0; i < datas.length; i++) {
htmldiv += '<tr>';
htmldiv += '<td><input type="hidden" name="data_ids[]" value="' + datas[i].id + '">' + datas[i].name + '</td>';
htmldiv += '<td><input type="text" name="data_qty[]" placeholder= "Qty Allocation" value="' + datas[i].qty + '"></td>';
htmldiv += '</tr>';
}
htmldiv += '</table>';
jQueryNC("#container_div").html(htmldiv);
}
}
<select id="data_store_id" name="data_store_id">
<?php
foreach($data_stores as $dstore) {
if($result->data_id == $dstore->id) {
?>
<option SELECTED value="<?php echo $dstore->id?>">
<?php echo $dstore->name ?>
</option>
<?php
}else {
?>
<option value="<?php echo $dstore->id?>">
<?php echo $dstore->name ?>
</option>
<?php
}
}
?>
</select>
<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.
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">
I'm having a strange problem. I have a HTML page with PHP code which inserts data to a MySQL database. The data gets saved to the DB without any errors but in an incorrect order.
Here's a screenshot. The table on the right side displays the existing records. The first 2 records are shown correctly.
But when I save more records, it displays like this.
Even in the MySQL table, the records are inserted that way.
I'm not sure where exactly the problem is so I've shown the whole code for the page below. I've commented what each code block does. Please comment if you need me to clarify something.
The Location ID is an auto-generated code.
<html>
<head>
<script language="javascript">
function SelectAll(source)
{ //The code for the 'Select All' checkbox
checkboxes = document.getElementsByTagName("input");
for(var i in checkboxes)
{
if(checkboxes[i].type == 'checkbox')
{
checkboxes[i].checked = source.checked;
}
}
}
</script>
</head>
<body>
<?php
//Database connection initialization
require_once("db_handler.php");
$conn = iniCon();
$db = selectDB($conn);
/* Generating the new Location ID */
$query = "SELECT LID FROM locations ORDER BY LID DESC LIMIT 1";
$result = mysql_query($query, $conn);
$row = mysql_fetch_array($result);
$last_id = $row['LID'];
$id_letter = substr($last_id, 0, 1);
$id_num = substr($last_id, 1) + 1;
$id_num = str_pad($id_num, 3, "0", STR_PAD_LEFT);
//$id_num = sprintf("%03d", $id_num);
$new_id = $id_letter . $id_num;
/* Displaying the exsisting locations */
$query = "SELECT * FROM locations";
$result = mysql_query($query, $conn);
$count = mysql_num_rows($result);
?>
<! The table which displays the existing records >
<div id="display">
<b>Locations</b><br/><br/>
<form name="displayLocs" action="<?php echo $PHP_SELF; ?>" method="post" >
<table border="1">
<tr>
<th>Location ID</th>
<th>Code</th>
<th>Location</th>
<th><i>Delete</i></th>
</tr>
<?php
while($row = mysql_fetch_array($result))
{
?>
<tr>
<td align="center"><? echo $row["LID"]; ?></td>
<td align="center"><? echo $row["Code"]; ?></td>
<td><? echo $row["Location"]; ?></td>
<td align="center"><input type="checkbox" name="checkbox[]" value="<? echo $row["LID"]; ?>" /></td>
</tr>
<?php
}
?>
</table>
<br/>
<div id="buttons2">
<input type="checkbox" onclick="SelectAll(this)" />Select All <input type="reset" value="Clear" /> <input type="submit" value="Delete" name="deletebtn" />
</div>
</form>
</div>
<! New record saving area >
<b id="loc_caption_1">Enter a new location</b>
<div id="loca">
<form name="locForm" action="<?php echo $PHP_SELF; ?>" method="post" >
<table width="300" border="0">
<tr>
<td>Location ID</td>
<td><input type="text" name="lid" readonly="readonly" value="<?php echo $new_id; ?>" style="text-align:right" /></td>
</tr>
<tr>
<td>Code</td>
<td><input type="text" name="code" style="text-align:right" /></td>
</tr>
<tr>
<td>Location</td>
<td><input type="text" name="loc" style="text-align:right" /></td>
</tr>
</table>
</div>
<br/>
<div id="buttons">
<input type="reset" value="Clear" /> <input type="submit" value="Save" name="savebtn" />
</div>
</form>
<?php
//Saving record
if(isset($_POST["savebtn"]))
{
$id = $_POST["lid"];
$code = $_POST["code"];
$location = $_POST["loc"];
$query = "INSERT INTO locations(LID, Code, Location) VALUES('$id', '$code', '$location')";
$result = mysql_query($query, $conn);
if (!$result)
{
die("Error " . mysql_error());
}
else
{
echo "<br/><br/>";
echo "<strong>1 record added successfully!</strong>";
echo "<meta http-equiv=\"refresh\" content=\"3;URL=locations.php\">";
}
mysql_close($conn);
}
//Deleting selected records
if(isset($_POST["deletebtn"]))
{
for($i = 0; $i < $count; $i++)
{
$del_id = $_POST["checkbox"][$i];
$query = "DELETE FROM locations WHERE LID = '$del_id' ";
$result = mysql_query($query, $conn);
}
if (!$result)
{
die("Error " . mysql_error());
}
else
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=locations.php\">";
}
mysql_close($conn);
}
?>
</body>
</html>
Can anyone please tell me what is causing this and how to rectify it.
Thank you.
The records in the database are stored in the database in no particular order (well, there's some order to it, but it's up to the engine to determine it). If you want to get the results in a particular order, then you need to explicitly specify it when querying the data. In your case, make this change:
/* Displaying the exsisting locations */
$query = "SELECT * FROM locations ORDER BY lid";
$result = mysql_query($query, $conn);
I need some js/ajax/jquery script saving data to database dynamically when I check the check-box.
the checkboxes at the moment or loaded in next to records and change the variable in the database depending if its checked or not.but i have to reload the page after i select one to save it to the database. i can do everything else but understand how to implement the ajax to this so i don't have to submit the query and refresh the page every time. any help is greatly appreciated.
<form name="form1aa" method="post" action="process.php?fn=<? echo $rows['first']; ?>&class=<?php echo $rows['class']; ?>&last=<?php echo $rows['last']; ?>
&model=<?php echo $rows['model']; ?>&cas=<?php echo $rows['cases']; ?>&upid=<?php echo $id; ?>&group=1" id="form1a" >
<select name="type" onchange=" fill_damage (document.form1aa.type.selectedIndex); ">
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
</select>
<select name="damage">
</select>
<input type=text name="comment" placeholder="Comments Box">
<input type=text name="cost" placeholder="Cost">
<input type="submit" value="Save" name="Save">
</form>
<?php
//Job Status
if(isset($_POST['checkbox'])){$checkbox = $_POST['checkbox'];
if(isset($_POST['activate'])?$activate = $_POST["activate"]:$deactivate = $_POST["deactivate"])
$id = "('" . implode( "','", $checkbox ) . "');" ;
$sql="UPDATE repairs SET status = '".(isset($activate)?'Completed':'In Progress')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Job Status
//Payment Status
if(isset($_POST['paycheck'])){$paycheck = $_POST['paycheck'];
if(isset($_POST['paid'])?$paid = $_POST["paid"]:$unpaid = $_POST["unpaid"])
$id = "('" . implode( "','", $paycheck ) . "');" ;
$sql="UPDATE repairs SET paid = '".(isset($paid)?'Paid':'Unpaid')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Payment Status
//Return Status
if(isset($_POST['retcheck'])){$retcheck = $_POST['retcheck'];
if(isset($_POST['ret'])?$ret = $_POST["ret"]:$unret = $_POST["unret"])
$id = "('" . implode( "','", $retcheck ) . "');" ;
$sql="UPDATE repairs SET ret = '".(isset($ret)?'Retuned':'In Office')."' WHERE id=$id" ;
$result = mysql_query($sql) or die(mysql_error());
}
//End Return Status
$sql="SELECT * FROM $tbl_name";
if(isset($_POST['all'])){
$sql="SELECT * FROM $tbl_name";
}
if(isset($_POST['tpc'])){
$sql="select * from $tbl_name WHERE class LIKE '1%'";
}
if(isset($_POST['drc'])){
$sql="select * from $tbl_name WHERE class LIKE 'D%'";
}
if(isset($_POST['bsc'])){
$sql="select * from $tbl_name WHERE class LIKE 'B%'";
}
$result=mysql_query($sql);
?>
<form name="frmactive" method="post" action="">
<input name="activate" type="submit" id="activate" value="Complete Job" />
<input name="paid" type="submit" id="Payment" value="Payment Status" />
<input name="ret" type="submit" id="ret" value="Returned 2 Student" />
<br />
<a id="displayText" href="javascript:toggle();">Show Extra</a>
<div id="toggleText" style="display: none">
<br />
<input name="unret" type="submit" id="unret" value="In Office" />
<input name="unpaid" type="submit" id="unpaid" value="Not Paid" />
<input name="deactivate" type="submit" id="deactivate" value="In Progress" /></div>
<table width="1000" border="0" cellpadding="3" cellspacing="1">
<thead>
<th width="67" align="center"><strong>Start Date</strong></th>
<th width="50" align="center"><strong>Cases</strong></th>
<th width="34" align="center"><strong>Type</strong></th>
<th width="120" align="center"><strong>Damage</strong></th>
<th width="31" align="center"><strong>Comment</strong></th>
<th width="31" align="center"><strong>Cost</strong></th>
<th width="90" align="center"><strong>Payment Status</strong></th>
<th width="100" align="center"><strong>Returned 2 Student</strong></th>
<th width="100" align="center"><strong>Job Status</strong></th>
</thead>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><? echo $rows['start']; ?></td>
<td><? echo $rows['cases']; ?></td>
<td><? echo $rows['type']; ?></td>
<td width="70"><? echo $rows['damage']; ?></td>
<td width="70"><? echo $rows['comment']; ?></td>
<td><? echo "$"; echo $rows['cost']; ?></td>
<!--Payment Display(Start)-->
<?php
if($rows['paid']=="Paid")
{
?>
<td><input name="paycheck[]" type="checkbox" id="paycheck[]" value="<? echo $rows['id']; ?>">
<? echo $rows['paid'];?>
</td>
<?
}
if($rows['paid']=="Unpaid")
{
?>
<td width="21"><input name="paycheck[]" type="checkbox" id="paycheck[]" value="<? echo $rows['id']; ?>">
<? echo $rows['paid']; ?>
</td>
<?
}
if($rows['ret']==""){
?>
<td width="50">No Data</td>
<?
}
?>
Do it with jQuery, a simple example could be:
HTML:
<input type="checkbox" name="option1" value="Milk">
<input type="checkbox" name="option2" value="Sugar">
<input type="checkbox" name="option3" value="Chocolate">
JS:
$("input[type='checkbox']").on('click', function(){
var checked = $(this).attr('checked');
if(checked){
var value = $(this).val();
$.post('file.php', { value:value }, function(data){
// data = 0 - means that there was an error
// data = 1 - means that everything is ok
if(data == 1){
// Do something or do nothing :-)
alert('Data was saved in db!');
}
});
}
});
PHP: file.php
<?php
if ($_POST && isset($_POST['value'])) {
// db connection
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
// error happened
print(0);
}
mysql_select_db('mydb');
// sanitize the value
$value = mysql_real_escape_string($_POST['value']);
// start the query
$sql = "INSERT INTO table (value) VALUES ('$value')";
// check if the query was executed
if(mysql_query($sql, $link)){
// everything is Ok, the data was inserted
print(1);
} else {
// error happened
print(0);
}
}
?>
Simple put...
$('input:checkbox').click( function() {
clicked = $(this).attr('checked');
if (clicked) {
/* AJAX the server to tell them it was clicked. */ }
else {
/* AJAX the server to tell them it was unclicked. */ } } );
I can make this even simpler. first, you need to ad a checkbox!!
<form name="form1aa" method="post" action="process.php?fn=<? echo $rows['frist']; ?>&class=<?php echo $rows['class']; ?>&last=<?php echo $rows['last']; ?>
&model=<?php echo $rows['model']; ?>&cas=<?php echo $rows['cases']; ?>&upid=<?php echo $id; ?>&group=1" id="form1a" >
<select name="type" onchange="fill_damage(document.form1aa.type.selectedIndex);">
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
</select>
<select name="damage">
</select>
<input type="text" name="comment" placeholder="Comments Box">
<input type="text" name="cost" placeholder="Cost">
<input type="checkbox" name="somecheck" onchange="if(this.checked)document.form1aa.submit()">Check this to Save.
<input type="submit" value="Save" name="Save">
</form>
<script type="javascript>
//another function that works for onchange="dosubmit(this)"
//IF you put it after the form.
function dosubmit(el) {
if (el.checked) {
document.form1aa.submit();
}
}
</script>
get rid of the spaces in your onchange events where possible.
If you have dynamic checkbox list and you want to dynamically save the clicked one to database or inserting the unchecked one, here how to do that:
Html/PHP
<?php
// $checklists are models that I am getting from db
$checklists = CheckList::getCheckLists(3);
echo '<ul>';
foreach ($checklists as $checklist) {
$isChecked = $checklist->getAnswer($requestID, $checklist->primaryKey);
$checked = $isChecked ? "checked" : "";
echo '<li>';
echo "<input id='{$checklist->primaryKey}'
name='{$checklist->primaryKey}' type='checkbox' {$checked}
value='{$isChecked}' data-request-id='{$requestID}'>
$checklist->check_list_text";
echo '</li>';
}
echo '</ul>';
?>
Jquery
<script>
$("input[type='checkbox']").on('click', function(){
var checkbox = $(this);
var checked = checkbox.prop('checked');
var checklistId = checkbox.attr("id");
$.ajax({
url:"<?= Url::to(['default/add-checklist-answer']) ?>",
// I don't need to write the type here because I am using Yii Framework
// type: 'post',
data: {
checklistId: checklistId,
requestId: checkbox.data('request-id'),
checked: checked
},
success: function(data) {
//alert(data);
console.log(data.firstMessage)
},
error: function(data) {
// alert(data);
}
});
});
</script>
I hope it will work for MVC users.