I have a form where there are select option and a textbox. All I want to do is when I select specific option, it will pass the id to query the same table to get another column's value based on ID of selected option and then display the value in a textbox before insert/update the table.
This code will works if both field in my form using select field. So in my opinion, maybe my script for storing value in input text field is totally wrong. Please correct me if I do wrong.
My form code :
<form name="inserform" method="POST">
<label>Existing Customer Name : </label>
<select name="existCustName" id="existCustName">
<option value="">None</option>
<?php
$custName = $conn->query("SELECT * FROM customers");
while ($row = $custName->fetch_assoc())
{
?><option id="<?php echo $row['customerID']; ?>" value="<?php echo $row['customerID']; ?>"><?php echo $row['customerName']; ?></option><?php
}
?>
</select>br>
<label>Current Bottle Balance : </label>
<input type="int" id="currentBal" name="currentBal"></input><br>
<input name="insert" type="submit" value="INSERT"></input>
</form>
My script code :
<script type="text/javascript">
$(document).on("change", 'select#existCustName', function(e) {
var existCustID = $(this).children(":selected").attr("id");
$.ajax({
type: "POST",
data: {existCustID: existCustID},
url: 'existingcustomerlist.php',
dataType: 'json',
success: function(json) {
var $el = $("input#currentBal");
$el.empty();
$.each(json, function(k, v) {
$el.append("'input[value='" + v.currentBal + "']").val();
});
}
});
});
</script>
existingcustomerlist.php code:
<?php
include 'config/config.php';
$result = $conn->query("SELECT * FROM customers WHERE customerID = '" .$_POST['existCustID'] . "'");
$results = [];
while ($row = $result->fetch_assoc()) {
$results[] = $row;
}
header('Content-Type: application/json');
echo json_encode($results);
?>
I need help to solve this.
I assume you are trying to show the results as input text element next to the #currentBal element. Try by changing the script tag inside the success callback as shown below.
$.each(json, function (k, v) {
$el.after("<input type='text' class="currentBalTemp" value='" + v.currentBal + "' />");
});
Make sure to remove the .currentBalTemp elements on change event of select otherwise duplication will be shown. Add the below code on change event.
$('.currentBalTemp').remove();
Related
I want to select a single value from the list of values that are retrieved from database. the problem is that when user types suppose f, and there are 2 or more than 2 values in database, then a tag is visible on the filed. How should I remove that br that is displayed between the values. Please help.
Controller page->admin_c.php
public function get_values_c()
{
$e_name = $_REQUEST['ename'];
$res = $this->admin_m->get_ename_m($e_name);
if(sizeof($res)>0)
echo implode("</br>",$res);
}
Model page->admin_m.php
public function get_ename_m($e_name)
{
$ename_value = [];
if($e_name!="")
{
$sql = "select distinct ename from event where ename like '$e_name%'";
$res = $this->db->query($sql);
foreach($res->result_array() as $row)
{
$ename_value[] = $row['ename'];
}
return $ename_value;
}
}
View page->edit_event.php
<div class="control-group" style="margin-bottom:10px;">
<label class="control-label" style="margin-left:-64px;">Event Name</label>
<div class="controls" style="margin-left:28%">
<input type="text" class="span11" placeholder="Event name" name="ename" id="ename" style="width:95% !important;margin-left: -28px !important;">
<span class="span11" id="show_ename" style="display:none;width:95% !important;margin-left: -28px !important;background-color:white;font-size:15px;"></span>
</div>
</div>
Ajax code in View page:
$('#ename').keyup(function(){
$.ajax({
url:'<?php echo site_url()."/admin_c/get_values_c";?>',
method:'post',
data:{'ename':$(this).val()},
success: function(res,res1){
$('#show_ename').show();
$('#show_ename').html('');
$('#show_ename').html(res);
}
});
});
$('#show_ename').click(function(){
var ename_value = $(this).html();
$('#ename').val(ename_value);
$(this).html('');
$(this).hide();
});
The working of this code is attached for reference:
The problem is you are tying to copy all the output that is echoed from server to the input box.
Since the output from http://your-siteurl/admin_c/get_values_c contains <br> tag the input box will just try to print. html input box does not render html elements . it just print html tags if there is any.
so to do what you want, i suggest these edits .
1st one is on Controller page->admin_c.php , before implode function, use :
foreach ($res as $key => &$value){
$value = "<div class='innerelement'>".$value."</div>";
}
echo implode("<br>",$res);
2nd replace your jquery click fuction by this code:
$("#show_ename").on("click",".innerelement", function(){
var ename_value = $(this).html();
$('#ename').val(ename_value);
$(this).html('');
$('#show_ename .innerelement').hide();
});
Note that in url:'<?php echo site_url()."/admin_c/get_values_c";?>' there is an extra "/" after siteurl() function call replace like this :
url:'<?php echo site_url()."admin_c/get_values_c";?>'
or use
url:'<?php echo site_url('admin_c/get_values_c');?>
I have multiple checkboxes displayed from MySQL table. I'm trying to pass all checked values to <div> using ajax. Currently, my code only passes one checked value to <div>. I want to display all checked values in a <div>.
What I have thus far:
<?php
$sql="SELECT * FROM options WHERE cat_id='".$id."' AND opg_id='".$group."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){ ?>
<input type="checkbox" name="<?php echo $row['op_id']; ?>" onClick="showPrice(this.name)" value="<?php echo $row['price']; ?>"/>
<!-- Display all prices from mysql table in checkbox. Pass `id` to ajax from name attribute. -->
<?php
} ?>
ajax
<script>
function showPrice(name) {
$.ajax({
url: 'ajax_price.php',
type: 'GET',
data: {option : name},
success: function(data) {
document.getElementById('c').innerHTML =data;
}
});
}
</script>
ajax_price.php
<?php
include ("../supplier/DB/db.php");
$id = $_REQUEST['option'];
<?php
$sql="SELECT * FROM options WHERE op_id='".$id."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
?>
<div class="oder">
<div class="odercol2"><?php echo $row['opt']; ?></div>
<div class="odercol3"><?php echo $row['price']; ?></div>
</div>
<?php
}
?>
This is the display with only one checked value in the <div>. I want to display all the checked values in my <div>.
checkboxes
Results display in this div (div id is "c")
Just change your AJAX function to concat the innerHTML of DIV, like this:
<script>
function showPrice(name) {
$.ajax({
url: 'ajax_price.php',
type: 'GET',
data: {option : name},
success: function(data) {
document.getElementById('c').innerHTML += data;
}
});
}
</script>
Notice this line document.getElementById('c').innerHTML += data;
Hope it works. Thanks
Add a class value in the checkbox
<?php
$sql="SELECT * FROM options WHERE cat_id='".$id."' AND opg_id='".$group."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){ ?>
<input type="checkbox" class="sundarCheckBox" name="<?php echo $row['op_id']; ?>" onClick="showPrice(this.name)" value="<?php echo $row['price']; ?>"/>
<!-- Display all prices from mysql table in checkbox. Pass `id` to ajax from name attribute. -->
<?php
} ?>
Loop using the class name input elements
<script>
$(document).ready(function(){
function showPrice(value){
$.each($('.sundarCheckBox'), function(index, element){
if($(element).is(':checked')){
alert($(element).prop('value'));
}
});
}
});
</script>
I have a two-part ajax form that submits data to a php file to process the request on the server-side and return the results.
Here is the HTML form:
<div id="new_loc">
<form id="loc_form" method="post" action="">
<p><b>Country Name</b><br />
<select id="country" name="country" tabindex="1">
<option value="">Choose One</option>
<?php
$cq = mysql_query("SELECT * FROM crm_countries WHERE country_status = '1' ORDER BY country_name ASC");
while($rowc = mysql_fetch_assoc($cq)) {
echo '<option value="' . $rowc['country_code'] . '">' . ucwords(strtolower($rowc['country_name'])) . '</option>';
}
?>
</select></p>
<p id="state_list"><b>State Name</b><br />
<select id="state" name="state" tabindex="2">
<option value="">Choose One</option>
</select></p>
<p><b>City Name</b><br />
<input type="text" id="city" name="city" size="30" tabindex="3" /></p>
<p><b>Zip Code</b><br />
<input type="text" id="zip" name="zip" size="7" tabindex="4" /></p>
<p><input type="submit" id="save_zip" name="save_zip" value="Save" tabindex="5" /></p>
</form>
</div>
Then here is my jquery code to send the data to the PHP file and receive the response:
$(function(){
// THE AJAX QUERY TO GET THE LIST OF STATES BASED ON THE COUNTRY SELECTION
$('#country').change(function(){
// DISPLAYS THE LOADING IMAGE
$("#state_list").html('<img src="images/Processing.gif" />');
var ctry = $('#country').val();
$.ajax({
type: "POST",
url: "ajax.php",
data: {c:ctry}
}).done(function(result) {
$("#state_list").html("<b>State Name</b><br />" + result);
});
});
// THE AJAX QUERY TO SAVE THE NEW ZIP CODE TO THE DATABASE
$('#loc_form').submit(function(){
// DISPLAYS THE LOADING IMAGE
$("#new_loc").html('<img src="images/Processing.gif" />');
var sz = $('#save_zip').val();
var ct = $('#country').val();
var st = $('#state').val();
var ci = $('#city').val();
var zc = $('#zip').val();
$.ajax({
type: "POST",
url: "ajax.php",
datatype: "text",
data: {save_zip:sz,country:ct,state:st,city:ci,zip:zc}
}).done(function(result) {
$("#new_loc").html(result);
}).fail(function() {
$("#new_loc").html('<div class="failure">An error occurred. The form could not be submitted.</div>');
});
});
});
And lastly here is the PHP code (in one file called ajax.php) that processes the code:
<?php
session_start();
require ROOT_PATH . '/config.php';
require LAN_PATH . 'english.php';
// GETS THE STATE LIST BASED ON THE COUNTRY SELECTED
if($_POST['c']) {
$sq = mysql_query("SELECT * FROM crm_states WHERE state_country = '{$_POST['c']}' ORDER BY state_name ASC");
$sRows = mysql_num_rows($sq);
if($sRows < '1') {
$result = '<i>Error: No states found!</i>';
}
else {
$result .= '<select id="state" name="state" tabindex="2">';
while($rows = mysql_fetch_assoc($sq)) {
$result .= '<option value="' . $rows['state_abbr'] . '">' . $rows['state_name'] . '</option>';
}
$result .= '</select>';
}
echo $result;
}
// SAVES THE NEW ZIP CODE TO THE DATABASE
if($_POST['save_zip']) {
$zcq = mysql_query("SELECT * FROM crm_zip_codes WHERE zip_code = '{$_POST['zip']}' AND zip_state = '{$_POST['state']}' AND zip_country = '{$_POST['country']}'");
$zcRows = mysql_num_rows($zcq);
if($zcRows == '1') {
$result = '<div class="failure">' . ZIP_EXISTS . '</div>';
}
else {
$azq = mysql_query("INSERT INTO crm_zip_codes VALUES('{$_POST['zip']}','{$_POST['city']}','{$_POST['state']}','{$_POST['country']}','','1')");
$azRows = mysql_affected_rows();
if($azRows != '1') {
$result = '<div class="failure">' . ZIP_ERROR . '</div>';
}
else {
$result = '<div class="success">' . ZIP_ADDED . '</div>';
}
}
echo $result;
}
?>
The first AJAX call seems to work just fine. The data is submitted to the PHP file and a result is returned -> Either the values for the state select form, or the text error message.
The second AJAX call is giving me problems. The information appears to be submitted, but no result (positive or negative) is retunred from the PHP file. I have tested the PHP file through direct $_GET and $_POST requests and it works fine.
I am very new to jQuery, so I don't know where I'm getting stuck. Any help is greatly appreciated.
Thanks!
You need:
$('#loc_form').submit(function(e){
e.preventDefault();
...
});
preventDefault() is needed to prevent the default submission of the form from occurring after the handler runs. The normal submission was reloading the page.
The submit event is being called and your <form> is directing the browser to nowhere action=""
Either don't use a submit button (aka use <input type="button"> or <button>) which would also require changing .submit() to .click() or use the submit button but cancel the default action.
$('#loc_form').submit(function(evt) {
var e = evt || window.event;
e.preventDefault();
...
});
Cheers
I am trying to populate drop down lists one after the other. These drop down lists contain categories and subcategories. I would like to continue creating drop down lists until there are not more subcategories for a particular category.
I am populating my drop down lists with results from MySQL.
I have searched all over and could not find any references to cascading drop down lists using more than two lists.
My code works for two lists, but not for more.
partRequest.php
<HTML>
<HEAD>
<script type="text/javascript" src="..\jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#1").change(function(e) {
e.preventDefault();
getNextCategory("1");
});
$("#2").change(function(e) {
e.preventDefault();
getNextCategory("2");
});
$("#3").change(function(e) {
e.preventDefault();
getNextCategory("3");
});
});
function getNextCategory(htmlID) {
var categoryID = ""
var newHTMLID = 0
var newCategory = ""
categoryID = $("#" + htmlID ).val();
newHTMLID = Number(htmlID) + Number(1)
newCategory = "category" + newHTMLID
$.ajax({
type: "POST",
url: "findNextCategory.php",
data: "ID=" + categoryID + "&Number=" + newHTMLID,
success: function(output){
$("#" + newCategory).html(output);
}
});
}
</script>
</HEAD>
<BODY>
<form name="partSubmissionForm" id="partSubmissionForm" action="" method="POST">
<table width=147 cellpadding=0 cellspacing=0>
<tr><td><select id="1">
<?PHP
$query = "SELECT Name, ID FROM categories WHERE ParentID = 0";
$result = mysql_query($query);
while ($row=mysql_fetch_array($result)){
?>
<option value="<? echo $row['ID'];?>"> <? echo $row['Name'];?></option>
<?}?>
</select>
</td>
<td>
<div id="category2">
test2
</div>
</td>
<td>
<div id="category3">
test3
</div>
</td>
</tr>
<tr><td><input type="submit" name="submit" id="submit" value="GO"></td></tr>
</table>
</form>
</BODY>
</HTML>
findNextCategory.php
<?PHP
define('INCLUDE_CHECK',true);
include ('..\db.php');
$categoryID = $_POST['ID'];
$categoryFieldNum = $_POST['Number'];
echo $categoryID;
echo $categoryFieldNum;
$query = "SELECT Name, ID FROM categories WHERE ParentID = $categoryID";
echo $query;
echo "<select id=$categoryFieldNum>";
$query = "SELECT Name, ID FROM categories WHERE ParentID = $categoryID";
$result = mysql_query($query);
while ($row=mysql_fetch_array($result)){
$optionValue = $row['ID'];
$optionText = $row['Name'];
echo "<option value='$optionValue'> $optionText </option>";
}
echo "</select>";
?>
The problem is that your click function definitions only apply to items that are already on the page at page load. Because you do not yet have a select object on the page with an id of "2", your $("#2").change function does not ever get attached.
What you need to do to get around this is to apply that click definition after you add the select to the page. Try changing your success function to this:
success: function(output){
$("#" + newCategory).html(output);
$("#" + newHTMLID).change(function(e) {
e.preventDefault();
getNextCategory(newHTMLID);
});
}
I will probably sound or look dumb by this but I need to learn. Check out the following part of a code:
$('.buttonclass').click(function(){
var button_id = $(this).attr('id');
$('#'+button_id).click(function(){
var yes = $("input#yes").val();
if (yes == "") {
return false;
}
var id = $("input#id").val();
if (id == "") {
return false;
}
var dataString = 'yes='+ yes + '&id=' + id;
//try insted this //alert (dataString);return false;
$.ajax({ type: "POST", dataType:'HTML',
//or the appropiate type of data you are getting back
url: "http://www.edshaer.com/EdinburgCISD/Gorena/Gorena.php", data: dataString,
//in the php file do $email = $_POST['email'];
//not a good practice but you can try with it and without it
success: function(data) {
$("#div").hide(data).fadeOut();
$("#div").html(data);
$("#div").show(data).fadeIn();
// Change the content of the message element
// Fade the element back in
} });
//ajax ends
return false; });
//click ends
});//document ready ends
My button ID that is being submitted in my html page is sending random numbers. For example
It can be:
$("#383").click(function() {
or it can be:
$("#521").click(function() {
My question is, how do I do it to auto increment the ID of the button clicked so that no matter what ID number is clicked it will still run the run the code smoothly... Right now I have this:
$('.buttonclass').click(function(){
var button_id = $(this).attr('id');
$('#'+button_id).click(function(){
Hopefully someone can help me... let me know if you need more info... Thank you in advanced...
Here is part of my HTML code... Hopefully it will be a little more understandable...
<?php
$data3 = mysql_query("SELECT * FROM `EdinburgCISDGorenamessage`
ORDER BY `ID` DESC LIMIT 0, 100")
or die(mysql_error());
echo "<div id=\"div\"> <table align=\"center\" width=\"570\">";
while($info3 = mysql_fetch_array( $data3 ))
{
$id = $info3['ID'];
}
?>
<form name="contact" id="post" method="post" action="">
<input id="id" value="<?php echo $id?>"/>
<input type="submit" class="buttonclass" id="<?php echo $id?>" name="<?php echo $id?>" value="Yes" />
<input type="submit" id="no<?php echo $id ?>" name="no<?php echo $id ?>" value=" No " /> </form>
I don' want to provide the whole code because its too messy and it doesn't go with the question... Let me know if you need anything else.
Use a class instead. Add a class to the button, and an incremental id you give it while printing it out in your html (I suppose you echo buttons in a loop?), and then just use one snippet:
$('.buttonclass').click(function(){
var button_id = $(this).attr('id');
$('#'+button_id).click(function(){
// your function here
alert(button_id); // just to see if ID is retrieved
)};
});
So, if you have
<button id="325" class="buttonclass" type="button">BUTTON 325</button>
<button id="150" class="buttonclass" type="button">BUTTON 150</button>
The ID of the button you click is retrieved only when you press it