I have auto-complete working, but how do I handle modifications?
What happens when the user modifies the original selection? I've got an auto-complete that, when a listing is chosen, other fields are filled in. If the user chooses a listing, then tries to modify it to something that is new (does not match anything in our DB), the other fields need to be cleared.
Another way of asking: How do I handle 'new' listings?
My code below
$(function() {
$( "#oName" ).autocomplete({
source: "include/organizerList.php",
minLength: 3,
select: function( event, ui ) {
$("input#oID").val(ui.item.oID);
$("input#oCID").val(ui.item.oCID);
$("div#organCity").text(ui.item.oCity);
$("div#organCountry").text(ui.item.oCountry);
}
});
});
organizerList.php
// important to set header with charset
header('Content-Type: text/html; charset=utf-8');
$term = htmlspecialchars(strtolower($_GET["term"]));
$return = array();
$query = mssql_query("SELECT CID, oID, oName, oCity, oCountry FROM TradeShowDB_Organizers WHERE oName LIKE '%$term%'");
while ($row = mssql_fetch_array($query)) {
array_push($return,array( 'oCID'=>$row['CID'], 'oID'=>$row['oID'], 'label'=>$row['oName'] . ', ' . $row['oCity'], 'value'=>$row['oName'], 'oCity'=>$row['oCity'], 'oCountry'=>$row['oCountry'] ));
}
// encode it to json format
echo(json_encode($return));
My html:
<input type="text" tabindex='20' id="oName" name="oName" size="60" maxlength="200" value="<?php echo $oName; ?>">
<div id='organCity'></div>
<div id='organCountry'></div>
<input type="hidden" id="oID" name="oID" value="<?php echo $oID; ?>">
<input type="hidden" id="oCID" name="oCID" value="<?php echo $oCID; ?>">
You can use the autocomplete select event http://jqueryui.com/demos/autocomplete/#event-select
Disable the input once the user selects an option
$("#oName").autocomplete({
source: "include/organizerList.php",
minLength: 3,
select: function (event, ui) {
this.value = ui.item.value;
$('#autocomplete').autocomplete("disable");
$('#autocomplete').trigger('keypress'); //needed to fix bug with enter on chrome and IE
$(this).attr('disabled','disabled');
return false;
},
autoFocus: true
});
http://jsfiddle.net/HKxua/6/
Then in your server side script, you can check the input to see if the value posted exists in the database.
Related
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();
I'm trying to submit my data to my php function (My app is based on an MVC framework), but all it does is erasing my data.
Here is my code in php that i want to replace by an inline x-editable:
<form method="post" action="<?php echo URL; ?>mylist/editSave/<?php echo $this->oneList->list_id; ?>">
<label>Change my list name: </label>
<input type="text" name="list_name" value="<?php echo $this->oneList->list_name; ?>" />
<input type="submit" value='Change' />
</form>
I have tried to do this:
echo '<td>Edit</td>';
But it doesn't work. What i want to do, is send $value->list_id and my new $value->list_name which has to be received by my php function URL/mylist/editSave/
Please help!
Thank you :)
I use success method with own function formatXEditable and you must always disable default display function.
function formatXEditable($item, $val){
$val = $val.replace(/<br\s*\/?>/mg,"\n");
$($item).text($val);
$($item).on('shown', function(e, editable) {
editable.input.$input.val($val);
});
}
$('#identifier').editable({
...
display: function(value, response) {
return false; //disable this method (success displays value information)
},
success: function(response, value) {
if(response.status == 'error') return response.msg; //msg will be shown in editable form
formatXEditable($('#identifier'), response.identifier);
$('#pagesForm-identifier').val(response.identifier);
},
error: function(errors) { }
});
Hope it helps.
I am currently working on this site for a client and I today hit a brick wall when I found I was unable to pass the current value from a jQuery slider to the URL in order to filter results from an SQL query.
Judging from the interface on the site it should be pretty clear what I want to accomplish, a user should be able to select what type of product they want to purchase, this currently refreshes the page and passes the value to the url when the button is pressed.
<form name="pumpType" action="<?php echo $_SERVER['PHP_SELF']; ?>?s=<?php echo $pType ?>&p=<?php echo $pVal ?>&g=<?php echo $gVal ?>" method="get" align="center">
<div class="btn-group" data-toggle="buttons-radio">
<button type="submit" class="<?php if( $pType == 'intermittent' ){ echo 'active '; } ?>btn btn-primary waitingUiBut" id="but1" name="s" value="intermittent">INTERMITTENT</button>
<button type="submit" class="<?php if( $pType == 'continuous' ){ echo 'active '; } ?>btn btn-primary waitingUiBut" id="but4" name="s" value="continuous">CONTINUOUS</button>
</div>
</form>
My client wants the user to be able to further refine the query results once the category has been filtered, I chose to use sliders to accomplish this.
When the sliders value changes I want my SQL query to run, constantly refining the result set ( I assume I will have to use AJAX to do this? Correct me if I am wrong ). The problem I am having is that only the ?s= variable is ever sent to the URL, both ?p and ?g variables do not get recognised.
SQL Query -
$pType = $_GET['s'];
$pVal = $_GET['p'];
$gVal = $_GET['g'];
$sql = "SELECT * FROM pumps
WHERE pump_type='$pType'
AND flow_psi <= '$pVal'
AND flow_gpm <= '$gVal'
AND high_psi <= '$pVal'
AND high_gpm <= '$gVal'";
jQuery Ui Slider Markup -
<div align="center" class="productSlider">
<form name="pumpSlider" action="?s=<?php echo $pType ?>&p=<?php echo $pVal ?>&g=<?php echo $gVal ?>" method="get">
<p class="inlineLabel">PSI</p><div class="filterSlider" id="psiSlider" name="p" value="1000"></div>
<p class="inlineLabel">GPM</p><div class="filterSlider" id="gpmSlider" name="g" value="1000"></div>
</form>
</div>
jQuery slider submission code ( to eventually be handled by AJAX )
$(document).ready(function() {
$("#psiSlider" ).slider({
// options
start: function (event, ui) {
},
slide: function( event, ui ) {
var curValue = ui.value || initialValue;
var target = ui.handle || $('.ui-slider-handle');
var tooltip = '<div class="tooltip"><div class="tooltip-inner">' + curValue + '</div><div class="tooltip-arrow"></div></div>';
$(target).html(tooltip);
},
change: function(event, ui) {
$('#pumpSlider').submit();
}
});
$("#gpmSlider" ).slider({
// options
start: function (event, ui) {
},
slide: function( event, ui ) {
var curValue = ui.value || initialValue;
var target = ui.handle || $('.ui-slider-handle');
var tooltip = '<div class="tooltip"><div class="tooltip-inner">' + curValue + '</div><div class="tooltip-arrow"></div></div>';
$(target).html(tooltip);
},
change: function(event, ui) {
$('#pumpSlider').submit();
}
});
});
Why are my p and g variables not being captured on the form submission? Any suggestions would be most appreciated.
Your problem is that your 'p' and 'g' are both in div tags, and div tags do not have a value attribute. You can use input fields and make them hidden so that you can have values for these.
<p class="inlineLabel">PSI</p><div class="filterSlider" id="psiSlider"></div>
<p class="inlineLabel">GPM</p><div class="filterSlider" id="gpmSlider"></div>
<input type="hidden" name="p" value="1000" />
<input type="hidden" name="g" value="1000" />
Then when you are moving the slider, make sure it is using/replacing the values of the input instead of trying to use a value on the div.
I am trying to autocomplete a text box in my search.php code using autocomplete.php
I know that my php code works perfectly and echo's back exactly what is needed for the autocomplete function in jQuery.
Here is the html for the text box.
<input type="text" name='search' id="search" class="input-block-level" autocomplete="off" placeholder="search...">
Here is my script for the autocomplete function
<script>
jQuery(document).ready(function($){
$('#search').autocomplete({source:'autocomplete.php', minLength:2});
});
</script>
Here is the php file
<?php
if ( !isset($_GET['term']) )
exit;
$conn = odbc_connect('Abilis', 'infosysreader', 'Wilsons12');
$query = "SELECT TOP 10 [Del_ad1] FROM [Abilis].[dbo].[Customers] WHERE Del_ad1 LIKE '%".$_GET['term']."%'";
$rs = odbc_exec($conn, $query);
$data = array();
for($i = 0; $i<odbc_num_rows($rs);$i++){
$row = odbc_fetch_array($rs, $i);
$data[] = array(
'label' => $row['Del_ad1'],
'value' => $row['Del_ad1']
);
}
// jQuery wants JSON data
echo json_encode($data);
flush();
Edit:
I found my error at the end of my html file. It was just a mistake on my part, the method I use above works fine.
Not sure what your problem is but since your PHP correctly returns json encoded string then problem is with autocomplete call. Try this and let me know if it makes any difference:
$('#search').autocomplete({
minLength:2,
source: function(request, response) {
$.ajax({
url: 'autocomplete.php',
dataType: 'json',
data: { term : request.term },
success: function(result) {
response(result);
}
});
}
});
Also try changing autocomplete="off" to autocomplete="on"
Remove the following from input element:
class="input-block-level" autocomplete="off" placeholder="search..."
and try with <input type="text" name='search' id="search" />
So, as the titles says, I need some clarifications on how to make interact jquery, ajax and php in order to realize a form submission and other controls.
This is my first web experience with jquery, ajax and php used all together, and, of course, I'm facing some problems.
I describe what I'm trying to do.
Basically, I've an index page with a registration form:
<form id="formRegistration" action="registration_success.php" method="post">
<p id="ptxtFullName">
<input id="txtFullName" name="txtFullName" class="textbox" placeholder="Insert you full name" type="text" />
</p>
<p id="pTxtEmail">
<input id="txtEmail" name="txtEmail" class="textbox" placeholder="Insert an email" type="text" />
</p>
<p id="pTxtPassword">
<input id="txtPassword" name="txtPassword" class="textbox" placeholder="Choose a password" type="password" />
</p>
<p id="pTxtPasswordConfirmation">
<input id="txtPasswordConfirmation" name="txtPasswordConfirmation" class="textbox" placeholder="Confirm your password" type="password" />
</p>
<p id="pBtnRegistration">
<input id="btnRegistration" type="submit" value="Register!" />
</p>
</form>
Then, I've a jquery file, which does all the input validation things (some effects if the inputs are correct or incorrect, and things like these), and, if the validation went good, makes an ajax call.
This is only an example, I don't post the entire file, because it's quite huge:
jQuery(document).ready(function($) {
$(function() {
var $fullName = $("input[name='txtFullName']");
var $email = $("input[name='txtEmail']");
var $password = $("input[name='txtPassword']");
var $passwordConfirmation = $("input[name='txtPasswordConfirmation']");
$("#btnRegistration").click(function() {
//Validation controls and effects.
});
return true;
});
$.ajax({
type : "POST",
url : "process_registration.php",
data : "fullName", "email", "password",
dataType : "HTML",
success : function() {
alert("Ok");
},
error : function() {
alert("Error");
}
});
});
NOTE that, the jquery file, when I add the ajax call, it stops to work, whilst if I don't add the ajax call, it works perfectly.
And then, here's my php file, named process_registration.php, wich is supposed to control if the email is already in use, and, after that, to insert the validated input datas into a MySQL database:
<?php
require 'db_connection.php';
$fullName = isset($_POST["fullName"]);
$email = isset($_POST["email"]);
$password = isset($_POST['password']);
$sql = mysql_query("SELECT * FROM utente WHERE mail = '$email'") or die("Email already in use");
$num_rows = mysql_num_rows($sql);
if ($num_rows == 0)
{
$password_md5 = md5($password);
mysql_query("INSERT INTO user (Full_Name , Email, Password) VALUES
('$fullName', '$email', '$password_md5')") OR DIE(mysql_error());
}
Thats all.
Obviously it isn't working.
Maybe I'm adopting a completely wrong approach in this thing?
Thanks in advance for your kindess and your answers.
Try using this:
jQuery(document).ready(function($) {
$('#formRegistration').submit(function() {
e.preventDefault();
// Perform form validation here and return from this function
// if you do not want to submit the form.
$.ajax({
type : "POST",
url : "process_registration.php",
data : $(this).serialize(),
dataType : 'html',
success : function() {
alert("Ok");
},
error : function() {
alert("Error");
}
});
});
});
This registers an event handler that gets called when the form is going to be submitted. The call to e.preventDefault() prevents the regular form submission. Then the handler posts the form via ajax.
You'll have to change the names of the input elements though because they need to match the names your PHP code is looking for (e.g., change "txtFullName" to "fullName").
The data attribute in the ajax call is supposed to be an object.
data : {
"fullName" : fullName,
"email" : email
}