complex jqueryui dialog - php

Okay, that's a presumptuous title - it's complex to me.
Overview: (See screenshots and UPDATE at bottom.)
a. On $(document).ready, jQuery/AJAX builds table with one contact per row
b. Each table row, 3rd cell, is: <a id="edit_83">edit</a> tag -- "83" is example and represents the contact_id from db, so each a tag will have a unique id number that is used in step (d)
c. As table being built, construct jqueryui dialog (autoOpen=false) for each contact in AJAX callback
d. when any edit anchor is clicked, jquery splits off the contact_id and uses that to display the appropriate jQueryUI dialog.
Objective: Clicking on edit link in any table row opens a jqueryui dialog with edit form for that contact.
Problem: The form opens, but there are no form fields inside. In fact, in the DOM the injected form/div is missing for each table row. ???
HTML:
<div id="contact_table"></div>
Javascript/jQuery - AJAX call:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "ax_all_ajax_fns.php",
data: 'request=index_list_contacts_for_client&user_id=' + user_id,
success: function(data) {
$('#contact_table').html(data);
var tbl = $('#injected_table_of_contacts');
tbl.find("div").each(function() {
$(this).dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons:
{
Okay: function() {
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
})
});
}
});
});
AJAX/PHP 1 - ax_all_ajax_fns.php:
}else if ($_POST['request'] == 'index_list_contacts_for_client') {
$user_id = $_POST['user_id'];
$r = build_contact_table_for_client($user_id);
echo $r;
}
AJAX/PHP 2: - functions.php
function build_contact_table_for_client($user_id) {
$aContact_info = get_contact_data_ARRAY_user_id($user_id, 'first_name','last_name','email1','cell_phone', 'contact_id');
$r = '<table id="injected_table_of_contacts">
<tr>
<th width="120">Name</th>
<th width="200">Email Address</th>
<th width="100">Cell Phone</th>
<th>Action</th>
</tr>
';
while ($rrow = mysql_fetch_array($aContact_info)) {
$r .= '
<tr>
<td>'.$rrow['first_name'].' '.$rrow['last_name'].'</td>
<td>'.$rrow['email1'].'</td>
<td>'.$rrow['cell_phone'].'</td>
<td>
<a class="editcontact" id="edit_'.$rrow['contact_id'].'" href="#">edit</a>
/
<a class="delcontact" id="del_'.$rrow['contact_id'].'" href="#">del</a>
<div id="editThisContact_'.$rrow['contact_id'].'" style="display:none">
<form name="editForm" onsubmit="return false;">
<p class="instructions">Edit contact information:</p>
First Name:<span style="padding:0 20px;">Last Name:</span><br />
<input type="hidden" id="fn_'.$rrow['contact_id'].'" value="'.$rrow['first_name'].'">
<input type="hidden" id="ln_'.$rrow['contact_id'].'" value="'.$rrow['last_name'].'">
Email:<span style="padding:0 20px;">Cell Phone:</span><br />
<input type="hidden" id="em_'.$rrow['contact_id'].'" value="'.$rrow['email1'].'">
<input type="hidden" id="cp_'.$rrow['contact_id'].'" value="'.$rrow['cell_phone'].'">
</form>
</div>
</td>
</tr>
';
}
$r .= '</table>';
return $r;
}
jQuery - document.click event - if injected code missing, how is it able to find the selector??
$(document).on('click', '.editcontact', function(event) {
var contact_id = this.id.split( 'edit_' )[1];
var etc = $( '#editThisContact_' + contact_id );
etc.dialog("open");
});
UPDATE - PARTIAL SOLUTION:
The dialog is now appearing - the cancel button was out of place, per this post. However, the injected code has vanished. Nothing else changed - just got the dialog code working by fixing syntax error in placement of cancel button.

In response to the question on my comment on the original post:
You really already know JSON, it stands for JavaScript Object Notation. This is a JSON object:
{"a":1,"b":2,"c":3}
look familiar? JSON is just a fancy name for something we've been using a long time (that may not be 100% true, but it's how I see it.)
The idea is to have the server pass back JSON objects and have your JavaScript create/update HTML based on them. In your scenario, you were having your PHP build multiple HTML dialogs. Instead, you would have your PHP pass back an array of objects each one representing a single row from your table, like so:
{
"records":
[
{
"field a":"value a",
"field b":"value b"
},
// record 2
{
"field a":"value a",
"field b":"value b"
}
]
}
If you were to request that from the server using .getJSON(), jQuery would automatically read that and give you a an object with a .records property that is an array of objects! Now you can use JavaScript to update a single dialog/form on the screen when they click one of the corresponding records.
Note: You could have PHP just pass back an array of objects, but it is best practice to wrap it in an object above. Many times you'll want other info too, for example, when you are doing paginated search results you're going to need to know the total number of records and what page you're on and maybe other data points.
An added benefit of this is that the server is done much faster. You push all of the display logic onto the client's computer, and hence, can server more pages from the same server.
That's a real brief explanation. There are tutorials and examples ALL OVER the web. Any good Ajax app you use online (GMail for example) uses JSON objects instead of passing huge blocks of HTML around. Here are a few links, Google has quite a few more:
http://php.net/manual/en/function.json-encode.php (turn any variable into a JSON string.)
http://www.json.org/example.html
http://www.w3schools.com/json/default.asp
http://www.jsonexample.com/
PHP Example: http://www.electrictoolbox.com/json-data-jquery-php-mysql/
Another PHP Example: http://www.jquery4u.com/json/ajaxjquery-getjson-simple/ (the alternative method for json-data.php in this link is the way to go, the other way is just silly!)
There are also some really good frameworks out there to help out with this process. I'm a huge fan of both backbone.js and spine.js. Both use jQuery, both help you use best practices when building apps (like MVC.)

It's nice when you solve your own question. Not so nice when the answer is a ID-ten-T error.
In the injected HTML, note the type of the input fields (screenshot 1). Change type to type="text", and all works as desired.
When concepts are new, Occam's Razor moves almost beyond reach.
I still don't understand why I can't see the injected markup, though..!

Related

access pair value in array in php which send using ajax

I'm new in php ajax and get two problem. The first problem, I want to save pairs of values (consist of value in text and it attribute) in an array every I click button. Is my method to push in array true? and the second, how I can access the array in php and insert to database? below is my HTML code
<script>
var a=0;
var b=1;
var tanya= new Array();
var object = {};
var pilgan= new Array();
function question(){
var x = $('#jenis').val();
a++;
if (x=="Multiple Choice") {
$("select").css("display","none");
alert("Pilihan :"+a);
$('ol').append('<li><input type="text" name="tanya" id="thequestion" uruts="'+a+'" class="thequestion" style="color: black; width: 50%;"><button style="margin-left:10px;" id="tambah" class="tambah">Choice</button><div id="thechoice" class="thechoice"><input type="radio" id="pilihan"><input type="text" name="text" urutp="'+a+'" class="text" id="text"><br/></div></li>');
}else if(x=="Essay"){
$("select").css("display","none");
$("#jenis").css("display:none;");
$('ol').append('<li><textarea name="text" uruts="'+a+'" id="thequestion" style="color: black; width: 50%;"></textarea>');
}
}
function uploadQuestion(){
$.ajax({
url : "questionDosenAjax.php",
type : "POST",
async : false,
data : {
upload : 1,
question : tanya,
choice : pilgan
},
success : function(res){
$('#coba').html(res);
}
});
}
$(document).ready(function(){
$("#backMakeAss").click(function(){
changePage("pilihanAssignAjax.php");
});
$('ol').on('click','button',function(){
alert("Pilihan :"+a);
//$pilgan.push(pilihan:$('#thechoice').val(), id:$('#thechoice').attr('urutp'))
$(this).siblings('#thechoice').append('<input type="radio" id="pilihan"><input type="text" name="text" class="text" id="text" urutp="'+a+'"><br/>');
});
$("#kumpul").click(function(){
object[$('#thequestion').attr('uruts')] = $('#thequestion').val();
tanya.push(object);
//$pilgan.push(pilihan:$('#thechoice').val(), id:$('#thechoice').attr('urutp'))
uploadQuestion();
});
$('#add').click(function(){
var id = $('#thequestion').attr('uruts');
var value = $('#thequestion').val();
object["id :"+id] ="value :"+value;
tanya.push(object);
//$.each(tanya, function (index, value) {
//alert({"id: "+value.id +" and value: "+ value.value});
//});
//$pilgan.push(pilihan:$('#thechoice').val(), id:$('#thechoice').attr('urutp'))
});
});
</script>
This is my php code, I don't know why it doesn't work.
<?php
$con = mysqli_connect("localhost", "root", "", "lantern");
if(isset($_POST['upload'])) {
$pertanyaan = count($_POST['question']);
$pilihan = $_POST['choice'];
for($i=0;$i<sizeof($pertanyaan);$i++){
echo $_POST['question'][$i+1]."\n";
}
}
?>
Thank you and sorry if my english not good.
There are several issues with your code.
Firstly, you're generating multiple elements with the same ID (#thequestion). IDs are supposed to be unique. When you try to access the elements through jQuery later on it is not clear which element it is that you want. You could reference the elements by their (unique) uruts attribute like so:
$('.thequestion[uruts="' + number + '"])
, but it would probably be a better idea to give each thequestion element a unique ID like
<input type="text" name="tanya" id="thequestion_' + a + '" uruts="' + a +'" class="thequestion" style="color: black; width: 50%;">
and then reference them as
$('#thequestion_' + number)
But since you never seem to be calling the question() function, it's not really clear to me where those elements are coming from in the first place. (It could be helpful if you also posted your HTML.)
Next, what you probably want in the event listener for #add instead of
object["id :"+id] ="value :"+value;
is just
object[id] = value;
or maybe (but I doubt it, because it's neither the way you do it in the #kumpul event listener (where you do it differently from here) nor does it seem to be what your php expects):
object[id] = {
'id': id,
'value': value
};
However, since you extend the object object every time the event is fired and then push the extended object into the tanya array, you push a new copy of the entire object in there every time, when what you really want is more likely just the new value. So
tanya[id] = value;
should be sufficient. Also it's not really clear to me why you do the pushing again in the event listener for #kumpul. Actually, it seems like you could just get rid of the object object altogether.
Then in your PHP, you could drop the $pertanyaan variable and rewrite
for($i=0;$i<sizeof($pertanyaan);$i++){
echo $_POST['question'][$i+1]."\n";
}
as
foreach($_POST['question'] as $question){
echo $question ."\n";
}
Your method is not necessarily wrong, it's just that there's an easier way to achieve the same thing. (Edit: actually it is wrong, I didn't look properly before. With $pertanyaan = count($_POST['question']); you already have an integer in $pertanyaan. You do not need to use sizeof on that. count and sizeof are aliases, they do exactly the same thing.)
(Also, google "PHP SQL injection" sometime. You really do not want to send user input to the database as-is, but I'll leave it at that for the moment. You mention a database so I'm assuming that's what you want to do with the $_POST data eventually.)
Then, in these two lines:
$("select").css("display","none");
$("#jenis").css("display:none;");
, the first line is the correct way to do this with jQuery, while the second one is incorrect and won't work.
Finally, is there any reason why your AJAX call needs to be synchronous (async: false in the settings)? This is generally discouraged these days (see https://stackoverflow.com/a/6685294/1901379).

Ajax output to second div using PHP

I am a new user of ajax; so...
I am using ajax on a simple html page to access a php script to receive data, calculate results using data in an mysql table, and echo results in a div on the same page. My javascript statement to do this is:
$.post('ajax/phpscript.php', {
postuser:theuser,
postname:uans1
}, function(data) {
$('#outputdiv1').html(data);
}
);
The php echo output goes to a div on the main page called outputdiv1.
I got that part; no problem. Not sure exactly how it works, but it does work.
I would also like to echo output to a different div (which I will call outputdiv2) on the same page, using the php script. In my php script, How do I refer to or echo output this other div?
I guess I could have a second $.post statement in the javascript code, accessing a second php script. But that would force me to access the mysql database a second time. Doesn't seem efficient to me.
Is there a better way to do this?
Thanks.
HTML code is here:
theuser is defined earlier
<table width=400 align=center><tr><td>
There is a question here, with 2 possible answers:<p>
<form>
<input type=radio style="width:22px; height:22px" name="ques1" id="opt1" value="answer 1" onclick="post1()"> answer 1<br>
<input type=radio style="width:22px; height:22px" name="ques1" id="opt2" value="answer 2" onclick="post1()"> answer 2<br>
</form>
<div id="outdiv1">first response from php will go here, beneath the question.<br></div>
<script type="text/javascript">
function post1() {
var uans1 = "none"
if (document.getElementById("opt2").checked) {
uans1 = "answer 2"
}
if (document.getElementById("opt1").checked) {
uans1 = "answer 1"
}
$.post('ajax/phpscript.php',{postuser:theuser,postname:uans1}, function(data) {$('#ans1div').html(data);});
}
</script>
</td>
<td width=20%>
<div id="outputdiv2">
second response from php will go here, to the right of the question.<p>
</div>
</td>
</tr></table>
first response will not be the same as the second response.
You could use JSON to communicate and return an array. something like this in js
$.ajax({
url: 'ajax/phpscript.php',
method: 'POST',
data: {
postuser: theuser,
postname: uans1
},
dataType: 'JSON'
}).done(function(data) {
if ($.isArray(data)) {
$('#outputdiv1').html(data[0]);
$('#outputdiv2').html(data[1]);
}
});
And your php script should do something look like this
<?php
include('dbconnection.php');
$result = [];
//SELECT data for div1 (part you already have)
$result[] = $mysql_result_as_html_for_outputdiv_1; // In your case this would be a html string
//SELECT other data for div2
$result[] = $mysql_result_as_html_for_outputdiv_2; // In your case this would be a html string
header('Content-Type: application/json');
echo json_encode($result);
?>
An even more clean solution would be to just return the data as objects from php and make some templates in js suitable for your data.
You need to understand this: who write in the div is javascript, not php, cause you are using ajax. Ajax is a way to comunicate with php, and give a response. Now you need to handle this response with javascript.
If you want to put the same content in outputdiv1 and outputdiv2, you not need to post ajax again, only write it in two divs.
$.post('ajax/phpscript.php',{postuser:theuser,postname:uans1}, function(data) {$('#outputdiv1').html(data);$('#outputdiv2').html(data);});
if you want different data i suggest you think the system to get all result that you need in one post request and return it in a json format (see http://php.net/manual/es/function.json-encode.php), so you can handle better with JSON.parse() in client side.

AJAX\JQUERY: Update MYSQL database with form data without refreshing

Ok, so I've gotten most of this thing done.. Now comes, for me, the hard part. This is untreaded territory for me.
How do I update my mysql database, with form data, without having the page refresh? I presume you use AJAX and\or Jquery to do this- but I don't quite grasp the examples being given.
Can anybody please tell me how to perform this task within this context?
So this is my form:
<form name="checklist" id="checklist" class="checklist">
<?php // Loop through query results
while($row = mysql_fetch_array($result))
{
$entry = $row['Entry'];
$CID = $row['CID'];
$checked =$row['Checked'];
// echo $CID;
echo "<input type=\"text\" value=\"$entry\" name=\"textfield$CID;\" id=\"textfield$CID;\" onchange=\"showUser(this.value)\" />";
echo "<input type=\"checkbox\" value=\"\" name=\"checkbox$CID;\" id=\"checkbox$CID;\" value=\"$checked\"".(($checked == '1')? ' checked="checked"' : '')." />";
echo "<br>";
}
?>
<div id="dynamicInput"></div>
<input type="submit" id="checklistSubmit" name="checklistSubmit" class="checklist-submit"> <input type="button" id="CompleteAll" name="CompleteAll" value="Check All" onclick="javascript:checkAll('checklist', true);"><input type="button" id="UncheckAll" name="UncheckAll" value="Uncheck All" onclick="javascript:checkAll('checklist', false);">
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');"></form>
It is populated from the database based on the users session_id, however if the user wants to create a new list item (or is a new visitor period) he can click the button "Add another text input" and a new form element will generate.
All updates to the database need to be done through AJAX\JQUERY and not through a post which will refresh the page.
I really need help on this one. Getting my head around this kind of... Updating method kind of hurts!
Thanks.
You will need to catch the click of the button. And make sure you stop propagation.
$('checklistSubmit').click(function(e) {
$(e).stopPropagation();
$.post({
url: 'checklist.php'
data: $('#checklist').serialize(),
dataType: 'html'
success: function(data, status, jqXHR) {
$('div.successmessage').html(data);
//your success callback function
}
error: function() {
//your error callback function
}
});
});
That's just something I worked up off the top of my head. Should give you the basic idea. I'd be happy to elaborate more if need be.
Check out jQuery's documentation of $.post for all the nitty gritty details.
http://api.jquery.com/jQuery.post/
Edit:
I changed it to use jquery's serialize method. Forgot about it originally.
More Elaboration:
Basically when the submit button is clicked it will call the function specified. You want to do a stop propagation so that the form will not submit by bubbling up the DOM and doing a normal submit.
The $.post is a shorthand version of $.ajax({ type: 'post'});
So all you do is specify the url you want to post to, pass the form data and in php it will come in just like any other request. So then you process the POST data, save your changes in the database or whatever else and send back JSON data as I have it specified. You could also send back HTML or XML. jQuery's documentation shows the possible datatypes.
In your success function will get back data as the first parameter. So whatever you specified as the data type coming back you simply use it how you need to. So let's say you wanted to return some html as a success message. All you would need to do is take the data in the success function and place it where you wanted to in the DOM with .append() or something like that.
Clear as mud?
You need two scripts here: one that runs the AJAX (better to use a framework, jQuery is one of the easiest for me) and a PHP script that gets the Post data and does the database update.
I'm not going to give you a full source (because this is not the place for that), but a guide. In jQuery you can do something like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { // DOM is ready
$("form#checklist").submit(function(evt) {
evt.preventDefault(); // Avoid the "submit" to work, we'll do this manually
var data = new Array();
var dynamicInputs = $("input,select", $(this)); // All inputs and selects in the scope of "$(this)" (the form)
dynamicInputs.each(function() {
// Here "$(this)" is every input and select
var object_name = $(this).attr('name');
var object_value = $(this).attr('value');
data[object_name] = object_value; // Add to an associative array
});
// Now data is fully populated, now we can send it to the PHP
// Documentation: http://api.jquery.com/jQuery.post/
$.post("http://localhost/script.php", data, function(response) {
alert('The PHP returned: ' + response);
});
});
});
</script>
Then take the values from $_POST in PHP (or any other webserver scripting engine) and do your thing to update the DB. Change the URL and the data array to your needs.
Remember that data can be like this: { input1 : value1, input2 : value2 } and the PHP will get something like $_POST['input1'] = value1 and $_POST['input2'] = value2.
This is how i post form data using jquery
$.ajax({
url: 'http://example.com',
type: 'GET',
data: $('#checklist').serialize(),
cache: false,
}).done(function (response) {
/* It worked */
}).fail(function () {
/* It didnt worked */
});
Hope this helps, let me know how you get on!

Opening jQuery UI Dialog box with dynamic content

I have a question about jQuery UI Dialog boxes and showing dynamic content from a database.
So I got a webapplication where I also need to make a admin module to manage all users and other information. I created a page that shows all users in a list, in every row I also made an edit button. I wanted to make it so that when you press on a users' edit button, a dialog box opens and shows all the user information and stuff in the dialog box.
So my question is, what is the best way to do this? I was thinking about making a PHP page where I execute the MySQL Query and show that in the dialog box, but I am sure there are better ways..
EDIT: Here is the code for the page as it is right now. I added a small placeholder dialogbox that I used for testing purposes.
Javascript:
script type="text/javascript">
jQuery(document).ready( function(){
jQuery(".edit-button").click( showDialog );
//variable to reference window
$myWindow = jQuery('#myDiv');
//instantiate the dialog
$myWindow.dialog({ height: 600,
width: 800,
modal: true,
position: 'center',
autoOpen:false,
title:'Bewerk therapeut',
overlay: { opacity: 0.5, background: 'black'}
});
}
);
//function to show dialog
var showDialog = function() {
$myWindow.show();
//open the dialog
$myWindow.dialog("open");
}
var closeDialog = function() {
$myWindow.dialog("close");
}
PHP:
<?php
//LEFT OUTER JOIN Vragen ON Vragen.bsn_nummer = Gebruikers.bsn_nummer
include_once 'classes/class.mysql.php';
$db = new Mysql();
$dbUsers = new Mysql();
$db->Query("SELECT * FROM USERS_users ORDER BY username ASC");
$db->MoveFirst();
echo "<table>";
echo "<tr><th> </th><th> </th><th>BSN Nummer</th><th>Gebruikersnaam</th> <th>Voornaam</th><th>Achternaam</th></tr>";
while(! $db->EndOfSeek()) {
$row = $db->Row();
$dbUsers->Query("SELECT * FROM Gebruikers WHERE user_idnr = '{$row->user_idnr}'");
$rowUser = $dbUsers->Row();
echo "<tr><td><a class='del-button' href='#'><img src='afbeeldingen/edit-delete.png' /></a></td>
<td><a class='edit-button' href='#'><img src='afbeeldingen/edit.png' /></a> </td>
<td>".#$rowUser->bsn_nummer."</td>
<td>".#$row->username."</td>
<td>".#$rowUser->voornaam."</td>
<td>".#$rowUser->achternaam."</td></tr>";
}
echo "</table>";
?>
<div id="myDiv" style="display: none">
<p>Gebruiker bewerken</p>
</div>
Nope. Sounds like you've got it right.
placeholder for the popup ->
<div id="popup"></div>
jQuery ui dialog ->
$('#popup').dialog({
autoOpen: 'false',
modal: 'true',
minHeight: '300px',
minWidth: '300px',
buttons: {
'Save Changes': function(){
$.ajax({
url: 'path/to/my/page.ext',
type: 'POST',
data: $(this).find('form').serialize(),
success: function(data){
//some logic to show that the data was updated
//then close the window
$(this).dialog('close');
}
});
},
'Discard & Exit' : function(){
$(this).dialog('close');
}
}
});
Now that the default settings have been created, send a ajax request for the data from the php file, and update the content in the 'popup' div.
$('.edit').click(function(e){
e.preventDefault();
$.ajax({
url: 'path/to/my/page.ext',
type: 'GET',
data: //send some unique piece of data like the ID to retrieve the corresponding user information
success: function(data){
//construct the data however, update the HTML of the popup div
$('#popup').html(data);
$('#popup').dialog('open');
}
});
});
in the PHP page, construct a form to be sent back ->
<?php
if(isset($_GET['id'])){
//build the query, do your mysql stuff
$query = mysql_query(sprintf("SELECT * FROM sometable WHERE id = %d", $_GET['id']));
//construct constant objects outside of the array
?>
<form>
<?php
while($row = mysql_fetch_array($query)){
?>
<tr>
<td>
<input type="text" name="<?php echo $row['id']?>" value="<?php echo $row['name'] ?>" />
</td>
</tr>
<?php
}
?>
</form>
<?php
}
?>
I am sure there are better ways..
No, that's about it.
You'll need a PHP script to give you the user's current details, and a second in which you should combine adding a new user, or updating an existing user.
Use AJAX to obtain the list of users, and likewise have the "current detail" page send back an JSON blob containing the information.
Use the client side Javascript to populate the dialog itself.
The hardest part is making sure that only authorised users can talk to the backend scripts.
Here's what I would do:
when creating the list of users, I know the id (unique) for each user. Then attach an event handler for the edit button that will make an ajax request to a server side script with that user id, the server side script will send you user details in JSON format.
have a template, for example a div, that has all the fields you need for updating user details (with classes attached or ids so you will know how to find them with selectors). when you receive data from the server you set the value of the fields in your template to the data in the response of the server then open the dialog (which is pre populated now with the data you need).
updating user details can also be done by ajax, to keep things simple. (grabbing the values in the inputs, and send a request to the server, sending also the id of the user you want to change details.
So... good luck!
The simplest way would be to get the information in the database using PHP, and populate the UI tables like that. The major downside would be loading time. If you find that the page is taking too long to load, then you may want to look into jQuery's .ajax()

How to pass multiple selected (through checkboxes) row ids to a php script in jQuery?

I'm generating an html file which looks like:
<tr id="ID001" property1="PROPERTY001"><td><input type="checkbox"
name="row_checkbox_ID001"></td><td>...</td><td>...</td></tr>
<tr id="ID002" property1="PROPERTY002"><td><input type="checkbox"
name="row_checkbox_ID002"></td><td>...</td><td>...</td></tr>
When the user selects individual rows for deletion, how can I (through jQuery), pass this to a php script?
I will need to build something like this:
$(document).ready(function () {
$('#contact-form input.contact-delete').click(function (e) {
e.preventDefault();
$.get("deleterecord.php", ...);
});
});
There can be 0, 1 or multiple rows... The HTML being generated is under my control and can be modified.
Clarification:
I want to have a button above all these rows which the user can click on AFTER he has selected the rows from the table.
<div id='contact-form'><h2>Contacts</h2>
<input type='button' name='contact-delete' value='Delete Record(s)'
class='contact-delete'/>
The TRs need to be deleted, but BEFORE that, the deleterecord.php script needs to be called with the TR ids.
Use HTML arrays
<input type="checkbox" name="chk[]" value="01234">
<input type="checkbox" name="chk[]" value="98765">
You could create a JSON object containing details of any rows selected (ID's or whatever you need) and send that to your php script. Check out this article on json, php + jquery.
I believe, you are looking for similar behavior:
$('#contact-form input.contact-delete').click(function (e) {
var $this = $(this);
// find the table row, in which are elements contained
var $tr = $this.closest('tr');
// take id
var id = $tr.attr('id');
// ajax with id
$.get("deleterecord.php?id="+id, function (data) {
// remove table row on success
$tr.remove();
});
e.preventDefault();
});
Sorry for answering my own question, but the SO post at: Getting all selected checkboxes in an array neatly solves my problem!
For future visitors to this page, pay attention to variable names in your HTML and how you're accessing the input checkboxes in jQuery!

Categories