update list with jquery & ajax [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i make a list with php & jquery which shows every row in my database.
i want to add this list an update button. when user clicks on a row, the row will expand and the button will become visible. and the text on that row will go in a textbox.
and my question is, how can i update the text when user click on the button in that row? first i thought, i could put a form in every row.. but i think that's a terrible solution.
can you suggest me an example or source for what i want to do?

Questions asking for code must show the code you've tried. Since you didn't give any code, I'll give a high-level answer:
Attach an event handler to the button (or probably actually to the table and use delegation).
In the the event handler, use jQuery traversal functions to find the row to which the button belongs.
Once you have a reference to the row, use jQuery traversal functions to find the inputs in the row.
Get the values and use ajax to update the database.

This is essentially what you need to do
jsFiddle (all working except AJAX)
Review the above jsFiddle and you can see how the first part of your question will work.
The values will be updated in the database via AJAX, and the code block is present in the jsFiddle example, but jsFiddle cannot demonstrate AJAX so you can't see it in action there.
However, if you copy/paste the following into two files (three if you break out the javascript into its own file), and edit it to match your own database, then you can see it in action.
Two files are required:
One: index.php (or whatever you wish to call it)
Two: my_php_processor_file.php (if change this name, must also change in the AJAX code block in the javascript
HTML:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<style>
</style>
<script type="text/javascript">
//Global var goes here:
editRow = 0;
$(document).ready(function() {
$('#msgbox').dialog({
autoOpen:false,
width:400,
modal:true,
buttons: {
Submit: function() {
var mfn = $('#mfn').val();
var mln = $('#mln').val();
var mem = $('#mem').val();
$('table').find('tr').eq(editRow).find('.fname').val(mfn);
$('table').find('tr').eq(editRow).find('.lname').val(mln);
$('table').find('tr').eq(editRow).find('.email').val(mem);
/*
//Now do the ajax transfer to the server
$.ajax({
type: 'POST',
url: 'my_php_processor_file.php',
data: 'user_id=' +editRow+ '&first_name=' +mfn+ '&last_name=' +mln+ '&email_addy=' +mem,
success:function(recd){
$('#alert').html(recd);
$('#alert').dialog('open');
}
}); //END ajax code block
*/ //Now, close the dialog -- doesn't happen automatically!
$(this).dialog('close');
}, //END Submit button
Cancel: function() {
$(this).dialog('close');
} //END Cancel button
} //END all buttons
}); //END msgbox div (dialog)
$('.editbutt').click(function() {
editRow = $(this).parents('tr').index();
//alert(editRow);
var fn = $(this).parents('tr').find('td').eq(0).find('.fname').val();
var ln = $(this).parents('tr').find('td').eq(1).find('.lname').val();
var em = $(this).parents('tr').find('td').eq(2).find('.email').val();
$('#mfn').val(fn);
$('#mln').val(ln);
$('#mem').val(em);
$('#msgbox').dialog('open');
}); //END editbutt
$('#alert').dialog({
autoOpen:false,
modal:true
});
}); //END document.ready
</script>
</head>
<body>
<table id="tbl">
<tr>
<td>
First Name
</td>
<td>
Last Name
</td>
<td>
Email
</td>
</tr>
<tr>
<td>
<input type="text" class="fname" id="fn1">
</td>
<td>
<input type="text" class="lname" id="ln1">
</td>
<td>
<input type="text" class="email" id="em1">
</td>
<td>
<input class="editbutt" type="button" value="Edit Row">
</td>
</tr>
<tr id="tr2">
<td id="td2a">
<input type="text" class="fname" id="fn2">
</td>
<td id="td2b">
<input type="text" class="lname" id="ln2">
</td>
<td id="td2c">
<input type="text" class="email" id="em2">
</td>
<td id="td2d">
<input class="editbutt" type="button" value="Edit Row">
</td>
</tr>
</table>
<div id="msgbox">
<h2>Edit User</h2>
First Name: <input id="mfn" type="text"><br/>
Last Name : <input id="mln" type="text"><br/>
Email Addy: <input id="mem" type="text"><br/>
</div>
<div id="alert"></div>
</body>
</html>
PHP Processor File: my_php_processor_file.php
<?php
$fn = $_POST['first_name'];
$ln = $_POST['last_name'];
$em = $_POST['email_addy'];
$uid = $_POST['user_id'];
/*
//This is where you use the security features of PHP to strip_slashes, and
//protect html_entities, etc. to guard your database against SQL injection
//attacks, etc. SEE THESE POSTS:
http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php
http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php
http://blogs.msdn.com/b/brian_swan/archive/2010/03/04/what_2700_s-the-right-way-to-avoid-sql-injection-in-php-scripts_3f00_.aspx
*/
//Now, update the database:
$success = mysql_query("UPDATE `users` SET `email`='$em', `first`='$fn', `last`='$ln' WHERE `user_id` = '$uid'");
//Now, return a message or something
if (mysql_affected_rows() == -1) {
$output = '<h2>Sorry, database update failed</h2>';
}else{
$output = '<h2>Update successful</h2>';
}
echo $output;

Related

Detect button click of a dynamic table contains dynamic buttons with jQuery

I have the following table dynamically generated using php and MySQL. The number of rows and number of buttons generated are dynamic.
<?php
if($resultCheck != 0){
while($result = mysqli_fetch_array($tableQueryExecute)){
$normalShiftDuration = $result['shift1Duration'];
?>
<tr> <form method="post" id="vtagViewTwo">
<td name=""><select class="form-control" name="normalShiftOa" id="normalShiftOa"><option>1</option></select></td>
<td>
<input type="submit" class="btn btn-primary" name="editButton" id="editButton" value="Save">
</td>
</form></tr>
<?php
}
}
?>
I want to get value of the <td> which is normalShiftOa value with the button click using jQuery click event as below.
$("#editButton").click(function(){
alert("Clicked");
});
But since there are many button generating for each row with the same id, I am not able to do it. Does anyone know how to do it? I am able to do it using php $_POST['editButton'] method. But I want to do it using jQuery.
Edit 1
I changed the id editButton to class and tried the following. But it is not working
$(".editButton").click(function(){
alert($(this).$("#normalShiftOa").val());
});
Instead of using ids, use class editButton. Then, if you want to get the value of the select, use jQuery like shown below:
$(".editButton").click(function(){
let tdValue = $(this).closest("form").find("select").val();
});
Edit: Code snippet that works.
$(".editButton").click(function(event){
let tdValue = $(this).closest("form").find("select").val();
alert(tdValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr> <form method="post" id="vtagViewTwo">
<td name=""><select class="form-control" name="normalShiftOa" id="normalShiftOa"><option>1</option></select></td>
<td>
<input type="submit" class="editButton btn btn-primary" name="editButton" id="editButton" value="Save">
</td>
</form></tr>

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

Sending quiz answers using a php form

I have forms which work fine. I have a quiz which works fine.
When I incorporate the two they don't work fine :(
The quiz works as a quiz but it wont send it out using php to my email address.
Here is a bit of my code:
<head>
<script>
CorrectAnswers = new Array();
CorrectAnswers[0]=1;
CorrectAnswers[1]=1;
CorrectAnswers[2]=1;
CorrectAnswers[3]=2;
macrightchar='YES';
macwrongchar='NO';
winrightchar='YES';
winwrongchar='NO';
var platform = 'win'
if (navigator.appVersion.indexOf('Mac') != -1) {platform = 'mac'}
if (platform == 'mac') {
rightchar = unescape(macrightchar)
wrongchar = unescape(macwrongchar)
}
else {
rightchar = unescape(winrightchar)
wrongchar = unescape(winwrongchar)
}
function CheckAnswer(){
var i = 0;
var TotalCorrect = 0;
var x = 0;
var Score = 0;
for (i=0; i<CorrectAnswers.length; i++){
if (document.QuizForm.elements[i*2].selectedIndex == CorrectAnswers[i]){
document.QuizForm.elements[(i*2)+1].value = rightchar;
TotalCorrect++;
}
else{
document.QuizForm.elements[(i*2)+1].value = wrongchar;
}
}
Score = Math.floor((TotalCorrect*100)/CorrectAnswers.length);
document.CheckForm.ScoreBox.value = Score + '%';
}
</script>
</head>
<body>
<form name="QuizForm" accept-charset="utf-8" method="post" action="forms/quiz/_process.php" onSubmit="return validate.check(this)">
<table class="widthOneHundredPercent">
<tr>
<td class="tableCellFloat columnOne" valign="top">
<label for="Big_Media_offers_a_great_multiplatform_tool">Big Media offers a great multiplatform tool</label>
</td>
<td class="tableCellFloat columnTwo" valign="top">
<select name="0">
<option>???</option>
<option>True</option>
<option>False</option>
</select>
<td valign=top>
<input type="text" name="1" size=2 maxlength=2>
</td>
</td>
</tr>
<tr>
<FORM name="CheckForm">
<td align="center">
<font face="Geneva,Arial"><input type="button" VALUE="Check" onClick="CheckAnswer()"> Your score is <input type=text name="ScoreBox" size="4" maxlength="4"></font>
<center><input type="submit" value="Submit Form" /></center>
</form>
When submit is pressed it will change the end of my file name in the address bar from quiz.php to quiz.php?ScoreBox=75%25. So it takes my correct answers and wrong answers.
I need the quiz to show a live right and wrong answers when check scores is clicked but I also need to send the results using PHP.
If I'm going at it completely wrong perhaps someone can point me in the right direction to start fresh.
Regards.
Few things I notice here:
QuizForm doesn't have a submit button and does not appear to be submitted dynamically (may just not be shown). Perhaps this form and CheckForm can be combined.
CheckForm doesn't have a method defined, which is why the submit puts a query string on it
The score is being submitted instead of the raw answers. Perhaps this is desired behavior, but it leaves the ability for someone to just submit they got a great score.
The answer could be as simple as moving the submit button from CheckForm to QuizForm.
Try adding a closing <form> tag for 'QuizForm' before you open 'CheckForm'.
[edit]Actually, QuizForm doesn't seem to have a submission method.

Wordpress jQuery to PHP data transfer

everyone. I'm a relatively new developer with limited experience in jQuery AJAX and PHP. I'm working on a Wordpress plugin that is very much a learning exercise for me as well.
Basic description: On my plugin's admin page, I have a bunch of forms that will be displayed as modal windows (using jQuery UI) and when filled out, will submit their fields to a separate PHP file for processing. That file will accept the data and prepare it for insertion into the wpdb table I have set up.
Plugin Admin page (PHP):
<div id="form1" title="My Awesome Form">
<form id="frmNewCom">
<fieldset>
<table>
<tr>
<td><label for="name">Community Name</label>
<td><input type="text" name="newComName" id="newComName" />
</tr>
<tr>
<td><label for="lefthead">Left Column Header</label></td>
<td><input type="text" name="newComLefthead" id="newComLefthead" /></td>
</tr>
<tr>
<td><label for="righthead">Right Column Header</label></td>
<td><input type="text" name="newComRighthead" id="newComRighthead" /></td>
</tr>
</table>
</fieldset>
</form>
</div>
jQuery UI code for form ($pcal is my no-conflict thing):
$pcal('#form1').dialog({
autoOpen: false,
height: 275,
width: 400,
modal: true,
buttons: {
"Add Living Option": function() {
// Functionality for submit
},
Cancel: function() {
$pcal(this).dialog("close");
}
},
close: function() {
// close function
}
});
Now here's the problem. I'm not really sure what to do from this point. I've read a bunch of stuff about using .post() and .serialize(), and I've gotten myself very confused at this point.
Do you guys have some insight into the proper javascript/jQuery to PHP handling you could lend? I've asked this on the Wordpress forum as well, but I've always found good advice here, so thought I'd ask. Any and all help is appreciated.
A very simple example would be :
$pcal.post("test.php", $pcal("#frmNewCom").serialize(), function() {
// this will run once returned from PHP
alert('thanks');
$pcal(this).dialog("close");
});
This posts the form (id = frmNewCom) in a serialized format (newComName=1&newComLefthead=2&newComName=3 where 1,2 and 3 are the values entered in your form) using .post() and .serialize()
then in test.php you would access your values like this :
$newComName = $_POST['newComName'];
$newComLefthead = $_POST['newComLefthead'];
$newComName = $_POST['newComName'];
// insert into table
The above is a) untested and b) does not contain any prevention against SQL injection should you want to store this in a DB

Put specific tds from a table row into edit using jQuery (then update w/ ajax)

I'm somewhat new to jQuery, so I could use some help here.
This is my issue:
I have a PHP script outputting a dynamic table. Each row has an "edit" button, plus some other fields. Only 3 of those need to be turned into an input box. The edit button should only put that specific row into "edit mode." I got as far as assigning each row a unique class by adding a number to the end of it.
I have been able to use jQuery to change all of the rows into edit mode, but I need it to be specific to a row.
An example row would have classes like name0, price0, and desc0. The next row would go on to classes name1, price1, and desc1 (for the fields that need changed). How can I reference these values and pass them to jQuery so it processes an event on just those elements?
There are two ways of doing this:
Dynamically creating the elements when the button is pressed; or
Hiding and showing elements that already exist.
Too much DOM manipulation can be really slow (particularly on certain browsers) so I favour (2). So for example:
<table class="editable">
<tbody>
<tr>
<td>one</td>
<td>
<div class="view">two</div>
<div class="edit"><input type="text"></div>
</td>
<td>
<div class="view">three</div>
<div class="edit"><input type="text"></div>
</td>
<td>
<input type="button" class="edit" value="Edit">
<input type="button" class="send" value="Send" disabled>
<input type="button" class="cancel" value="Cancel" disabled>
</td>
</tr>
</tbody>
</table>
with:
table.editable div.edit { display: none; }
and
$(function() {
$(":button.edit").click(function() {
var row = $(this).closest("tr");
row.find("input.view").attr("disabled", true");
row.find("div.view").each(function() {
// seed input's value
$(this).next("div.edit").children("input").val($(this).text());
}).fadeOut(function() { // fade out view
row.find("div.edit").fadeIn(function() { // fade in edit
row.find("input.edit").removeAttr("disabled"); // enable edit controls
});
});
});
$(":button.cancel").click(function() {
var row = $(this).closest("tr");
row.find("input.edit").attr("disabled", true");
row.find("div.edit").fadeOut(function() {
row.find("div.view").fadeIn(function() {
row.find("input.view").removeAttr("disabled");
});
});
});
$(":button.save").click(function() {
// ...
});
});

Categories