I have the following code which when div clicked converts the div into a dropdown - works perfectly, however, I have "on change" set to submit the form and it passes all data apart from the option selected in the dropdown/select element, any ideas?
This is the js
<script type="text/javascript">
$(document).ready(function(){
var choices = "<select class='choices_dropdown' name='list_name' onchange=\"this.form.submit();\">"+"<option value='My list'>My list</option>"
<?php
// this loads the select element
$wishes4 = mysql_query("select event_id from user_events where user_id = '$userfromcookie'",$db);
while ($databack444 = mysql_fetch_array($wishes4)) { // cc
$wishes5 = mysql_query("select event from events_master where event_id = '$databack444[event_id]'",$db);
$databack555 = mysql_fetch_array($wishes5);
echo "+\"<option value='".$databack555[event]."'>".$databack555[event]."</option>\"";
} // close CC
?>
+"</select>";
$(".update").click(function() {
var $this = $(this),
currentChoice;
// don't continue if there's already a select in this cell
if ($this.find("select").length != 0)
return;
currentChoice = $this.html();
var $choices = $(choices);
$this.empty().append($choices);
$choices.val(currentChoice);
});
$(document).on("change", ".choices_dropdown", function() {
var $this = $(this);
$this.parent().html($this.val());
$('#event_update').submit(); /* this submits the form */
return false;
});
});
</script>
and the html which displays the div is:
echo '<td class="update">
<form action=/list2.html method=post id=event_update>'
.$databack33[list_name].
'<input type="hidden" name="wishlist_id" value='
.$databack33[list_id].
'>
<input type="hidden" name="action" value="update_list">
</form></td>';
Related
I have a block of code which is a dynamically generated div with a form (based on array loop) that has dynamic inputs which are added by a button:
<?php foreach($tickerDisplays as $key => $ticker):?>
<form id="Items" method="post">
<label id="ItemLabel">Item 1: </label>
<input type="text" name="Items[]"><br/>
<button type="button" class="moreItems_add">+</button>
<input type="hidden" name="tickerID" id="tickerID" value="<?php echo $ticker['ticker'] ?>">
<input type="submit" name="saveTickerItems" value="Save Ticker Items">
</form>
<?php endforeach;?>
<script type="text/javascript">
$("button.moreItems_add").on("click", function(e) {
var tickerID = $('#tickerID').val();
var numItems = $("input[type='text']", $(this).closest("form")).length;
if (numItems < 10) {
var html = '<label class="ItemLabel">Item ' + (numItems + 1) + ': </label>';
html += '<input type="text" name="Items[]"/><br/>';
$(this).before(html);
console.log(tickerID);
}
});
</script>
That code above is working and simply allows the '+' button to add a new input. I'm getting the input values as well as the tickerID from my hidden input in preparation for ajax submission. I'm getting what I expect from the serialized form but I have an issue.
The following code:
<script type="text/javascript">
$("#Items").submit(function(e) {
e.preventDefault();
var data = $("#Items").serialize();
console.log(data);
});
</script>
Prints this:
Items%5B%5D=this&Items%5B%5D=is&Items%5B%5D=test&tickerID=1
Which I expect. The problem is that with my ajax call to my mysql insert function, I need to insert one record for each value plus the tickerID. My sql insert is inserting into columns tickerID and content. So for the above console.log, I would need the following insert:
tickerID | content
----------------------
1 this
1 is
1 test
How can I properly pass my form data to the ajax and then do something like a foreach in order to insert multiple records?
ajax call
<script type="text/javascript">
$("#Items").submit(function(e) {
$.ajax({
type: "POST",
url: addticker.php,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
addticker.php
$tickerID = $_POST[''];
$content = $_POST[''];
$addTicker = "
INSERT INTO tickerTable (tickerID, content)
values ('$tickerID', '$content');
"
$mysqlConn->query($addTicker)
Hope this works.
$items = $_POST['Items'];
$tickerID = $_POST['tickerID'];
foreach ($items as $item){
$addTicker = "
INSERT INTO tickerTable (tickerID, content)
values ('$tickerID', '$item');
"
$mysqlConn->query($addTicker);
}
I have an ajax autocomplete where it returns the full name of the user. However, when there are instances where some names or values are the same, it doesn't return the correct value. Rather, it returns the first value in the dropdown. Even if it has 4 same occurences, it still returns the first value.
When I click Stannis Arryn Baratheon, it returns Stannis Targaryen Baratheon.
Here is my php code (sql/php code; ad.php):
<?php
include('config.php');
if($_POST)
{
if($_POST['search_keyword'])
{
$similar = mysql_real_escape_string($_POST['search_keyword']);
$result=mysqli_query($conn, "SELECT * FROM person WHERE (firstName like '" . $_POST["search_keyword"] . "%' OR lastName like '" . $_POST["search_keyword"] . "%') AND residentOrNot = 'Yes' ");
if (mysqli_num_rows($result) > 0) {
while($row=mysqli_fetch_array($result))
{
//$name = $row['fullname'];
//$copiedname = $row['fullname'];
//$b_name= '<strong>'.$similar.'</strong>';
//$final_name = str_ireplace($similar, $b_name, $name);
?>
<div class="show" align="left">
<span class="returnName"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
<span class="returnID" style="display:none"><?php echo $row['idPerson'];?></span>
</div>
<?php
}
}
else {
?>
<div class="show" align="left">
<span class="returnMessage">No matching records found.</span>
</div>
<?php
}
}
mysqli_close($conn);
}
?>
HTML input form:
<form method="post" action="try.php" name="try">
<div class='web'>
<input type="text" class="search_keyword" id="search_keyword_id" placeholder="Search" />
<input type="hidden" name="resID" id="resID"/>
<div id="result"></div>
<input type="submit" name="try" value="Submit">
</div>
AJAX/JS/JQUERY CODE (i think this is where the problem occurs):
<script type="text/javascript">
$(function(){
$(".search_keyword").keyup(function()
{
var search_keyword_value = $(this).val();
var dataString = 'search_keyword='+ search_keyword_value;
if(search_keyword_value!='')
{
$.ajax({
type: "POST",
url: "ad.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}
return false;
});
jQuery("#result").on("click", function(e)
{
/*var $clicked = $(e.target);
var $name = $clicked.find('.returnName').html();
var decoded = $("<div/>").html($name).text();
$('#search_keyword_id').val(decoded);
var $clicked = $(e.target);
var $id = $clicked.find('.returnID').html();
var id = $("<div/>").html($id).text();
$('#resID').val(id);
*/
$name = $('span.returnName',this).html();
$name = $("<div/>").html($name).text().toString();
$('#search_keyword_id').val($name);
$id = $('span.returnID',this).html();
$id = $("<div/>").html($id).text().toString();
$('#resID').val($id);
});
jQuery(document).on("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search_keyword")){
jQuery("#result").hide();
}
});
});
</script>
It really returns the first value even if I click the second or third or fourth value. Where did I go wrong in my code? Please help me. Thank you so much!
Your code is currently collecting all elements with class returnName in #result, and by calling .html() on that collection jQuery will only return the html of the first element found. The same goes for the your returnID search. This is why you are only getting the first returned entry.
Modify your #result click handler to only trigger for elements with class show, since that is the element that will contain your data.
jQuery("#result").on("click", ".show", function(e){
Then all you have to do is search for the elements with class returnName and returnID and call .text().
var showName = $('.returnName',this).text();
var showId = $('.returnID',this).text();
$('#search_keyword_id').val(showName);
$('#resID').val(showId);
So all together
jQuery("#result").on("click", ".show", function(e){
var showName = $('.returnName',this).text();
var showId = $('.returnID',this).text();
$('#search_keyword_id').val(showName);
$('#resID').val(showId);
});
Though note there are probably better ways of returning your data, and utilizing it rather than transporting it in html elements. For example use data-* attributes instead of using a separate span element to contain your id.
Another option is to use jQuery-UI's autocomplete that does most of the client side work for you and just return the raw data in JSON format from your php script.
In your php code, change this:
<div class="show" align="left">
<span class="returnName"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
<span class="returnID" style="display:none"><?php echo $row['idPerson'];?></span>
</div>
With this:
<div class="show" align="left">
<span class="returnName" data-id="<?php echo $row['idPerson'];?>"><?php echo $row["firstName"].' '.$row["middleName"].' '.$row["lastName"]; ?></span>
</div>
And your new jquery function:
jQuery("#result").on("click","'.returnName" function(e)
{
var choosenName = $(this).html();
var choosenId = $(this).data('id');
$('#search_keyword_id').val(choosenName );
$('#resID').val(choosenId );
});
I have a dropdown list, via <select>, that is being generated by a javascript code, which is also coming from my database:
function dirfunc(){
var dirdiv = document.getElementById("dirdiv");
var ahref = document.getElementById("href");
var directidarr = new Array();
var directorarr = new Array();
<?php
include("../conn.php");
if($stmt = $con->prepare("SELECT directorid,directorname FROM directortb")){
$stmt->execute();
$stmt->bind_result($directorid,$directorname);
$counter = 0;
while($stmt->fetch()){
?>
directidarr[<?php echo $counter; ?>] = "<?php echo $directorid; ?>";
directorarr[<?php echo $counter; ?>] = "<?php echo $directorname; ?>";
<?php
$counter = $counter + 1;
}
$stmt->close();
}
?>
var div = document.createElement("div");
div.setAttribute("class","form-group");
var label = document.createElement("label");
label.setAttribute("class","col-sm-2 control-label");
label.appendChild(document.createTextNode("Director"));
var div2 = document.createElement("div");
div2.setAttribute("class","col-sm-9");
var sel = document.createElement("select");
sel.setAttribute("name","director");
sel.setAttribute("class","form-control");
for (var x = 0; x < directidarr.length; x++){
var opt = document.createElement("option");
opt.appendChild(document.createTextNode(directorarr[x]));
opt.setAttribute("value", directidarr[x]);
sel.appendChild(opt);
}
var div3 = document.createElement("div");
div3.setAttribute("class","col-sm-1");
var div4 = document.createElement("div");
div4.setAttribute("class","input-group");
div2.appendChild(sel);
div3.appendChild(ahref);
div.appendChild(label);
div.appendChild(div2);
div.appendChild(div3);
dirdiv.appendChild(div);
}
In my HTML code, where it generates the dropdown, on its right side is a button that would show a modal. In this modal is a form that would allow users to add more option for the select dropdown.
Here is the script I am using to add data without refreshing the page:
$(function() {
$("#adddirector").click(function(e) {
e.preventDefault();
var directorname = $("#directorname").val();
var dataString = 'directorname=' + directorname;
if(directorname == '')
{
$('.success').fadeOut(200).hide();
$('.error').fadeIn(200).show();
}
else
{
$.ajax({
type: "POST",
url: "../action.php",
data: dataString,
success:{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
With this form:
<form class="form-horizontal" action="../action.php" method="POST">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Director's Name</label>
<div class="col-sm-10" id="ccdiv">
<input type="text" class="form-control" name="directorname" id="directorname" value="" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" name="adddirector" id="adddirector">Add Director <span class="glyphicon glyphicon-plus"></span></button>
</div>
</div>
</form>
But after adding a new data, through the form or the back-end/phpmyadmin, the dropdown is not updating. User has to still refresh the page in order for the dropdown to be updated. What am I missing or should do with my script?
I'm assuming the form to create a new Director sends an ajax request on submit, that is handled by some PHP code which will update the database with this new entry.
I suggest that, in this PHP code, you return the id of the newly inserted entry. You can then add a "success" function to your ajax call, which will receive that new id once it is inserted, so you can use it to add a new row to your select box.
EDIT:
$(function() {
$("#adddirector").click(function(e) {
e.preventDefault();
var directorname = $("#directorname").val();
//in jQuery you can pass an object, directorname will now show up as $_POST['directorname'] in your PHP handler.
var dataObj = {'directorname': directorname}
if(directorname == '')
{
$('.success').fadeOut(200).hide();
$('.error').fadeIn(200).show();
}
else
{
$.ajax({
type: "POST",
url: "../action.php",
data: dataObj,
//success function should receive the id back as result
success: function(result){
var newId = result;
// create and append the new option here with the new id and the given name.
var newOption = $('<option></option>');
newOption.val(result);
newOption.html(directorname);
$('.form-control[name="director"]').append(newOption)
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
And make sure that your php file action.php echoes the new id at the end of file! If you want me to take a look at that please post the code in that file also.
Here's a question from stackoverflow might help you with php. Getting insert id with insert PDO MySQL
I'm making a simple list application and the items should be easy to edit (just clicking on them). It works fine, but I still have a problem at saving the changes to the database, for some reason it doesn't happen. I'm sure it's a code problem, but I haven't been able to find it.
List Page
<input type="hidden" id="hidden" id="hidden" value="">
<ul id="lista">
<?php
$IDllista = 1;
$selectitems = mysql_query ("SELECT * FROM items WHERE IDllista=".$IDllista." ORDER BY posicio ASC") or die (mysql_error());
while ($row = mysql_fetch_array($selectitems))
{
echo'<li class="item" id="';
echo $row['IDitem'];
echo '"><span class="edit" id="span-';
echo $row['IDitem'];
echo '" data="';
echo $row['Text'];
echo '">';
echo $row['Text'];
echo'</span></li>';
}
?>
</ul>
JavaScript
//Call the edit function
$(".edit").live("click", function () {
// Get the id name
var iditem = $(this).parent().attr("id");
var element = this;
var id = element.id;
//New text box with id and name according to position
var textboxs = '<input type="text" name="text' + id + '" id="text' + id + '" class="textbox" >'
//Place textbox in page to enter value
$('#'+id).html('').html(textboxs);
//Set value of hidden field
$('#hidden').val(id);
//Focus the newly created textbox
$('#text'+id).focus();
});
// Even to save the data - When user clicks out side of textbox
$('.edit').focusout(function () {
//Get the value of hidden field (Currently editing field)
var field = $('#hidden').val();
//get the value on text box (New value entred by user)
var value = $('#text'+field).val();
//Update if the value in not empty
if(value != '') {
//Post to a php file - To update at backend
//Set the data attribue with new value
$(this).html(value).attr('data', value);
$.ajax({
type: 'POST',
data: {id: iditem},
url: 'editartext.php'
});
}
// If user exits without making any changes
$(".edit").each(function () {
//set the default value
$(this).text($(this).attr('data'));
});
});
Edit Page
<?php
include_once "../connect.php";
$IDitem = $_POST['id'];
$noutext = "hola";
$actualitza = mysql_query ("UPDATE items SET Text = ".$noutext." WHERE IDitem = ".$IDitem." ");
?>
Quote problem i think. You can use query with single quote like;
"mysql_query("UPDATE items SET Text ='$noutext' WHERE IDitem ='$IDitem'");
I have a below javascript function which updates the display values when I move the slider. However, now I am planning to update the values only on the button click. This is the javascript function.
.on("slider:ready slider:changed", function (event, data) {
var $output =$(this).nextAll(".output:first");
$output.html(data.value.toFixed(2));
masterData[$output.attr("id").replace(/output/,"")] = data.value;
$("#kwBody > tr").each(function() {
var $cells = $(this).children("td");
var found=false,count=0,currentCell;
for (var i=0;i<masterData.length;i++) {
currentCell=$cells.eq(i+1);
found = parseInt(currentCell.text(),10) >=masterData[i];
currentCell.toggleClass("found",found); //add or remove class to highlight
count+=found;
}
window.console && console.log(masterData,count);
$(this).toggle(count==masterData.length); // show if all cells >
});
});
});
I designed a button as below.
<button onclick="myFunction()">Display!</button>
I included the above javascript function inside myfunction(). However, the update is not happening on the button click. A working example can be found here.
EDIT:
<h2>Keyword Scores</h2>
<?php
$i = 0;
while (++$i <= $_SESSION['totalcolumns']-1) {
isset($_GET["slider$i"]) ? $rangevalue=$_GET["slider$i"] : $rangevalue="";
$range = $_SESSION["min-column-$i"] . ',' . $_SESSION["max-column-$i"];?>
<br><?php echo "Keyword" ?>
<?php echo $i ?>
<br><input type="text" data-slider="true" id="slider<?php echo $i; ?>" data-slider-range="<?php echo $range ?>" autocomplete="off" value="<?php echo $rangevalue; ?>" data-slider-step="1">
<meta http-equiv="refresh">
<?php } ?>
<script>
Add an 'id' attribute to the button. Say it is 'myButton'. Now,
I'm assuming that the var masterData is global
Change the slider listener to
.on("slider:ready slider:changed", function (event, data) {
var $output =$(this).nextAll(".output:first");
$output.html(data.value.toFixed(2));
masterData[$output.attr("id").replace(/output/,"")] = data.value;
});
Create a click listener for the button
$("#myButton").click(function (){
$("#kwBody > tr").each(function() {
var $cells = $(this).children("td");
var found=false,count=0,currentCell;
for (var i=0;i<masterData.length;i++) {
currentCell=$cells.eq(i+1);
found = parseInt(currentCell.text(),10) >=masterData[i];
currentCell.toggleClass("found",found); //add or remove class to highlight
count+=found;
}
window.console && console.log(masterData,count);
$(this).toggle(count==masterData.length); // show if all cells >
});
});
Simulate button click on each page load.
$(document).ready(function(){
$("#myButton").click();
});
I haven't tried it, but hopefully, it works.