I've been searching for this kind of problem and I couldn't find one. I am using ajax to solve this problem but it didn't work out. I really want to have this scenario where after the user scanned his/her QR code, its data (account ID) will be in the input field. Then the other input field will automatically show its corresponding data from the database based on the data from QR code. This is so far my code.
This is from the main page:
<label id="acc">Account ID
<input type="text" name="accId" id="accID" class="idnum" required="" value="">
</label>
<label id="label">QR ID
<input type="text" readonly=" " name="qrId" id="qrId" style="width: 108px;margin-right: 15px;" value="" >
</label>
Ajax:
<script>
$("#accID").change(function() {
var accID = $(this).val();
$.ajax({
url: 'loadata.php',
type: 'POST',
data: 'accID='+accID,
success: function(html) {
$("#qrId").html(html);
}
});
});
</script>
this is the loadata.php:
<?php
session_start();
include ('connection.php');
if(isset($_POST['accID']))
{
$accID = $_POST['accID'];
$sel = "SELECT * FROM qrcode WHERE Cus_IDNum = '$accID'";
$sel_run = $conn->query($sel);
if($sel_run->num_rows>0)
{
while($rows = $sel_run->fetch_assoc())
{
?>
<input type="text" readonly=" "id="qrId" name="qrId" style="width: 108px;margin-right: 15px;" value="" >
<?php
}
}
}
?>
Thank you very much for your time! :)
Are you getting any data to return? Have you tried changing your input field in loadata.php to a div with the same ID? Right now you're trying to place an input within an input.
Also, you don't need to wrap your inputs within the label. As long as the label and input share the same ID, they will always be together. Currently, you are not doing that.
Setting $("#qrId").html(html); will do nothing, as #qrId is an input field. I think, what you want to do is to set the value of the input field.
This should work like this: $("#qrId").val(html);
Then, there is a second problem as your PHP script returns HTML of an input field rather than just the value to set. Also, it may return multiple values as you loop through the database results.
You could try to change your script to something like this to just return the value of the first selected database record. Replace qrCodeValue with the real column name to use:
<?php
session_start();
include ('connection.php');
if(isset($_POST['accID']))
{
$accID = $_POST['accID'];
$sel = "SELECT * FROM qrcode WHERE Cus_IDNum = '$accID'";
$sel_run = $conn->query($sel);
if($sel_run->num_rows>0)
{
$row = $sel_run->fetch_assoc();
print $row['qrCodeValue'];
exit;
}
}
?>
Related
I have a page with a select list (gets successfully populated from mysql) and a text box. The text box has to be populated with a value from mysql based on the item selected in the list. But the ajax call to php is not working and i can not figure out what the issue is. I am just learning ajax and php, so a novice.. Please help. i am stuck with this for a long time.
<script>
$(document).ready(function() {
$('.selectpicker').on("change", function(){
var selected_data = $(this).find("option:selected").val();
alert(selected_data);
$.ajax ({
type: "POST",
data: { selected_data: selected_data },
url: "getoldcharity.php",
dataType: "json",
success: function(res) {
$('#charity_new').val(data.charity_new);
}
});
});
});
</script>
<form id="assign-fundraiser_form" class="form-horizontal" action="" method="post">
<div class="form-group">
<div class="col-md-3">
<select class="selectpicker form-control" id="fundraiser" name="fundraiser" required>
<option value="" selected disabled>Select a Fundraiser</option>
<?php
include('session.php');
$result1 = mysqli_query($db,"select concat(f_firstname,' ',f_lastname) fundraiser from fundraiser where f_company in (select contractor_name from contractor where company_name = '$_SESSION[login_user]') and f_status = 'Active' order by concat(f_firstname,' ',f_lastname)");
while ($rows = mysqli_fetch_array($result1))
{
echo "<option>" .$rows[fundraiser]. "</option>";
}
?>
</select>
</div>
</div>
<input type="text" name="charity" id="charity_new" />
</form>
<?php
include "session.php";
if (ISSET($_POST['.selectpicker'])) {
$ref = $_POST['.selectpicker'];
$query = $db->query("select f_charity charity_new from fundraiser limit 1");
$row = $query->fetch_assoc();
$charity_new = $row['charity_new'];
$json = array('charity_new' => $charity_new);
echo json_encode($json);
}
$db->close();
?>
There are a few problems that I've spotted from quick glance, so I've separated them below.
PHP
In your AJAX request, you are using data: { selected_data: selected_data } which means the PHP code will be expecting a POSTed key named selected_data but you're looking for .selectpicker. You seem to have mixed up a couple of things, so instead of:
$_POST['.selectpicker']
it should be:
$_POST['selected_data']
JavaScript
As Ravi pointed out in his answer, you also need to change your success function. The parameter passed through to this function is res not data, so instead of:
$('#charity_new').val(data.charity_new);
it should be:
$('#charity_new').val(res.charity_new);
MySQL
It also appears as though your query itself is invalid - you seem to be missing a comma in the column selection.
select f_charity charity_new from fundraiser limit 1
should be:
select f_charity, charity_new from fundraiser limit 1
or, seeing as you're not using the f_charity column in the results anyway:
select charity_new from fundraiser limit 1
You aren't using the value that is being POSTed either, meaning that whatever option is selected in the dropdown makes no difference to the query itself - it will always return the first record in the database.
Other
One other thing to be aware of is you're using a class selector on your change function. This means if you have multiple dropdowns with the same class name in your HTML, they will all be calling the same AJAX function and updating the textbox. I don't know if this is what you're aiming for, but from your code posted, you only have one dropdown in the form. If you only want that one dropdown to be calling the AJAX function, you should use an ID selector instead:
$('#fundraiser').on("change", function() {
// ...
}
I think, it should be
$('#charity_new').val(res.charity_new);
instead of
$('#charity_new').val(data.charity_new);
I've got an HTML form that uses jQuery serialize method and ajax to post results using PHP into a sqlite database. I've set the jQuery to run every minute to act as an autosave feature so users can return later to finish what they started. Because of the autosave, I can't force all inputs be required.
It works 99% of the time. However, in a few cases, the application sometimes posts blank data to the database even though there is data in the input fields. I've checked to make sure all the HTML input fields have name attributes. Any ideas why it works most of the time but in a few random cases, it doesn't?
I wish I had more to report why it doesn't work all the time. I haven't been able to replicate the bug myself, I'm just going on reports of users. But I know the form is posting blanks into the database because when I go into the database, it says " " instead of "null". So I know the database is receiving something, but it isn't receiving the data the user typed.
HTML
<form action="" method="post" id="evaluationForm">
<!-- this input is disabled since this user can't edit it -->
<label for="FirstName">First Name</label>
<input type="text" name="FirstName" value="<?php echo htmlspecialchars($data['FirstName']);?>" disabled >
<label for="WorkHabitsCommentsSuper">Comments </label><br>
<textarea name="WorkHabitsCommentsSuper" placeholder="Comments are optional">
<?php echo htmlspecialchars($data['WorkHabitsCommentsSuper']);?>
</textarea>
<label for="GoalsSuper">More Comments</label>
<textarea name="GoalsSuper" required>
<?php echo htmlspecialchars($data['GoalsSuper']);?>
</textarea>
<!-- and a whole bunch more fields but you get the idea -->
</form>
JavaScript
function saveEval() {
var datastring = $("form").serialize();
$.ajax({
type: "POST",
url: "autosave-s.php",
data: datastring,
success: function(text) {
if (text == "success") {
alert('It saved. Hooray!');
} else {
alert('Oh no. Something went wrong.');
}
}
});
}
window.onload = function() {
setInterval("saveEval()", 60000)
}
PHP
$db = new PDO('sqlite:evals.sqlite');
$sql = "UPDATE table SET
WorkHabitsCommentsSuper = :WorkHabitsCommentsSuper,
GoalsSuper = :GoalsSuper";
$query = $db->prepare($sql);
$query->execute(array(
':WorkHabitsCommentsSuper' => $_POST['WorkHabitsCommentsSuper'],
':GoalsSuper' => $_POST['GoalsSuper']
));
echo "success";
if(!in_array("",$_POST)){
$db = new PDO('sqlite:evals.sqlite');
$sql = "UPDATE table SET
WorkHabitsCommentsSuper = :WorkHabitsCommentsSuper,
GoalsSuper = :GoalsSuper";
$query = $db->prepare($sql);
$query->execute(array(
':WorkHabitsCommentsSuper' => $_POST['WorkHabitsCommentsSuper'],
':GoalsSuper' => $_POST['GoalsSuper']
));
echo "success";
}else{
echo "Empty";
}
This will check if the posting data is not empty if empty any of the field it will not update and will send 'Empty' response so alert on empty data posting.
i have been searching a solution for days and i have tried ajax/jquery methods posted online but it just wouldnt work. I have a drop down list which gets its value from the database. On selecting any value apart from "Select", i want to display a value which is called upon by a php file:
here's my code for the form:
<tr>
<fieldset id="Date">
<td class="select"><label><span class="text_9">Date:</span></label></td>
<td><select name="date" id="date">
<option value="">Select</option>
<?php include_once "selectdate.php"?></td>
</select>
</tr>
</fieldset>
</table>
and here's the php to run on selection of the drop down (called retrieve.php)
<?php
include_once "connect.php";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$form=$_GET;
$trade=$form['tradetype'];
$metal=$form['metal'];
$amount=$form['amount'];
$date=$form['date'];
$stmt = $conn->query("SELECT Discount FROM Contracts WHERE Trade='$trade' AND Metal='$metal' AND Amount='$amount' AND ExpiryDate='$date'");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo ($row['Discount']);
}
?>
As you can see, the php to be run uses the value from multiple form elements...
I am very new to jquery/ajax... any help is appreciated as i want the result to be displayed on the same page as the form is. Thank you!
If you want to get data from another file to a select, you should add as option. Plain text inside select will not help you out. So wrap the vales with <option></option>
So change this line,
echo "<option>{$row['Discount']}</option>";
If you want to give values,
echo "<option value='{$row['Discount']}'>{$row['Discount']}</option>";
EDIT
Now onchange of deopdown, date call ajax to do next stuff.
$(document).on("change","#date",function() {
var tradetype = //capture the value here;
var metal = //capture the value here;
var amount = //capture the value here;
$.ajax({
url:"path/filename.php",
data:{date:$(this).val(),"tradetype":tradetype,"metal":metal,"amount":amount},
type: "POST",
success: function(data){
alert(data);//this will alert what you have echoed on php file
}
});
});
I've got some code that works nicely for saving to the database etc. What i'd like to do now is after the fields are saved, i want the echoed last id to be populated to a hidden field so i can use that to determine any future insert/update queries.
My form is:
<div id="formHolder">
<form type="post" action="add_room.php" id="mainForm">
<label for="itemName[]">Item</label>
<input type="text" name="itemName[]">
<label for="itemPhoto[]">Item</label>
<input type="text" name="itemPhoto[]">
<input type="hidden" name="hiddenId[]" value="">
<div class="save">Save Item</div>
</form>
</div>
my jQuery is:
<script>
$(document).ready(function() {
$('body').on('click', '.save', function(e) {
var string = $(this).closest('form').serialize();
$.ajax({
type: "POST",
url: "add_room.php",
data: string,
cache: false,
success: function(data){
$('#message').text('The id of the inserted information is ' + data);
}
});
});
});
$(document).ready(function(){
$('#addForm').on('click', function(){
$('<form><label for="itemName[]">Item</label><input type="text" name="itemName[]"><label for="itemPhoto[]">Photo</label><input type="text" name="itemPhoto[]"><input type="hidden" name="hiddenId[]" value=""><div class="save">Save Item</div></form>').fadeIn(500).appendTo('#formHolder');
});
});
</script>
and finally my php is:
<?PHP
include('dbConfig.php');
$item = $_POST['itemName'];
$photo = $_POST['itemPhoto'];
foreach($item as $key => $val) {
if ($stmt = $db->prepare("INSERT test (test_title, test_desc) VALUES (?, ?)"))
{
// Use an s per variable passed to the string, example - "ss", $firstname, $lastname
$stmt->bind_param("ss", $val, $photo[$key]);
$stmt->execute();
$stmt->close();
echo $db->insert_id;
//echo "success";
}
// show an error if the query has an error
else
{
echo "ERROR: Could not prepare SQL statement.";
}
}
?>
Everything works nicely for adding field data to the database, adding extra fields etc. I just cannot get it to save the echoed id of each ajax post to save to the hidden field, yet it saves it to the #message div no problem. Any ideas? I have tried using .val(); but it didn't work, i'm stumped
Andy
try this within success function
$("[type=hidden]").val(data);
or if you able to set the hidden field id thats much better like this
<input type="hidden" name="hiddenId[]" id="hiddenId" value="">
code will be like this
$("#hiddenID").val(data);
Hope it will help
You can use the following code
$("[type=hidden").val(data);
or
$("#hiddenId").attr("value",data);
Your data variable in the ajax success function contains all output from your php file so if you are adding multiple items, it will be a string with all newly added ID's concatenated together.
What I would do is something like:
use a counter in the html form-fields so that you know exactly what fields to address, something like: <input type="text" name="itemName[1]">;
add this key and the value to an array in your php instead of echoing it out: $array[$key] = $db->insert_id;;
after your php insert loop, echo out the data you need on the javascript side: echo json_encode($array);
loop through your data in the ajax success function to assign the right values to the right elements.
You'd probably need to change your ajax call a bit to accept json.
I'm currently building a system using ExpressionEngine that allows users to answer questions in exchange for points, they can then use these points to claim prizes.
I've been writing the functionality to claim a prize, it needs to do the following:
Check the prize is in stock
Check the user has enough points
If in stock and enough points submit a form which lets the admin know to send the prize out
I have the following code which I think is nearly there however I'm struggling with the last bit, the actual success/failure parts. I've used jQuery Ajax:
<script type="text/javascript">
$(function() {
$("#prizeClaim").submit(function() {
var data = "entry_id={entry_id}&member_id={logged_in_member_id}&prize_title={title}&prize_points={prize_points}";
$.ajax({
url: "/prizes/prize_validation/",
data: data,
success: function(html) {
alert(html); // alert the output from the PHP Script
}
});
return false;
});
});
</script>
This code currently just outputs the html of prize_validation in an alert, this is the code used on the validation page so far:
<?php
// All data required made into vars
$entry_id = ($_GET['entry_id']);
$member_id = ($_GET['member_id']);
$prize_title = ($_GET['prize_title']);
$prize_points = ($_GET['prize_points']);
// Select the stock column
$query = ee()->db->query("SELECT field_id_6 FROM exp_channel_data WHERE entry_id = $entry_id");
if ($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
// define stock_total
$stock_total = $row['field_id_6'];
// If stock more than 0 go ahead
if($stock_total > 0) {
//remove 1 stock item
ee()->db->query("UPDATE exp_channel_data SET field_id_6 = field_id_6 - 1 WHERE entry_id = $entry_id");
//update users points
$data = array('member_id' => $member_id, 'prize_points' => $prize_points, 'prize_id' => $entry_id);
$sql = ee()->db->insert_string('exp_rmdy_member_prize_data', $data);
ee()->db->query($sql);
}
}
}
?>
{exp:freeform:form form_id="1" return="thanks"}
<input type="hidden" name="name" value="{username}" id="freeform_name" maxlength="150">
<input type="hidden" name="email" value="{email}" id="freeform_email" maxlength="150">
<input type="hidden" name="company" value="{exp:channel:entries channel='company' dynamic='no'}{if {member_code} == {company_code}}{title}: {company_address}{/if}{/exp:channel:entries}" id="freeform_company" maxlength="200">
<input type="hidden" name="prize" value="<?php echo $prize_title ?>" id="freeform_prize" maxlength="150">
<p><input type='submit' name='submit' value='Process order'></p>
{/exp:freeform:form}
This code checks the stock and if the item is in stock it then removes the amount of points from the users total points, this works. However once this has happened I want to submit the Freeform, I'm not 100% sure if this should be within the prize_validation file or in a third location. But after lots of experimentation I'm still not sure how to go about either!
Any hints/tips much appreciated!
Pjacks answer in the above comment helped me fix this.
Do you want to use ajax to submit or a normal form submit. This should submit the form if you put $("#freeform").submit(); in your call back instead of the alert. Thats assuming the id of your form is called freeform. If you want to do ajax, it's done a bit differently.