I have a blog and get data from some SQL-database.
I have a problem to get correct data from a foreach loop and i don't know why. I will try to explain.
For each image there is a textarea where users can put in a comment. For each comment i have to send the corresponding id (ajax) to add to the database.
foreach($db->query("SELECT id, image FROM news") as $row)
{
<a href='images/news/{$row['image']}'><img src='images/news/{$row['image']}'/></a>";
<div class="save_comment">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>
<input type="text" class="_comment_id" name="id" value="<?php print_r($row['id'] );?>" />
Comment:
<textarea id="_comment_text" class="comment_area" name="comment_area" maxlength="400" cols="80" rows="8" ></textarea>
</td>
</tr>
<tr>
<td>
<a class="post_comment" href=".popupContainer">Post Comment</a>
</td>
</tr>
</table>
</div>
}
On click on "Post Comment" following js-script will be initialised....
<script type="text/javascript">
jQuery(document).ready(function() {
$(".post_comment").leanModal({top : 200, overlay : 0.6, closeButton: ".modal_close" });
$(function(){
jQuery('.tabs .tab-links a').on('click', function(e) {
var currentAttrValue = jQuery(this).attr('href');
jQuery('.tabs ' + currentAttrValue).show().siblings().hide();
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
});
});
</script>
....and a popup Container (div with class .popupContainer) is shown, where users can finally submit their comment.
<div class="popupContainer" style="display:none;">
Your Name: <input type="text" class="_user_name" />
Email:<input type="text" class="_comment_email" />
<input type='button' class='_submit_comment' value='Speichern' >
</div>
By submitting this comment, following script is initialised and data will be sent by ajax.
<script type="text/javascript">
$("._submit_comment").click(function(){
var parentObj = $(this).closest('.save_comment');
var _comment_id = parentObj.find('._comment_id').val(); -> I don't get the correct id
So here begins the problem. I only get the first id from the foreach-loop, but i need to get for every comment the corresponding id. Can anybody help with this problem?
Thank you
Misch
This part is wrong IMHO :
$(this).closest('.save_comment');
You should set a JS variable when you click on "Post Comment" with the id that you can store in the link like :
<a class="post_comment" href=".popupContainer" data-idcomment="<?php print($row['id'] );?>">Post Comment</a>
And
var _comment_id = null;
jQuery('.tabs .tab-links a').on('click', function(e) {
_comment_id = jQuery(this).data('idcomment');
var currentAttrValue = jQuery(this).attr('href');
jQuery('.tabs ' + currentAttrValue).show().siblings().hide();
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
});
});
Then you can use _comment_id for you ajax call
Related
I'm trying to make a search form, based on the date from input field, the variable is exist when I show it with first alert. But after the first alert line, it seems nothing happen and console log don't says anything
<script type="text/javascript">
$(document).ready(function(){
$('#find').click(function(){
var date = $('#date').val();
var month = $('#month').val();
var year = $('#year').val();
var search = year+'-'+month+'-'+date;
//alert(search); <--currently the alert stop by the comment tag , its work well if the comment tag remove
$.ajax({
url:'page/report/find.php',
method:'post',
data:{data:search},
success:function(data){
$('#find_date').html(data); <-- not send value to the div id aka blank result
alert(data); <--not showing alert aka nothing happen
console.log(data); <--not showing error
}
});
});
});
</script>
Below is the PHP file waiting the variable from AJAX to proccess
<?php
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);
ini_set('display_errors',1);
if(isset($_POST)){
//parse_str($_POST['data'],$_POST);
$message = $_POST['data'];
}
echo $message;
?>
And below is the form
<form name="edit" id="edit_frm" method="post">
<table class="edit-table">
<tr>
<td colspan="6" align="center">
<input type="text" id="date" size="1" value="" placeholder="date"> -
<input type="text" id="month" size="1" value="" placeholder="month"> -
<input type="text" id="year" size="2" value="" placeholder="year">
<input type="button" id="find" value="<< search >>" />
<div id="find_date"></div>
</td>
</tr>
</table>';
I have to one public_page.php page and one action.php page. If a user press submit button in public_page.php it sends information to action.php page by jquery post method. After successful processing the action.php page sends one tr data which should be replaced in table of public_page.php.
page: public_page.php
<div id="result"></div>
<table>
<thead><tr><th>S/N</th><th>Name</th><th>Address</th><th>Mobile</th><th>Action</th></tr></thead>
<tbody>
<tr id="1"><td>1</td><td>Mr.X</td><td>Japan</td><td>95684256</td><td><a class="edit" href="">Edit</a></td></tr>
<tr id="5"><td>1</td><td>Mr.Y</td><td>USA</td><td>123856641</td><td><a class="edit" href="">Edit</a></td></tr>
<tr id="8"><td>1</td><td>Mr.Z</td><td>UK</td><td>456862043</td><td><a class="edit" href="">Edit</a></td></tr>
</tbody>
</table>
jquery code (without $(document).ready line here):
$("body").on("click",".edit",function(event){
event.preventDefault();
var url = 'action.php';
var trid = $(this).closest('tr').attr('id');
$.post(url,
{
trid: trid,
},function(data){
$("#result").html(data).show();
});
});
after that the data of table row is come in '#result' div for editing. Let. tr id=5 (Mr.Y) is now for editing. So here it is comes in #result div as follows:
<div id="result">
<form id="5000">
Name:<input type="text" name="name" value="Mr.Y" /><br />
Address:<input type="text" name="adrs" value="USA" /><br />
Mobile:<input type="text" name="mobile" value="123856641" /><br />
Age:<input type="text" name="age" value="30" /><br />
<input type="submit" value="Submit" />
</form>
</div>
Now when user edit the information and press Submit, it sends the form information to action.php page by jquery. what is doing action.php page, after getting trid (which is actually id of database row that is to be edited) it process the data and produce callback data for public_page.php like this:
page: action.php
echo '<div class="success_msg">Data Updated Successfully!</div>';
echo '<div class="trid">5</div>';
echo '<div class="trcontent"><tr id="5"><td>1</td><td>Mr.Y</td><td>Tokeyo</td><td>123856641</td><td><a class="edit" href="">Edit</a></td></tr></div>';
and jquery code of public_page.php process the data like this:
var url = 'action.php';
var id = $(this).closest('form').attr('id');
var form_id = "#"+id ;
var data = $(form_id).serializeArray();
$.post(url,
data,function(callbackdata){
var msg = $(callbackdata).filter(".success_msg").html();
var trid = $(callbackdata).filter(".trid").html();
var trdata = $(callbackdata).filter(".trcontent").html();
$("#result").html(msg).show();
$('#'+trid).replaceWith(trdata);
});
as per query code, it should replace the tr which id is 5. But although it is replacing the tr but not in tabular format, it is replacing as text format like this:
page: public_page.php
<div id="result"></div>
<table>
<thead><tr><th>S/N</th><th>Name</th><th>Address</th><th>Mobile</th><th>Action</th></tr></thead>
<tbody>
<tr id="1"><td>1</td><td>Mr.X</td><td>Japan</td><td>95684256</td><td><a class="edit" href="">Edit</a></td></tr>
1Mr.YTokeyo123856641<a class="edit" href="">Edit</a>
<tr id="8"><td>1</td><td>Mr.Z</td><td>UK</td><td>456862043</td><td><a class="edit" href="">Edit</a></td></tr>
</tbody>
</table>
I think ...... is not inserting with replaced data.
How to resolve this issue, so that after replacing tr id="5" looks like a table row, not a string.
I'd suggest making an edit that will deal with this in a simpler way.
In your php code, instead of returning a div, what you should return is data.
<?php
$data = new stdClass();
$data->successMsg = 'Data Updated Successfully!';
$data->trid = 5;
$data->trContent = '<tr id="5"><td>1</td><td>Mr.Y</td><td>Tokeyo</td><td>123856641</td><td><a class="edit" href="">Edit</a></td></tr>';
echo json_encode($data);
Then in your JS code, you can go directly at the data instead of filtering it out of your HTML.
$.post(url,
data,
function(callbackdata){
var msg = callbackdata.successMsg;
var trid = callbackdata.trid;
var trdata = callbackdata.trContent;
$("#result").html(msg).show();
$('#'+trid).replaceWith(trdata);
},
'json');
The reason you're having problems is because of the way jQuery handles invalid HTML. <div><tr><td>1</td><td>2</td></tr></div> is not valid.
$('<div><tr><td>1</td><td>2</td></tr></div>').html() // outputs `12`
Note #1: var id = $("#mysqlid").val(); is supposed to be the value from the hidden field from the form where the delete button has been pushed.
The id is unknown, since it is the auto_increment id from the ever changing database. To make it unique.
<script type="text/javascript">
$(document).ready(function(){
$(document).on("click", "#delete", function(){
var id = $("#mysqlid").val(); // Note #1
$.ajax({
type:"post",
url:"http://www.mydomain.no/action.php",
data:"id="+id+"&action=delete",
success:function(data){
showList();
// showlist() returns an updated list of entries from the database after the selected row is deleted.
}
});
});
});
</script>
<table id="list">
<theader>
<tr>
<td>Name</td><td>Action</td>
</tr>
</theader>
<tbody>
<!-- Content from action.php start here -->
<tr>
<td>Test data</td>
<td>
<form>
<input type="hidden" id="mysqlid13" value="13">
<a href="#" id="delete">
<img style="cursor:pointer;" src="gfx/delete.png" alt="Delete">
</a>
</form>
</td>
</tr>
<tr>
<td>Test data 2</td>
<td>
<form>
<input type="hidden" id="mysqlid14" value="14">
<a href="#" id="delete">
<img style="cursor:pointer;" src="gfx/delete.png" alt="Delete">
</a>
</form>
</td>
</tr>
<!-- Content from action.php ends here -->
</tbody>
</table>
I've removed all the excess code, as to not clutter the issue at hand.
I'm sure this is an easy fix for someone more advanced in javascript than me.
As per my previous suggestion, you can assign a common class name to the elements that will need to be grabbed and passed back to the server. The class name wouldn't have to be unique just known. If you give all the elements you wish to perform this action on the same class name you can select those elements, get their values, and pass them back in your ajax call.
Given html:
<form>
<input type="hidden" id="mysqlid13" class='deleteMe' value="13">
<a href="#" id="delete">
<img style="cursor:pointer;" src="gfx/delete.png" alt="Delete">
</a>
</form>
Your js could become:
$(document).on("click", "#delete", function(){
var id = $(this).closest("form").find(".deleteMe").val();
/*make your ajax call or whatever*/
});
Now if you only have that one hidden input element per form element you could even simplify it and not even use an identifier and select by type:
$(document).on("click", "#delete", function(){
var id = $(this).closest("form").find("input[type='hidden']").val();
/*make your ajax call or whatever*/
});
I'd prefer to do this in a bit better approach, like this
Note it's invalid HTML to have duplicate ID in a document, please change it to class
<form>
<input type="hidden" name="id" value="14" />
<input type="hidden" name="action" value="delete" />
<a href="#" class="delete">
<img style="cursor:pointer;" src="gfx/delete.png" alt="Delete" />
</a>
</form>
$(document).on("click", ".delete", function (e) {
e.preventDefault(); // prevent default action
var that = this;
$.ajax({
type: "post",
url: "http://www.mydomain.no/action.php",
data: $(that).closest('form').serialize(),
success: function (data) {
showList();
// showlist() returns an updated list of entries from the database after the selected row is deleted.
}
});
});
set data format , it may not pass like query string and complete url may not work cause of CORS
$.ajax({
type:"post",
url:"/action.php",
data:{"id":id,"action":"delete"},
success:function(data){
showList();
}
First you need to change you links to use a class, not an id, as ids must be unique. So you html becomes
<a href="#" class="delete">...
Then your js becomes
$(document).on("click", ".delete", function(){
var id = $(this).prev("input").val();
...
}
I have a problem. jQuery Datepicker does not work in a dynamic form, so you can't pick a date. Here is my demo link http://gestionale.odoyabooks.com/sum.php.
JavaScript:
<script>
$(document).ready(function() {
$('.input_date').on('click', function() {
$(this).datepicker('destroy').datepicker({showOn:'focus'}).focus();
});
});
</script>
HTML:
<form action="" method="POST">
<div class="yes">
<div id="cost1" class="clonedCost" style="display: inline;">
<table border="0">
<tr>
<td><label class="date" for="date">Date</label></td>
</tr>
<tr>
<td><input class="input_date" id="date" type="text" name="date[]" /></td>
</tr>
</table>
</div>
<div id="addDelButtons_cost"><input type="button" id="btnAdd" value=""> <input type="button" id="btnDel" value=""></div>
</div>
</form>
The problem is that when you bind the event initially, the new field doesn't exist.
By applying the on click to the body, with the selector .input_date, it should attach the event to the new element in the dynamic form.
$(function() {
$('body').on('click','.input_date', function() {
$(this).datepicker('destroy').datepicker({showOn:'focus'}).focus();
});
});
Working Example
A better way:
You should initialize the datepicker for the field when you create the element.
$(function() {
$('.input_date').datepicker();
});
function createNewDatepickerInput() {
var $newInput = $('<input type="text" name="date123" class="input_date" />');
$newInput.appendTo("form").datepicker();
}
Working Example
I don't understand why you're destroying/re-initializing the datepicker.
You simply need to call .datepicker() after creating the element. For example:
function createInput() {
$('<input type="text" name="date" />').appendTo("form").datepicker();
}
Edit:
Here's a demo: http://jsfiddle.net/xEmJu/
I have working script that the user completes inputs on a form and when they submit the form and the content of the form inputs are entered as a table row.
Is there any way of, I think within the JS to make each row have a unique ID and add a delete button to the last colum of each row so the user can delete an individual row.
Thanks for saving a life!!!!
HTML Form
<form id="my_form" action="table_form.php" method="post">
<div style="width:10%; float:left;">
Quantity<br />
<input name="field_1" type="text" id="field_1" size="3" />
</div>
<div style="width:20%; float:left;">
Part Number<br />
<input type="text" id="field_2" name="field_2" />
</div>
<div style="width:30%; float:left;">
Notes<br />
<input name="field_3" type="text" id="field_3" size="45" />
</div>
<div style="width:20%; float:left;">
Unit Price<br />
<input type="text" id="field_4" name="field_4" />
</div>
<div style="width:20%; float:left;">
<br />
<input type="submit" value="Add Row" />
</div>
</form>
<!--
Here we create our HTML table.
Note the ID of the table. This will be used in our javascript file
Our table only contains a header row. All other content will be added dynamically
--><? $rowid = 1; ?>
<table width="100%" id="my_table">
<tbody id="my_table_body">
<tr>
<th width="5%"><div align="left">Qty</div></th>
<th width="19%"><div align="left">Part Number</div></th>
<th width="46%"><div align="left">Notes</div></th>
<th width="15%"><div align="left">Unit Price</div></th>
<th width="15%"><div align="left">Row Total</div></th>
</tr>
</tbody>
</table>
JS
window.addEvent('domready', function(){
$('my_form').addEvent('submit', function(e){
e.stop();
this.set('send', {
onComplete: function( response ){
var data = JSON.decode(response);
inject_row( $('my_table_body'), data );
}
});
var valid_form = true;
$$('#my_form input').each(function(item){
if( item.value == '' ) valid_form = false;
});
if( valid_form ) {
this.send();
} else {
alert('Fill in all fields');
}
});
var inject_row = function( table_body, data ){
var row_str = '<tr width="100%">';
data.each( function(item, index){
row_str += '<td>'+item+'</td>';
});
row_str += '<td><input type="submit" name="deleterow" id="deleterow" value="Delete" /></td></tr>';
var newRow = htmlToElements( row_str );
newRow.inject( table_body );
}
var htmlToElements = function(str){
return new Element('div', {html: '<table><tbody>' + str + '</tbody></table>'}).getElement('tr');
}
});
PHP
<?php
/**
* If nothing is being posted to this script redirect to
* our HTML page.
*/
if( ! $_POST ){
header('Location: newquote.php');
}
// create an empty array for our results
$results = array();
/**
* Stick the values from _POST into our results array
* while also stripping out any html tags
*
* This is where you would perform any required processing
* of the form data such as server side validation or updating
* a database.
*/
foreach( $_POST as $field ){
$results[] = strip_tags( $field );
}
// Echo our results as a JSON encoded string.
echo json_encode( $results );
?>
I agree with J-P, it sounds like you don't need an unique id here.
Since the question is tagged "jquery" I suggest using the live event binding, e.g.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$(".deleterow").live("click", function() {
$(this).parents("tr:first").remove();
});
});
function foo(id) {
$("#"+id).append('<tr><td>'+(new Date()).getSeconds()+'</td><td>x</td><button class="deleterow">delete</button></td></tr>');
}
</script>
</head>
<body>
<table id="t1">
<tr><td>a</td><td>A</td><td><button class="deleterow">delete</button></td></tr>
<tr><td>b</td><td>B</td><td><button class="deleterow">delete</button></td></tr>
<tr><td>c</td><td>C</td><td><button class="deleterow">delete</button></td></tr>
</table>
<button onclick="foo('t1')">add</button>
</body>
</html>
The function passed to $(document).ready() is invoked when ...well, as the name states, when the document (dom) is ready.
$(".deleterow").live("click", ... : Whenever a click event occurs on an element with the css class "deleterow" the function passed as second parameter is invoked. In this case
function() {
$(this).parents("tr:first").remove();
}
When the function is invoked the this-context is the element where the event occurred. parents("tr:first") returns the first/"nearest" tr element in the ancestor-axis of the current element. remove() is probably self-explaining...
edit: ok, now that the jquery tag is gone....
http://www.jaycarlson.net/blog/2009/04/06/live-events-in-mootools/ shows a live-event binding for mootools. Using that the "new" solution is quite similar to the jquery script
window.addEvent('domready', function() {
// add an onclick handler for all current and future button elements
// within the table id=t1
$('t1').addLiveEvent('click', 'button', function(e){
// a button in t1 has been clicked, this=button element
// get the "nearest" tr in the parent/ancestor-axis
// and remove it
$(this).getParent("tr").dispose();
});
});
This should be unique enough for this project:
var newDate = new Date;
var id = newDate.getTime();
Then it would just be a matter of adding it the row in your loop and linking it to your delete button.
I always use the php function uniqid(). It generates a unique id based on the time in microseconds. PHP Documentation.
You could loop through your results in PHP and add the result from uniqid() to each result before using json_encode().