I am trying to send a textbox value (invoice number) to a PHP file through jQuery and AJAX. From the PHP file, I am returning the JSON encoded data. I want to display the values fetched from the database in the following textboxes (Total Amount, Balance Amount) and select boxes (Payment mode, Payment status).
I am not getting the output I wish. Where am I going wrong?
HTML:
<form name="inv_payment" method="post" action="" style="margin:0px;width:400px;">
<fieldset>
<legend>Payment details</legend>
<label for=inv_num>Invoice Number</label>
<input id=inv_num name=inv_num type=number placeholder="12345" required autofocus >
<input type=button name="get_details" id="get_details" value="Get Details" >
<label for=tot_amt>Total Amount</label>
<input id=tot_amt name=tot_amt type=text placeholder="12345" disabled > <br/>
<label for=pay_up>Pay Up </label>
<input id=pay_up name=pay_up type=text placeholder="12345" required ><br/>
<label for=bal_amt>Balance Amount </label>
<input id=bal_amt name=bal_amt type=text placeholder="12345" disabled > <br/>
<label id="paymt_mode"><strong>Payment Mode</strong></label>
<select name="pay_mode" style="width: 130px">
<option selected="selected">Cash</option>
<option>Cheque</option>
</select><br/>
<label id="paymt_status"><strong>Payment Status</strong> </label>
<select name="pay_status" style="width: 130px">
<option selected="selected">Pending</option>
<option>Completed</option>
</select><br/>
<input type="submit" value="Payment" name="pay_btn">
</fieldset>
</form>
jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#get_details').click(function() {
//To pass the invoice number and fetch related details
$.getJSON("get_invpay_details.php", {id: $('#inv_num').val()}, function(data){
$('#tot_amt').val(data['Total_Amount']);
$('#bal_amt').val(data['Balance_Amount']);
$('#pay_mode').val(data['Payment_Type']);
$('#pay_status').val(data['Payment_Status']);
});
});
</script>
PHP:
<?php
include('includes/dbfunctions.php');
include('includes/db.php');
if(isset($_GET['id']))
{
$tmp = $_GET['id'];
$sql = mysql_query("select Total_Amount,Balance_Amount,Payment_Type,Payment_Status from invoice where InvoiceNum='$tmp'");
if(mysql_num_rows($sql))
{
$data = mysql_fetch_array($sql);
echo json_encode($data);
}
}
?>
Your json response value populate with object.data like this.
$('#tot_amt').val(data.Total_Amount);
$('#bal_amt').val(data.Balance_Amount);
$('#pay_mode').val(data.Payment_Type);
$('#pay_status').val(data.Payment_Status);
Here data is an object not a array.
I have checked my query.It gave me the correct output in mysql editor.
what i could see is.. you have a typo in your question...
missing }); for document.ready..which might be breaking your script..(this should have error in your console though..)..anyways something to check about..
$(document).ready(function() {
$('#get_details').click(function() {
//To pass the invoice number and fetch related details
$.getJSON("get_invpay_details.php", {id: $('#inv_num').val()}, function(data){
$('#tot_amt').val(data['Total_Amount']);
$('#bal_amt').val(data['Balance_Amount']);
$('#pay_mode').val(data['Payment_Type']);
$('#pay_status').val(data['Payment_Status']);
});
});
});
//^^--here
Related
I have a form in a php page that I want to have updated as the drop down is changed. Here is the code for the form:
<form action="AdminPage.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="action" value="version" />
<label><strong>Name:</strong></label>
<select id="WebName" name="Name">
<option value="ReportDashboard">ReportDashboard</option>
<option value="ReportDashboard Dev"<?php if(strpos($_SERVER['PHP_SELF'],"dev/FrontierReports",1) > 0){echo " selected='selected'";}?>>ReportDashboard Dev</option>
<option value="ReportDashboard Testing"<?php if(strpos($_SERVER['PHP_SELF'],"dev/Testing",1) > 0){echo " selected='selected'";}?>>ReportDashboard Testing</option>
</select><p></p>
<label><strong>Version Number: </strong></label>
<input id="VersionNumber" type="text" name="VersionNumber" value="<?php echo $VersionNumber['VersionNo']; ?>" /><p></p>
<label><strong>Version Type:</strong></label>
<select id="Type" name="VersionType">
<option value="1">Major</option>
<option value="2">Minor</option>
<option value="3" selected="selected">Bug</option>
</select><p></p>
<input type="hidden" name="VersionNumberCheck" value="<?php echo $VersionNumber['VersionNo']; ?>" />
<label><strong>Notes</strong></label>
<input id="Notes" type="text" name="Notes" value="<?php echo $ReleaseNotes['ReleaseNotes']; ?>" />
<p><input class="Pointer" type="submit" name="submit" value="Update Version" /></p>
<p><input id="VersionSubmit" class="Pointer" type="button" name="VersionSubmit" value="Current Notes" /></p>
</form>
Currently, the form gets its values for the 2 text fields (VersionNumber and Notes) from outside the form. I would like to have them be obtained as the form is created based on what the first drop down (Name) has selected and then update if that drop down gets changed.
I thought of adding some PHP to the form to help, but it doesn't work. Here is what I tried:
<form action="AdminPage.php" enctype="multipart/form-data" method="post">
<input type="hidden" name="action" value="version" />
<label><strong>Name:</strong></label>
<select id="WebName" name="Name">
<option value="ReportDashboard">ReportDashboard</option>
<option value="ReportDashboard Dev"<?php if(strpos($_SERVER['PHP_SELF'],"dev/FrontierReports",1) > 0){echo " selected='selected'";}?>>ReportDashboard Dev</option>
<option value="ReportDashboard Testing"<?php if(strpos($_SERVER['PHP_SELF'],"dev/Testing",1) > 0){echo " selected='selected'";}?>>ReportDashboard Testing</option>
</select><p></p>
<?php
$Vsql = "select top 1 VersionNo,ReleaseNotes from pmdb.Version where Name = 'ReportDashboard' order by name,VersionNo desc";
$GetVersion = $conn->query($Vsql);
$VersionNumber = $GetVersion->fetch(PDO::FETCH_ASSOC);
?>
<label><strong>Version Number: </strong></label>
<input id="VersionNumber" type="text" name="VersionNumber" value="<?php echo $VersionNumber['VersionNo']; ?>" /><p></p>
<label><strong>Version Type:</strong></label>
<select id="Type" name="VersionType">
<option value="1">Major</option>
<option value="2">Minor</option>
<option value="3" selected="selected">Bug</option>
</select><p></p>
<input type="hidden" name="VersionNumberCheck" value="<?php echo $VersionNumber['VersionNo']; ?>" />
<label><strong>Notes</strong></label>
<input id="Notes" type="text" name="Notes" value="<?php echo $ReleaseNotes['ReleaseNotes']; ?>" />
<p><input class="Pointer" type="submit" name="submit" value="Update Version" /></p>
<p><input id="VersionSubmit" class="Pointer" type="button" name="VersionSubmit" value="Current Notes" /></p>
</form>
I don't know how to capture what is in the drop down to change the SQL that is pulling the data. I thought of possibly just pulling all of the rows back and then doing a search against it once the form is built, but I still don't know how to capture when the drop down changes and then update the 2 text boxes.
UPDATE
I now have a new file named UpdateAdminVersion.php this is what is has:
$Vsql = "select top 1 VersionNo,ReleaseNotes from pmdb.Version where Name = 'ReportDashboard' order by name,VersionNo desc";
$GetVersion = $conn->query($Vsql);
$VersionNumber = $GetVersion->fetch(PDO::FETCH_ASSOC);
$data = $VersionNumber;
echo json_encode($data);
I also added the following script to the previous file with the form:
$("#WebName").change(function ()
{
$.post("UpdateAdminVersion.php",
{
parameter1: "ReportDashboard Dev",
parameter2: $("#VersionNumber").val()
},
function (data, status)
{
aconsole.log(data)
$("#Notes").val(data);
});
});
I must still be missing something because nothing happens when I change the drop down.
UPDATE 2
I've changed the script to this:
$("#WebName").change(function ()
{
$.post("UpdateAdminVersion.php",
{
WebName: $('#WebName').val(),
VersionNumber: $("#VersionNumber").text()
},
function (data, status)
{
console.log(data)
$("#Notes").val(data);
success: alert ("Number 2 is successful!");
});
success: alert ("Number 1 is successful! \n" + WebName + "\n" + VersionNumber);
});
I get the alert Number 1 is successful!, but the WebName and VersionNumber variables return [object HTMLSelectElement] and [objectHTMLInputElement] respectively. How do I return the actual values?
And how do I use them in the UpdateAdminVersion.php file?
For starters you can use jqueryUI Autocomplete to feed Select tag with options.
Then use onchange event to capture dropdown changes.
<select onchange="myFunction()">
when event is triggered retreive data from db using Ajax, on success modify your form fields accordingly.
Look at this Fiddle give your own parameters, should work.
I have a problem, I need to associate a input type checkbox to a input type text.
The situation is as follows:
Extract data from a database. The PK data are the value of the checkbox. When a checbox select an input type text where you can enter a specific number is activated.
Now the problem is that selecting a checkbox input text all kinds are activated. And what I hope is that by selecting the checkbox input only the input associated with the checkbox enabled.
My HTML code (This code creates a input checkbox and input text for each record in the database, and what I want is to activate a specific checkbox is activated, the input type text):
<form action="send.php" method="POST" id="form-touch">
<?php foreach ($data as $key): ?>
<div id="inputsForm">
<input type="checkbox" class="id-check" name="nuevoid[]" value="<?php echo $key['pr_id'] ?>">
<input type="newquantity[]" class="myinput" disabled name="newQuantity" value="" placeholder="Enter quantity">
</div>
<?php endforeach; ?>
<input type="submit" value="Send">
</form>
My jquery code (code that activates or deactivates the text field by selecting a checkbox):
$('.id-check').change(function(){
if ($('.id-check').is(':checked') == false){
$('.myinput').val('').prop('disabled', true);
} else {
$('.myinput').val('1').prop('disabled', false);
}
});
How I can achieve what I want? Greetings from Chile.
Try
$('.id-check').change(function() {
if ($(this).is(':checked') == false) {
$(this).closest('div').find('.myinput').val('').prop('disabled', true);
} else {
$(this).closest('div').find('.myinput').val('1').prop('disabled', false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="send.php" method="POST" id="form-touch">
<div id="inputsForm">
<input type="checkbox" class="id-check" name="nuevoid[]" value="">
<input type="newquantity[]" class="myinput" disabled name="newQuantity" value="" placeholder="Enter quantity">
</div>
<div id="inputsForm">
<input type="checkbox" class="id-check" name="nuevoid[]" value="1">
<input type="newquantity[]" class="myinput" disabled name="newQuantity" value="" placeholder="Enter quantity">
</div>
<input type="submit" value="Send">
</form>
you can use .next() jQuery selector. I have modified your jQuery change handler below. It works for me so try it. It should work for you too.
$('.id-check').change(function(){
if ($(this).is(':checked') == false){
$(this).next().val('').prop('disabled', true);
} else {
$(this).next().val('1').prop('disabled', false);
}
});
Goodluck and happy coding! :-)
Okay this is driving me crazy now, I can't seem to find a solution at all!
Basically I have two select boxes on my page, However I want the second select box to to be populated from a mysql database depending on the value of the first select box.
For example if I choose the value 'misc' from the first select box, the second select would be populated with the misc table from my database! (the second select box will be refreshed via ajax on first select box choice change)
My only problem is I can't think of a way to store the value of the first select box in a php variable, so it can be used in my function to populate the second select box(which is refreshed by ajax)
Thanks guys
<form action="scripts/tp/process.php" method="post" enctype="multipart/form-data">
Select teleport here:
<select name="selectmate" id="Testid" onchange='Ajax();'>
<option value="Misc">Misc...</option>
<option value="Stunt">Stunt</option>
<option value="deathmatches">Deathmatches</option>
<option value="Car"> Car </option>
<option value="Races">Races </option>
</select>
<br/>
<label for="file">Filename:</label>
<input name="file" type="file"/>
<br/>
<label for="Name">Teleport name:</label>
<input type="text" name="Name" id="Name"/>
<br/>
<label for="Tp"> Teleport command:</label>
<input type="text" name="Tp" id="Tp"/>
<br/>
<label for="Info">teleport infomation</label>
<input type="text" name="Info" id="Info"/>
<br/>
<input type="submit" name="submit" value="Submit"/>
</form>
<h2>Delere entry here!</h2>
<form action="scripts/misc/miscdelete.php" method="post" enctype="multipart/form-data">
<select name="deletemisc">
<?php
ListDatabase($value);
?>
</select>
<input type="submit" name="delete" value="Delete"/>
</form>
I need to store the value of the first select box in the variable $value
$("#Testid").change(function () {
var val = $("#Testid option:selected").text();
// here your ajax request
// Fill second select here:
var deletemisc = $("#deletemisc");
$("#deletemisc > option").remove();
$.post("/path/to/script", { selected_val: val}, function(result) {
$.each(result, function (item) {
deletemist.append($("<option />").val(item.val).text(item.text));
})
});
});
"/path/to/script" - must return json array of vals.
I am probably making some silly mistake but I am newer to the world of Jquery and am looking for some help with this issue.
I have a form that I need to check/validate two dates once they change their values. Once they change I had an Ajax call that loaded a page "checkdates.php" and passed in two bits of data. The Date that changed and a project name to "checkdates.php" using GET and adding the data to the URL string. This Ajax call loaded the page in a div with the ID "status" and php page displayed what the outcome of the date check was.
The Old code used prototype to pull in the data as a function and I used the onChange event on the form elements:
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
/*function checkDate(date,project){
if(date!==''){
new Ajax.Updater('status', 'datechecker.php?date='+date+'&project='+project, { method: 'get' });
} else {
alert('enter a valid date!');
}
}
</script>
The code I'm trying to move over to jquery now looks like:
<script type="text/javascript">
$(document).ready(function() {
$('input#date_to').change(function() {
var datevalue = $(this).val();
$('#status').load('datechecker.php?date='+datevalue+'&project='+<? echo $_COOKIE['department']; ?>);
}
);
$('input#date_from').change(function() {
var datevalue = $(this).val();
$('#status').load('datechecker.php?date='+datevalue+'&project='+<? echo $_COOKIE['department']; ?>);
}
);
});
</script>
I think it may be an issue probably with how i'm pulling in my data or how i'm asking it to check the .change feature because it's not firing. Any assistance would be wonderful. Again the disclaimer: I'm sort of new to jquery so please be nice if it's some obvious idiot mistake.
EDIT:
As requested the HTML/PHP of the rest of the file (sorry for the formatting, this was a quick and dirty project that was last minute but turned into a huge headache):
<form id="form1" name="form1" method="get" action="?page=post_request">
<div class="timeavailable">
<?
require('data.php');
$name=$_COOKIE['un'];
$query="SELECT * FROM time WHERE emp_name='".$name."'";
$result=mysql_query($query);
$num=mysql_num_rows($result);
mysql_close();
$i=0;
?>
Vac: <b><? echo mysql_result($result,$i,"vacationtime"); ?></b>
Personal: <b><? echo mysql_result($result,$i,"personaltime"); ?></b>
Pts: <b><? echo mysql_result($result,$i,"points"); ?></b>
<input type="hidden" name="vacationtime" value="<? echo mysql_result($result,$i,"vacationtime"); ?>">
<input type="hidden" name="personaltime" value="<? echo mysql_result($result,$i,"personaltime"); ?>">
</div>
<h1>Time Off Request Form</h1>
<div class="header">
<div class="floatydetails">
<br>
Reason for Absence:<br>
<textarea name="reason_detail" id="reason_detail" rows="<?php echo $textareaheight; ?>" cols="<?php echo $textareawidth; ?>"></textarea>
<div id="status"></div>
<div id="daysrequested"></div>
</div>
<div class="col1">
Type of Absence Requested:<br>
<label for="reason_for_request"></label>
<select name="reason_for_request" id="reason_for_request">
<option value="Sick" >Sick</option>
<option value="Vacation" >Vacation</option>
<option value="Bereavement" >Bereavement**</option>
<option value="Doctor Appointment" >Doctor Appointment**</option>
<option value="Court" >Court*</option>
<option value="Jury Duty" >Jury Duty*</option>
<option value="Personal Day" >Personal Day</option>
<option value="Other" >Other</option>
</select><br>
<div class="col2">
Date of Request (mm/dd/yyyy)<br/>
<label for="date_from">From:</label>
<input type="text" name="date_from" id="date_from" class="required" /><br>
<label for="date_to">To:</label>
<input type="text" name="date_to" id="date_to" class="required" /><br>
Partial Request (HH:MM am/pm)<br/>
<label for="date_from">From:</label>
<input type="text" name="partial_from" id="partial_from" class="date-pick" /><br>
<label for="date_to">To:</label>
<input type="text" name="partial_to" id="partial_to" class="date-pick" /><br>
</div>
</div>
<div class="clear-fix"></div><br><br>
<hr>
<center><b>
Note: If You do Not have the Time Available, Your request will be Denied.<br>
* Proper Documentation is required Before approval is made. ** Proper documenation is required upon return.
</b></center>
</div>
<input type="hidden" name="do" value="post">
<input type="hidden" name="emp_name" value="<? echo $_COOKIE['un']; ?>">
<input type="hidden" id="projects" name="projects" value="<? echo $_COOKIE['department']; ?>">
<input type="hidden" name="supervisor" value="<? echo $cms->grabItemByName(employees, $_COOKIE['user_id'], supervisor); ?>">
<input type="hidden" name="emp_number" value="<? echo $cms->grabItemByName(employees, $_COOKIE['user_id'], employee_id); ?>">
<input type="hidden" name="page" value="post_request">
</form>
Is $_COOKIE['department'] an integer? Otherwise you'll probably have a syntax error there.
Both the functions seem to be identical so you can combine them like this:
<script type="text/javascript">
$(document).ready(function() {
$('input#date_to,input#date_from').change(function() {
var datevalue = $(this).val();
$('#status').load('datechecker.php?date='+datevalue+'&project='+<? echo json_encode($_COOKIE['department']); ?>);
});
});
</script>
Here is a possible answer:
jquery change event trigger
Also, try watching the console in Firebug to make sure your php page is getting/returning the correct values.
I found a solution after some of your help and some trial and error. Using the .ajax I was able to get more flexiability to do what I wanted.
<script type="text/javascript">
$(document).ready(function() {
$('#date_to,#date_from').change(function() {
//$('input').change(function() {
var datevalue = $(this).val();
var project = $('#projects').val();
$('#status p').load('datechecker.php?date='+datevalue+'&project='+project);
});
});
</script>
Hope this helps someone out.
I am creating a dynamic form where the user will have the ability to add a set of inputs to the form. The html looks like this:
<form>
<input id="title1" class="title" name="title1" type="text" value="">
<input id="productionCompany1" name="productionCompany1" type="text" value="">
<input id="year1" name="year1" type="text" value="">
<input id="role1" name="role1" type="text" value="">
<div id="newCredit"> </div>
add another credit
</form>
When the user clicks the link with the id of "addCredit" the following jQuery script is called:
$(document).ready(function() {
var $ac = $('#addCredit');
$ac.click(function() {
/* the following two lines are where the problem lies? */
var $credInt = $(this).prev(".title");
$.get("addCredit.php", {num: $credInt},
function(data){
$('#newCredit').append(data);});
return false;
});
});
The jQuery function queries a php file called "addCredit.php", which looks like this:
<?php
$int = $_GET["num"];
$int = substr($int, -1);
$int++;
?>
<input id="title<?php echo $int;?>" class="title" name="title<?php echo $int;?>" type="text" value="">
<input id="productionCompany<?php echo $int;?>" name="productionCompany<?php echo $int;?>" type="text" value="">
<input id="year<?php echo $int;?>" name="year<?php echo $int;?>" type="text" value="">
<input id="role<?php echo $int;?>" name="role<?php echo $int;?>" type="text" value="">
My problem is getting the javascript variable $credInt set properly so that it can be sent to the addCredit.php page and update the form fields accordingly. I also need to be sure that every time the form is appended, the next value sent is the incremented value.
Any thoughts on how I might accomplish this? Thank you for your help.
This is the wrong way of doing it; PHP can handle array syntax in a variable name. This makes it much easier to handle. It is also unnecessary to call the server to clone the form. You should name your fields like this:
<form>
<div id="originalCredit">
<input name="title[]" type="text" value="">
<input name="productionCompany[]" type="text" value="">
<input name="year[]" type="text" value="">
<input name="role[]" type="text" value="">
</div>
add another credit
</form>
And then your Javascript can be like this:
$(function() {
$('#addCredit').click(function() {
var newCredit = $('#originalCredit').clone(); // create new set
newCredit.find('input').val(''); // empty input fields
$(this).before(newCredit); // append at the end
return false;
});
});
When the form is finally sent to the server, because the variables are in the format of name[] PHP will recognize they are an array and then you can do this:
<? foreach($_POST['title'] as $k => $v) { ?>
Title: <?=$_POST['title'][$k]?><br>
Company: <?=$_POST['productionCompany'][$k]?><br>
Year: <?=$_POST['year'][$k]?><br>
Role: <?=$_POST['role'][$k]?><br>
<? } ?>
Obviously this is just displaying it as an example, but you can then save/update/whatever with it.