jquery id selector echoed php? not working - php

//play.php
echo' <div id="new_char" style="text-align:center; position:relative; top: 100px;"><center>
You do not have a character! <br> Make one...<br><br>
<form method="post" >
Character Name: <input type="text" name="name" size="25"> <br>
Class: <select name="class">
';
$classinfo = "select * from classes";
$classinfo2 = mysql_query($classinfo) or die("could not select classes");
while($classinfo3 = mysql_fetch_array($classinfo2) )
{
echo"<option>$classinfo3[type]</option>";
}
echo'
</select><br />
<div id="new_char_error"> </div>
<br />
<input id="make_char" type="submit" value="submit">
</form>
<table border="0" cellspacing="30">
<tr><td valign="top">
</td>
<td valign="top" >
<b style="text-align:center;">Class Starting Modifiers</b>
';
$selectclass="select * from classes";
$selectclass2=mysql_query($selectclass) or die("couldnt get classes");
echo'
<table border="1" bordercolor="black" bgcolor="#fffffff">
<tr><td font color="cc0033"> Class </td> <td font color="cc0033"> Attack </td> <td font color="cc0033"> Defense </td> <td font color="cc0033"> Endurance </td> </tr> <br>
';
while($selectclass3=mysql_fetch_array($selectclass2)) {
echo " <tr><td> $selectclass3[type]</td> <td> $selectclass3[attack]</td> <td> $selectclass3[defense]</td> <td> $selectclass3[maxendurance]</td> </tr>";
}
echo'
</table>
</td></tr></table></center>
</div>
';
<script>
$("#make_char").click(function() {
$.ajax({
url:'character_scripts/new_char.php',
success: function(data) {
$('#new_char_error').html(data);
}
});
});
</script>
Is it possible to use a div that is echoed through php as a jquery selector? I have a form that is not being submitted when the submission is clicked. All the code on new_char.php looks good. Ive tested all the loops and possible variation of the codes structure during runtime, all I can think of is that jquery can not use a selector that is echoed in php. but Im not that familiar with jquery and did not find the answer when searching online.
ps:
The function is a separate file and that is not the entire files posted, (to conserve space)

If you could post what you found, you might help others who've come here looking for an answer to the same problem.
Im guessing it was something simple like a missing semi or a typo as jquery really shouldnt care how your tag got the selector
Thanks!

First check jQuery is loading properly or not.
After then following code will work not directly in php file
$("#make_char").click(function() {
$.ajax({
url='character_scripts/new_char.php',
success: function(data) {
$('#new_char_error').html(data);
}
});
});
you should write like below.
echo "<script type='text/javascript'>$('#make_char').click(function() {
$.ajax({
url='character_scripts/new_char.php',
success: function(data) {
$('#new_char_error').html(data);
}
});
});</script>";

Related

PHP - HTML best practices to handle (submit) generated rows

I have html table generated via ajax. And last column on this table contains button. My question is what is the best practice to submit these rows (only one at time. I need use this method to amend records).
Is it worth to wrap each row with
<form>
<input type="hidden" value="hidden value">
<input type="submit">
</form>
Or people using something difference? Reason why i'm asking for is because i'm worry about very long list example 1k rows or 10k rows (that means i will have 1k or 10k forms on a page).
You can just use a hyperlink (which you can style to look like a button using CSS if you want). e.g:
Edit
where the value you give as the "id" parameter is the primary key of the record in that row.
Then in edit.php look for the id value using $_GET["id"] and fetch the appropriate record from the DB.
As Progrock advises, a form element may only be used "where flow content is expected" (i.e. not as a direct child of table or tr).
HTML 5 introduces a form attribute as a workaround:
<form id="row_1">
<input type="hidden" name="id" value="pk1">
</form>
<form id="row_2">
<input type="hidden" name="id" value="pk2">
</form>
<table>
<tr>
<td> <input type="text" name="attribute1" form="row_1"> </td>
<td> <input type="submit" form="row_1"> </td>
</tr>
<!-- and so on for each row -->
</table>
It has been brought to my attention that in this case, there is no direct user input being submitted, but only generated contents.
Well, then the solution is even simpler:
<table>
<tr> <td>
<form id="row_1">
<input type="hidden" name="id" value="pk1">
<input type="hidden" name="attribute1" value="whatever">
<input type="submit">
</form>
</td> </tr>
<!-- and so on for each row -->
</table>
I thought I'd have a go without form elements, working with editable table cells. Within each row you provide a button. And when you click it, an ajax post is made of the cell values.
You could have a non js fall back where the save button is replaced for an edit button that takes you to another page with a single form.
Forgive my JS.
I have the session storage in there just to check the concept.
<?php
session_start();
var_dump($_SESSION);
$data = array(
23 => ['triangle', 'green', '2'],
47 => ['square', 'red', '3'],
17 => ['pentagon', 'pink', '4']
);
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Save state here
$_SESSION['submission'] = $_POST;
}
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(function() {
$('button').click(function() {
// Get all table cells in the buttons row
var $cells = $(this).closest('tr').find('td[contenteditable="true"]');
var jsonData = {};
$.each($cells, function() {
jsonData[get_table_cell_column_class($(this))] = $(this).text().trim();
});
jsonData['id'] = $(this).attr('id');
$.post('',jsonData, function() {
alert('Saved.');
});
});
function get_table_cell_column_class($td)
{
var $th = $td.closest('table').find('th').eq($td.index());
return $th.attr('class');
}
});
</script>
</head>
<body>
<table>
<thead>
<tr>
<th class="shape">Shape</th>
<th class="colour">Colour</th>
<th class="width">Width</th>
<th>Ops</th>
</tr>
</thead>
<tbody>
<?php foreach($data as $key => $row) { ?>
<tr>
<?php foreach($row as $field) { ?>
<td contenteditable=true>
<?php echo $field ?>
</td>
<?php } ?>
<td>
<button id="<?php echo $key ?>">Save</button>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</body>
</html>
You can use the following
<table id="YourTableId">
...
<tr data-id="yourrowId">
<td class="col1"> value1</td>
<td class="col2"> value2</td>
<td class="col3"> value3</td>
<td class="actions">
Submit
</td>
</tr>
....
</table>
your javascript code will be like
$(document).ready(function (){
$('#YourTableId a').off('click').on('click',function(e){
e.preventDefault();
var tr = $(this).closest('tr')
var data={ // here you can add as much as you want from variables
'id' : tr.data('id), // if you want to send id value
'col1': tr.find('.col1').text(),
'col2': tr.find('.col2').text(),
'col3': tr.find('.col3').text(),
};
$.ajax({
method: 'post',
url: 'your url goes here',
data: data,
success: function(result){
// handle the result here
}
});
});
});
Hope this will help you

Can't get dynamic table elements value using jquery

I want to get the values of a dynamic created table but I couldn't figure out what is wrong.
the table created in a php file or it creates in server side by calling it in jquery.
for making it clear : in my html page I run a jquery method to load this table.
then I need this table values to be able to edit them. but what I get instead of the element value is undefined. (when I alert the value)
this is the jquery code :
//<!-- ajax Post Request -->
$(function() {
$('#edit_test_show').hide();
$('#save_edit').hide();
var vop_id = localStorage.getItem('op_id');
$.post("Requests/OPS.php", //Required URL of the page on server
{ // Data Sending With Request To Server
read_OPS: true,
op_id: vop_id
},
function(response) { // Required Callback Function
if (response) {
$("#result_table").html(response);
}
});
//====================
$('#enable_edit').on('click', function() {
$('#edit_test_show').show();
$('#enable_edit').hide();
$('#save_edit').show();
});
$('#save_edit').on('click', function() {
$('#edit_test_show').hide();
$('#enable_edit').show();
$('#save_edit').hide();
var vop_id = localStorage.getItem('op_id');
var vop_title = $('#result_table').find('#op_title').val();
var vop_descrip = $('#result_table').find('#op_descrip').val();
alert(vop_title);
});
});
html part which the table loads in :
<form method='post' class="form-inline">
<div class="form-group">
<div id="result_table">
<!-- dynamic op load -->
</div>
</div>
</form>
<button type='button' id="enable_edit" class='btn btn-default'>edit</button>
<button type='button' id="save_edit" class='btn btn-default'>save</button>
and this is the php code which generate the table :
if($row=mysqli_fetch_assoc($read_op)) {
echo "
<table class='styled-table' cellspacing='0' width='360' border='1' >
<tr>
<td>
<label for='mail_num' style='margin-right:10px;color:#595959;float: right;'>شماره فرآیند : </label>
</td>
<td>
<input name='op_id' style='width:240px;height: 25px;margin:0 3px 0 3px;'
value='".$row['id']."'/>
</td>
</tr>
<tr>
<td>
<label for='op_title' style='margin-right:10px;color:#595959;float: right;'>عنوان فرآیند : </label>
</td>
<td>
<input name='op_title' style='width:240px;height: 25px;margin:0 3px 0 3px;'
value='".$row['op_title']."'/>
</td>
</tr>
<tr>
<td>
<label for='op_descrip' style='margin-right:10px;color:#595959;float: right;'>شرح فرآیند : </label>
</td>
<td>
<textarea name='op_descrip' class='textarea_2' rows='0' cols='0' >".$row['op_descrip']."</textarea>
</td>
</tr>
</table>
<div class='cleaner h20'></div>";
}
You are using ID Selector (“#id”) but not defined ID in HTMl thus you are not able to find element
Define the IDs as
<input id='op_id' value='".$row['id']."'/>
OR, Use Attribute Equals Selector [name=”value”]
Selects elements that have the specified attribute with a value exactly equal to a certain value.
var vop_title = $('#result_table').find('[name=op_title]').val();
var vop_descrip = $('#result_table').find('[name=op_descrip]').val();

Using Ajax with PHP and MySQL

I would like to fetch information from a database with AJAX with html buttons, without having to refresh the browser.
I can make it work via HTML with the code below, but I want to do it via Ajax.
I have the following code in the same file, example.html;
<form action="?" method="get">
<input id="Button1" type="hidden" name="q" value="%U/%Y"/>
<input id="Button1" style="width: auto" type="button" value="Weekly stats">
</form>
<form action="?" method="get">
<input id="Button2" type="hidden" name="q" value="%M/%Y"/>
<input id="Button2" style="width: auto" type="submit" value="Monthly Stats">
</form>
<br>
<?php
//execute a mysql query to retrieve all the users from users table
//if query fails stop further execution and show mysql error
if ($_GET['q'] == '') {
$q = '%M/%Y';
}
else {
$q = $_GET['q'] ;
}
$query=mysql_query("SELECT DATE_FORMAT((post_date), '".$q."') 'Date',
SUM(balance) 'Balance'
FROM posts
GROUP BY Date
LIMIT 0, 25") or die(mysql_error());
//if we get any results we show them in table data
if(mysql_num_rows($query)>0):
?>
<table id="lastTips" class="main" cellspacing="0" width= "100%">
<thead>
<tr>
<th align="center">Date</th>
<th align="center">Balance</th>
</tr>
</thead>
<tbody>
<?php
//while we going through each row we display info
while($row=mysql_fetch_object($query)):?>
<tr>
<td align="center"><?php echo $row->Date;?></td>
<td align="center"><?php echo $row->Balance;?></td>
</tr>
<?php endwhile;?>
</tbody>
</table>
<?php
//if we can't get results we show information
else: ?>
<h3>No Results found.</h3>
<?php endif; ?>
I have tried several jquery functions without success, I have seen examples which call a separate file, but in my case I need to have the above code in the same file.
Can someone help me?
Thanks
I think you should split the code on two files.
First "index.html" ( with html/js ):
<
script type="text/javascript">
$('#btn-week').click(function(){
$.post("result.php", { date: "%U/%Y" }).done(function(data)
{
formatResponse(data);
}
);
});
$('#btn-month').click(function(){
$.post("result.php", { date: "%M/%Y" }).done(function(data)
{
formatResponse(data);
}
);
});
function formatResponse( values ){
var result = jQuery.parseJSON(data);//parse json response
var element = $("#lastTips tbody");
element.html('');//to clean previous result
for ( var i in result ){
element.append('<tr><td align="center">' + values.date + '</td><td align="center">' + values.balance + '</td></tr>');//append to table
}
}
</script>
<input id="btn-week" style="width: auto" type="button" value="Weekly stats">
<input id="btn-month" style="width: auto" type="submit" value="Monthly Stats">
<table id="lastTips" class="main" cellspacing="0" width= "100%">
<thead>
<tr>
<th align="center">Date</th>
<th align="center">Balance</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Second "result.php" with php:
<?php
//execute a mysql query to retrieve all the users from users table
//if query fails stop further execution and show mysql error
if ($_POST['q'] == '') {
$q = '%M/%Y';
}
else {
$q = $_POST['q'] ;
}
$query=mysql_query("SELECT DATE_FORMAT((post_date), '".$q."') 'Date',
SUM(balance) 'Balance'
FROM posts
GROUP BY Date
LIMIT 0, 25") or die(mysql_error());
echo json_encode(mysql_fetch_array($query));
I doesn't have tested the code.
One warning, the html file cannot have two elements with same id ;)
You should use AjaxForm plug-in for jQuery:
$('.my-ajax-form').ajaxForm(function(data){
alert(data);
// do some thing with data here.
})

can't see the html code that respone from server using ajax and php

1.Jquery Script with Ajax
$('#location').change(function(){
var l = $('#location :selected').val();
$.ajax({
type:'POST',
url : 'function/get_location.php',
dataType:'html',
data : { loc : l},
success: function(data){
$('#advertise_record').html(data);
}
});
});
i want to see the html code the response from server displayed in a blog div called #advertise_record in my web page . but when right clicked view source code i didn't see that html code inside that blog but the result of it show here.
2.html code
<div id="advertise_record"></div>
i need the result that response from server display here.
it's show the result but when i right click view source code i didn't see that code.
3. get_location.php
<?php
include_once (dirname(__FILE__). '/dbconfig.php');
define('ADVERTISE_DIRECTORY','../advertise/');
if(isset($_POST['loc'])) $loc = mysql_real_escape_string($_POST['loc']);
switch($loc){
case 0 : $sql = 'SELECT * FROM tblads';break;
case 1 : $sql = 'SELECT * FROM tblads WHERE loc_id="'.$loc.'"'; break;
case 2 : $sql = 'SELECT * FROM tblads WHERE loc_id="'.$loc.'"'; break;
case 3 : $sql = 'SELECT * FROM tblads WHERE loc_id="'.$loc.'"'; break;
default:"";
}
?>
<table border="1" cellpadding="5" cellspacing="5" width="850px;">
<tbody>
<tr>
<td><input type="file" name="filename" id="filename" class="text"/></td>
<td><label class="title">Name :</label><input type="text" name="ads_name" id="ads_name" class="text" style="width:150px;"></td>
<td><label class="title">URL :</label><input type="text" name="url" id="url" class="text" style="width:150px;"/></td>
<td><input type="button" name="update" id="update" class="button button_update"/></td>
</tr>
<?php
$output = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($output)){
?>
<tr>
<td colspan="3" align="center">
<div style="width: 700px;height: auto;overflow-x: scroll;">
<img src='<?php echo ADVERTISE_DIRECTORY.$row['image_name']?>' alt='<?php echo $row['ads_name'];?>' />
</div>
</td>
<td align="center"><a href='#tab-advertise?edit=<?php echo $row['ads_id']?>' >Edit</a></td>
</tr>
<?php
}
?>
</tbody>
</table>
so what's wrong with my code . really thank for you time to answer.
You're not going to see anything in the source that wasn't there initially. If you want to see the html that is returned by your ajax calls check the network/net tab in your browsers development tools. Also you're setting the content type for an image which is incorrect since your output is an html table.

Using jQuery, I am submitting a form wihout refreshing the browser and I need help in listing the submitted data in a custom table column

I have a table where it's rows are generated by a foreach loop.
Each table row has two columns, one with a form and the other with the forms submitted data, which I have called notes. (and updates using a jQuery library without refreshing the browser).
<script>
$(".notes_column").each(function(){
var $myform = $(this).find('.notes_form');
var $mynotes = $(this).find('.notes');
$myform.validate({
submitHandler: function(form) {
$.post('process.php', $myform.serialize(), function(data) {
$mynotes.html(data);
});
}
});
}); // each function
</script>
<table id="myTable" class="tablesorter" border="1" cellpadding="5">
<thead>
<tr>
<th>Notes</th>
<th>Submit Note</th>
</tr>
</thead>
<tbody>
<?php
foreach($myarray as $myvar){
echo '
<tr>
<td>ID LIKE TO PLACE THE content of the div class="notes" HERE, HOW CAN I DO IT?</td>
<td class="notes_column">
<form class="notes_form" action="" method="post">
<input class="q" type="text" name="notes" size="30" placeholder="Place your notes here..." />
<input class="searchsubmit" type="submit" name="submit" value="Submit" />
</form>
<div class="notes"></div>
</td>
</tr>
';
}
?>
</tbody>
</table>
Right now I use a jQuery each function which iterates through each table column, and for each column with the class name ".notes_column" populates a div with the class "notes" with the submitted data.
The question is listed inside the code with capitalized letters, how can I populate the other column with the forms submitted data?
Any ideas?
Ty
I would create a <div> in the first <td> such as
<td>
<div class="put_notes_here">ID LIKE TO PLACE THE content of the div class="notes" HERE, HOW CAN I DO IT?</div>
</td>
Then populate it the same as you did before
$mynotes.closest("tr").find(".put_notes_here").html(data);
Change the selector for your each to $('#myTable tr'), then you can iterate through each in your table.
Then you could either do an each on the tr object to access each td, or make use of jQuery's :first-child and nth-child(2) etc in a subsequent selector

Categories