I have the code that dynamically generates textboxes and select boxes upon a button click. I want to fetch the data from DB and display in the dynamically generated select box.
Fiddle http://jsfiddle.net/hEByw/11/ shows how the text and selectboxes are generated dynamically.
I have tried the following part of code to fetch the data from DB and Put into dynamically generated select box(Tax Type) but its not working for me.
//To Display the tax types from DB
$(function(){
var items="";
$.getJSON("get_tax_type.php",function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.id+"'>"+item.name+"</option>";
});
$("#tax_type' + counter + '").html(items);
});
});
I feel the way I am doing is wrong.Can anybody suggest where am I doing wrong or the proper way of implementing it. I am newbie in jquery. Any help is appreciated.Thanks in advance.
PHP Code(get_tax_type.php)
<?php
include('includes/db.php');
$q = "select TaxID, TaxName from tax";
$sql = mysql_query($q);
$data = array();
while($row = mysql_fetch_array($sql, true)){
$data[] = $row;
};
echo json_encode($data);
?>
Try this. UPDATED
$(document).ready(function() {
var items = "";
$.getJSON("get_tax_type.php", function(data) {
alert(data);
$.each(data, function(index, item) {
$("#tax_type" + parseInt(index) + parseInt(1)).empty();
$("#tax_type" + parseInt(index) + parseInt(1)).append("<option value='" + item.TaxID+ "'>" + item.TaxName+ "</option>");
});
}, 'json');
});
Related
I've been trying to come up with a solution for this problem. I thought .live() would help but it isn't used in jquery 1.9.1
I have this function - the gist of which is this:
while($row = $result->fetch_assoc()) {
$currentID = $row['UserID'];
$query2="SELECT FirstName, LastName, UserID FROM Users WHERE UserID = $currentID";
$result2 = $mysqli->query($query2);
$row1 = $result2->fetch_assoc();
echo '<div class="commentEntry">';
echo "<h5><a href='user.php?User=".$row1['UserID']."'>".$row1['FirstName']." ".$row1['LastName']."</a></h5>";
echo "<p>".$row['Content']."</p>";
echo "<p class='agree'>Agree</p>";
echo "</div>";
}
This function works, it isn't the issue.
So essentially with jquery I want to get hold of all dynamically added instances of a.agreeWith.
To test, I am using this:
$(document).ready(function() {
$('a.agreeWith').click(function(event) {
event.preventDefault();
alert("test");
var agree = $(this).id;
var data = 'Agree=' + agree.val();
});
});
Now what I find isn't happening, is that the alert never appears. The a href link still triggers and so clearly there is no call.
I have tested it simply by writing whatever into the page, and it works, the alert appears.
So clearly there is an issue with dynamically loaded information and trying to apply jquery to it.
The question is. How do I get around this?
Thanks for your help.
This should work for you at least to get your alert working. Not sure what your trying to do after....
$(document).ready(function() {
$(document.body).on('click', 'a.agreeWith', function(event) {
event.preventDefault();
alert("test");
var agree = $(this).id;
var data = 'Agree=' + agree.val();
});
});
please take a look of this:
$(function () {
$("#add").click(function() {
val = $('#add_lang').val();
val1 = $('#add_lang_level').val();
listitem_html = '<li>';
listitem_html += val + ' <strong>('+ val1 + '/100)</strong>';
$.ajax({ url: 'addremovelang.php', data: {addname: val,addlevel: val1}, type: 'post', success: function(output) { alert(output); }});
listitem_html += 'Remove'
listitem_html += '</li>';
$('#langs').append(listitem_html);
});
$('.remove_lang').live('click', function(e) {
e.preventDefault();
$(this).parent().remove();
$.ajax({ url: 'addremovelang.php', data: {delname: val}, type: 'post', success: function(output) { alert(output); }});
});
});
This simple jquery script adds strings to a html list when the user hits the button with the id add. Also, it puts a remove link to each line, so when the user hits remove it triggers the function remove_lang and the string is deleted.
When the users add a string, this text comes from a text field, and i stored it on the variable val (as you can see on the 5 line of the code). Then i call a php script via Ajax to add this info to my mysql database.
But, when the user remove the string, i dont know how to know what string was removed, i mean, the name of this one, that i need to send to my php script in order to remove it from the database.
Take a look of this version of my code without the ajax call: http://jsfiddle.net/wnFsE/
Thanks for any help!!!
When you click remove you can do something like this:
val = $(this).parent().find('input').val();
That will get the value from hidden input you added:
Demo Here
You need to think about the string as instead a group of elements:
var li = $('<li/>');
var strong = $('<strong/>', { text: '(' + val1 + '/100)' });
var link = $('<a/>');
link.click(function()
{
// Insert code here for the link click
});
li.append(strong).append(link);
$('#langs').append(li)
There are other patterns that would work too, like:
$(listitem_html').find('a').click(function()
{
// Insert code here for the link click
});
Just get a reference to the element, and then attach the click event handler.
An Object Oriented Programming approach would help keep the actions very organized. You basically store the actions for each given language in an object, modifying the action for that language whenever it's removed or added.
Here's a live example that will print that "storage" object out to the console every time you add or remove a language so that you can clearly see what's going on.
And here's just the JS code (you'll notice that I barely changed a thing):
languageActions = {}
$(function () {
$("#add").click(function() {
val = $('#add_lang').val();
listitem_html = '<li>';
listitem_html += val;
listitem_html += '<input type="hidden" name="languages[]" value="' + val + '" /> ';
listitem_html += 'Remove'
listitem_html += '</li>';
$('#langs').append(listitem_html);
//now add it to our object
languageActions[val] = 'add';
console.log(languageActions);
});
$('.remove_lang').live('click', function(e) {
e.preventDefault();
val = $(this).prev().val();
$(this).parent().remove();
//now change it's value in languageActions
languageActions[val] = 'remove';
console.log(languageActions);
});
});
The only other thing I'll point out is that you don't really need that hidden input element since you're doing this via AJAX rather than a standard form submit. Instead, you could just do <li><span>Spanish</span><a class="remove_lang">Remove</a></li> for your HTML and then the click event on .remove_lang would do $(this).prev().text() rather than $(this).prev().val(). Not a huge deal, but you're HTML will be a little cleaner.
I guess that would be a simple:
$i = 1;
while(xxx){
//get the list with a different value for each element
echo '<div id="add_' . $i . '>$whatever</div>';
$i++;
}
With thanks to Elf Sternberg (I couldn't get your solution working, sorry), I think I am heading in the right direction, but I am having trouble writing the php to the mysql database.
The original post: jQuery AJAX POST to mysql table for dynamic table data- Am I doing this in anything like the right way?
Firstly, the dynamic table form on my webpage has multiple user input data, and I am using this jQuery function and the AJAX call to send to a php file. Am I correctly creating the multidimensional array here? Firebug shows dataString to have all the data I want, but the POST parameters and source just say dataString. Also the alert function shows the data is all there:
EDIT: With thanks to Jancha and Andrew, I have changed the data source for the AJAX post. The database is being written to now, but only BLANK data gets written, for as many entries as were in the table. The firebug console is showing all the data as it should look in the post. I just don't know how to structure the php loop now.
jQuery(function() {
jQuery(".button1").click(function() {
// process form here
var rowCount = jQuery('#dataTable tr').length;
var dataString = [];
dataString.length = rowCount - 2;
for(var i=2; i<rowCount; i++) {
var txtRow1 = jQuery('#txtRow' + (i-1)).val();
var tickerRow1 = jQuery('#tickerRow' + (i-1)).val();
var quantRow1 = jQuery('#quantRow' + (i-1)).val();
var valueRow1 = jQuery('#valueRow' + (i-1)).val();
// previous code: dataString[i-2] = 'txtRow1='+ txtRow1 + '&tickerRow1=' + tickerRow1 + '&quantRow1=' + quantRow1 + '&valueRow1=' + valueRow1;
// new code:
dataString[i-2] = [txtRow1, tickerRow1, quantRow1, valueRow1];
}
//alert (dataString);return false;
jQuery.ajax({
type: "POST",
url: "form_action2.php",
data: { 'data': dataString }
});
return false;
});
});
If this is sending the data okay then I am thinking that the php function needs to look something like this:
Could I have help with the php function please. Thankyou for your time.
$data = $_POST['data'];
foreach ($data as $key => $value){
$txtRow1 = $data['txtRow1'];
$tickerRow1 = $data['tickerRow1'];
$quantRow1 = $data['quantRow1'];
$valueRow1 = $data['valueRow1'];
$sqlinsert = "INSERT INTO stock_port (name, ticker, quantity, value) VALUES ('$txtRow1', '$tickerRow1', '$quantRow1', '$valueRow1')";
mysql_query($sqlinsert, $conn);
}
FINAL EDIT: Ok so this works to enter the data into the database:
$data = $_POST['data'];
foreach ($data as $value){
$txtRow1 = $value[0];
$tickerRow1 = $value[1];
$quantRow1 = $value[2];
$valueRow1 = $value[3];
$sqlinsert = "INSERT INTO stock_port (name, ticker, quantity, value) VALUES ('$txtRow1', '$tickerRow1', '$quantRow1', '$valueRow1')";
mysql_query($sqlinsert, $conn);
}
It seems using data: {'data':dataString} in the AJAX jQuery call means I lost all the variable names of the data sent in the array to POST. Even though this is working, it doesn't feel like the way it should have been done. I have seen others use array structure in their id or names for input on forms, and that seems like it should have been the way to go.
change data: "dataString" to data: dataString or else you are not passing variable but a 'string'.
there is a problem with your foreach statement try this
$data = $_POST['datastring'];
foreach($data as $key => $value){
$txtRow1 = $data['txtRow1'];
}
It is not tested still you try once
I'm trying to sort images using: http://jqueryui.com/demos/sortable/display-grid.html
And then somehow submit the newly sorted array/results into a MySQL Database using PHP?
I'm having difficulty figuring this out (newby alert), so if anyone can shed some light on this, I'll be dishing out hi-5s like there's no tomorrow.
Cheers
In particular you need to look at attaching an event to the sortable
http://jqueryui.com/demos/sortable/#event-update
and serialize for getting the relevant content http://jqueryui.com/demos/sortable/#method-serialize
EDIT
This is a primitive version of what you need to do.
<script>
$(function() {
var arrayOfIds = [];
$( "#sortable" ).sortable({
update: function(event, ui) {
$.each($(this).sortable('toArray'), function(key, value) {
arrayOfIds.push(value.replace('el-',''))
});
var jqxhr = $.ajax({
url: "order.php?order="+encodeURIComponent(arrayOfIds),
})
.success(function(response) { console.log("success" + response ); })
.error(function() { console.log("error"); })
.complete(function() { console.log("complete "); });
}
});
$( "#sortable" ).disableSelection();
});
</script>
Each li element than needs an id that your DB can understand
<li class="ui-state-default" id="el-1">1</li>
the "1" in id="el-1" should relate to an id in your DB table. When you reorder, the update event fires, goes through the new order, grabs all the ids and passes that to an ajax request which a php file then can pick up. the order.php script then go split the numbers by the "," and update your table one by one.
e.g.
$itemOrders = explode(',',$_POST['order']);
$sizeOfList = sizeof($itemOrders);for($i=0; $i<$sizeOfList; $i++)
{
$itemId = intval($itemOrders[$i]);
$query = "UPDATE your_table_name SET order_no = '".$i."' WHERE id = '".$itemId."' ";
if ($result = $msHandle->query($query))
{
$message = 'success';
}
else
{
$message = 'fail ';
}
}
There will be a callback function on the sorting event which you can use to send an AJAX request to a PHP script which updates a database. Think of it as after you've made a sorting action (i.e. moving one item around), you send the values (i.e. the ordered list) to a PHP script that takes those values and updates the database. I'll assume you have experience in MySQL as you seem to know the fundamentals of the problem.
Ive got textarea area on each table row with unique ID .
How to retrieve that unique id with javascript?
PHP:
$query = $db->query("SELECT * FROM bs_events WHERE eventDate = '".$date."'");
while($row = $query->fetch_array(MYSQLI_ASSOC)){
echo '<textarea id=\"att_name_" . $row['id'] . "\" style=\"width:300px\"></textarea>";'
}
PHP OUTPUT:
<textarea id="att_name_1" style="width:300px">
<textarea id="att_name_2" style="width:300px">
<textarea id="att_name_3" style="width:300px">
jQuery:
$(document).ready(function(){
$("#book_event").submit(function(){
id = event.target.id.replace('att_name_','');
$.post("Scripts/book_event.php", {
att_name: $("att_name_"+id).val(),
}, function(data){
if(data.success) {
$("#err").text(data.message).fadeIn("slow");
}
}, "json");
});
});
It looks to me like you're naming your textareas to correlate to the database entries, then trying to make updates and pass those values back. Assuming the textareas are in the form you're submitting, you can use:
$('#myform').submit(function(e){
// find each of those text areas
$(this).find('textarea[id^=att_name]').each(function(i,e){
//
// from here-in, e now represents one of those textareas
//
// now submit the update
$.post('Scripts/book_event.php',{
att_name: $(e).val()
},function(data){
if (!data.success)
$("#err").text(data.message).fadeIn("slow");
},'json');
});
e.preventDefault();
});
Ideally though, if you're looking to use AJAX to push updates/changes back to the server, you may look in to .serialize() and push all forms back. Then, on the server-side you'll get the standard $_POST['att_name_1'] values that you can use for your actual updating. e.g.
// .serialize() example
$('#myform').submit(function(e){
$.post('Scripts/book_event.php',$(this).serialize(),function(data){
if (!data.success)
$("#err").text(data.message).fadeIn("slow");
});
e.preventDefault();
});
To solve your problem, you can use each()
$(function()
{
$("textarea").each(function()
{
var textarea_id = $(this).attr('id');
});
});
I don't fully understand the question.
If you want a list of the ids, how about something like:
$(document).ready( function ( ) {
var textareas = new Array();
// Run through each textbox and add the id to an array
$("textarea").each( function( ) {
textareas.push( $(this).attr("id") );
});
// Print out each id in the array
textareas.forEach( function(i) { alert(i); });
});
(that's untested and probably not the quickest way - I'm a bit out of practice)