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).
Related
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..!
Coming from Adobe Flex I am used to having data available in an ArrayCollection and when I want to display the selected item's data I can use something like sourcedata.getItemAt(x) which gives me all the returned data from that index.
Now working in php and javascript I am looking for when a user clicks a row of data (in a table with onClick on the row, to get able to look in my data variable $results, and then populate a text input with the values from that row. My problem is I have no idea how to use javascript to look into the variable that contains all my data and just pull out one row based on either an index or a matching variable (primary key for instance).
Anyone know how to do this. Prefer not firing off a 'read' query to have to bang against the mySQL server again when I can deliver the data in the original pull.
Thanks!
I'd make a large AJAX/JSON request and modify the given data by JavaScript.
The code below is an example of an actual request. The JS is using jQuery, for easier management of JSON results. The container object may be extended with some methods for entering the result object into the table and so forth.
PHP:
$result = array();
$r = mysql_query("SELECT * FROM table WHERE quantifier = 'this_section'");
while($row = mysql_fetch_assoc($r))
$result[$row['id']] = $row;
echo json_encode($result);
JavaScript + jQuery:
container.result = {};
container.doStuff = function () {
// do something with the this.result
console.debug(this.result[0]);
}
// asynchronus request
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(result){
container.result = result;
}
});
This is a good question! AJAXy stuff is so simple in concept but when you're working with vanilla code there are so many holes that seem impossible to fill.
The first thing you need to do is identify each row in the table in your HTML. Here's a simple way to do it:
<tr class="tablerow" id="row-<?= $row->id ">
<td><input type="text" class="rowinput" /></td>
</tr>
I also gave the row a non-unique class of tablerow. Now to give them some actions! I'm using jQuery here, which will do all of the heavy lifting for us.
<script type="text/javascript">
$(function(){
$('.tablerow').click(function(){
var row_id = $(this).attr('id').replace('row-','');
$.getJSON('script.php', {id: row_id}, function(rs){
if (rs.id && rs.data) {
$('#row-' + rs.id).find('.rowinput').val(rs.data);
}
});
});
});
</script>
Then in script.php you'll want to do something like this:
$id = (int) $_GET['id'];
$rs = mysql_query("SELECT data FROM table WHERE id = '$id' LIMIT 1");
if ($rs && mysql_num_rows($rs)) {
print json_encode(mysql_fetch_array($rs, MYSQL_ASSOC));
}
Maybe you can give each row a radio button. You can use JavaScript to trigger an action on selections in the radio button group. Later, when everything is working, you can hide the actual radio button using CSS and make the entire row a label which means that a click on the row will effectively click the radio button. This way, it will also be accessible, since there is an action input element, you are just hiding it.
I'd simply store the DB field name in the td element (well... a slightly different field name as there's no reason to expose production DB field names to anyone to cares to view the page source) and then extract it with using the dataset properties.
Alternatively, you could just set a class attribute instead.
Your PHP would look something like:
<tr>
<td data-name="<?=echo "FavoriteColor"?>"></td>
</tr>
or
<tr>
<td class="<?=echo "FavoriteColor"?>"></td>
</tr>
The javascript would look a little like:
var Test;
if (!Test) {
Test = {
};
}
(function () {
Test.trClick = function (e) {
var tdCollection,
i,
field = 'FavoriteColor',
div = document.createElement('div');
tdCollection = this.getElementsByTagName('td');
div.innerText = function () {
var data;
for (i = 0; i < tdCollection.length; i += 1) {
if (tdCollection[i].dataset['name'] === field) { // or tdCollection[i].className.indexOf(field) > -1
data = tdCollection[i].innerText;
return data;
}
}
}();
document.body.appendChild(div);
};
Test.addClicker = function () {
var table = document.getElementById('myQueryRenderedAsTable'),
i;
for (i = 0; i < table.tBodies[0].children.length; i += 1) {
table.tBodies[0].children[i].onclick = Test.trClick;
}
};
Test.addClicker();
}());
Working fiddle with dataset: http://jsfiddle.net/R5eVa/1/
Working fiddle with class: http://jsfiddle.net/R5eVa/2/
See this form - http://schnell.dreamhosters.com/form.php
This form has a portion of it where you enter data and can choose to add more of the same data by clicking a button called 'Add A Site' and it will make another of that section to enter another site. This is the jQuery that performs the duplication...
$(function () {
var sites = 1;
var siteform = $("#site1").html();
$(".addsites").live("click", function(e) {
e.preventDefault();
sites++;
$("#events").append("<div id='site" + sites + "'>"
+ "<br /><hr><br />"
+ siteform
+ "<center><button class='removesites' title='site"
+ sites + "'>Remove This Site</button><br />"
+ "<button class='addsites'>Add Another Site</button>"
+ "</center></div>");
});
$(".removesites").live("click", function(e) {
e.preventDefault();
var id = $(this).attr("title");
$("#" + id).remove();
});
});
The duplication works perfectly, but one thing that's bugging me is that when I have to enter data for someone claiming a LOT of sites, it gets very annoying having to repeat same or similar parts of this section of the form (like every site is in the same city, on the same day, by the same person, etc.) So I had the idea that with each duplication, the values of the form elements would also carry over and I just edit what's not the same. The current implementation only duplicates the elements, not the data. I'm not sure how to easily copy the data into new sections, and I can't find any jQuery tools to do that.
PS - This part isn't as important, but I've also considered using this same form to load the data back in for viewing/editing, etc. The only problem with this is that the reprinting of the form means that there will be a form section with the id "Site7" or something, but jQuery starts its numbering at 1, always. I've thought about using selectors to find the highest number site and start off the variable 'sites' at that number, but I'm not sure how. Any advice how to do this, or a better system overall, would be much appreciated.
You want to itterate over the input fields in siteform and store them in an object using their name attribute as a key.
Then after the duplication of the object you made and look for the equivelant fields in the new duplicated form ans set their values.
Somthing like this (not tested, just the idea)
var obj = new Object();
$("#site1 input").each(function(){
obj[this.id] = this.value;
);
// Dupicate form
$.each(obj, function(key, value){
$('#newform input[name="'+key+'"]').value = value;
});
Mind you these two each() functions differ from each other.
http://api.jquery.com/jQuery.each/
http://api.jquery.com/each/
You could consider using cloneNode to truely clone the previous site-div and (by passing true to cloneNode) all of its descendants and their attributes. Just know that the clone will have the same id as the original, so you'll have to manually set its id afterwards
Try this in your click-function
var clone = $("#site" + sites).clone(true, true); // clone the last div
sites++; // increment the number of divs
clone.attr('id', "site" + sites); // give the clone a unique id
$("#events").append(clone); // append it to the container
As Scuzzy points out in a comment jQuery does have its own clone() method (I don't use jQuery much, so I didn't know, and I didn't bother to check before answering). Probably better to use jQuery's method than the built-in cloneNode DOM method, since you're already using jQuery for event listeners. I've updated the code
The query to transfer values is quite simple (please, check the selector for all the right types on the form):
$("#site1").find("input[checked], input:text, input:hidden, input:password, input:submit, option:selected, textarea")
//.filter(":disabled")
.each(function()
{
$('#site2 [name="'+this.name+'"]').val(this.value);
}
Ok I finally figured this out. It's, more or less, an expansion on Alex Pakka's answer.
sites++;
$("#events").append("<div id='site" + sites + "'>"
+ "<hr><br />"
+ siteform
+ "<center><button class='removesites' title='site"
+ sites + "'>Remove This Site</button><br />");
$("#site1").find("input:checked, input:text, textarea, select").each(function() {
var name = $(this).attr("name");
var val = $(this).val();
var checked = $(this).attr("checked");
var selected = $(this).attr("selectedIndex");
$('#site' + sites + ' [name="'+name+'"]').val(val);
$('#site' + sites + ' [name="'+name+'"]').attr("checked", checked);
$('#site' + sites + ' [name="'+name+'"]').attr("selectedIndex", selected);
});
I used extra vars for readability sake, but it should do just as fine if you didn't and used the methods directly.
Dont forget to create a function for registering the event! Its very important because when the DOM is loaded, all new attributes need to be registrated to the DOM.
Small example:
<script>
$(document).ready(function(){
$('#click-me').click(function(){
registerClickEvent();
})
function registerClickEvent(){
$('<input type="text" name="input_field_example[]">').appendTo('#the-div-you-want')
}
registerClickEvent();
})
</script>
I've referred to this post:
Post array of multiple checkbox values
And this jQuery forum post:
http://forum.jquery.com/topic/checkbox-names-aggregate-as-array-in-a-hidden-input-value
I am trying to collect an array (or concatenated string with commas, whatever) of checkbox values in a hidden input field using jQuery. Here's the script code I'm using:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val(function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
});
});
</script>
A snippet of the relevant HTML:
<form id="advancedSearchForm" name="advancedSearchForm" method="post" action="<?php echo site_url('/magcm/advancedSearch#results'); ?>">
<input type="checkbox" name="FCM" id="FCM" class="chk" value="FCM" <?php echo set_checkbox('FCM', 'FCM'); ?>/>
<input type="hidden" name="specialty" id="specialty" value="" />
<input class="button" name="submit3" id="submit3" type="submit" value="Search" />
I've tried changing "submit" to "submit3" in the jQuery, which breaks (obviously). When I print_r($_POST), the checkboxes POST correctly but the condensed hidden variable does not. (It posts, but a blank value.) The checkboxes persist correctly using CI's hacked set_value() function (Derek needs to implement this in the main trunk... but that's another story)
I'm sure I'm doing something that is wrong and easy to point out. I've just been banging my head against the wall for the past 2 hours on it, trying various functions and changing a ton of things and analyzing it in Chrome dev tools (which don't show any errors).
Help is appreciated. :)
Let's say you applied an class, maybe "tehAwesomeCheckboxen" to every checkbox. Then
<script>
$("#advancedSearchForm").submit(function() {
var chkbxValues = $(".tehAwesomeCheckboxen").val();
$("#specialty").val( chkbxValues.join(",") );
});
</script>
EDIT:
I don't think the $_POST array is getting populated, since the submit is being handled locally by the JavaScript engine. SO... let's try this:
<script>
var chkbxValues = new Array();
$(".tehAwesomeCheckboxen").live("change", function(e){
var val = $(this).val();
if( $(this).is(":checked") ) {
if( chkbxValues.length == 0 || chkbxValues.indexOf(val) == -1){
// Add the value
chkbxValues.push(val);
}
}
else {
// remove the value
chkbxValues.splice( chkbxValues.indexOf(val), 1 );
}
$("#specialty").val( chkbxValues.join(",") );
});
</script>
This adds an event handler the checkboxes themselves, such that checking/unchecking the box alters the hidden element. Then your form handles its submission as normal.
Is this more in line with what you're trying to do?
P.S. Those who upvoted this, please note I have modified my answer. Please verify whether you still find it useful and adjust your vote accordingly.
I ended up solving it using PHP arrays rather than jQuery:
<input type="checkbox" name="chk[]" id="RET" class="chk" value="RET" <?php echo set_checkbox('chk', 'RET'); ?>/>
I changed the name to an array and POSTed it to my script, where I looped through the array and handled it there. Still not sure what the problem was with the jQuery-based solutions, but I figured I'd post this for everyone to refer to in the future.
You've got lots of nested functions() in your JavaScript, makes it hard to follow what you're doing.
However, it seems that you're just passing a function to .val() rather than an actual value. Try this instead:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val((function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
})());
});
</script>
Or even better, calculate the value first:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
var value = $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
$(form).find("input[name=specialty]").val(value);
});
</script>
I have a simple checkbox on a page that allows a user to say if they'd like to receive email notifications. I am using jquery for this to call some php code when the checkbox changes. However, I am not having much luck even calling the jquery function (clicking the checkbox does nothing) let alone test the backend functionality.
Any help in pointing out the error would be great. Thanks.
The checkbox HTML:
<input id="notify_checkbox" type="checkbox" value="y" name="notify">
The jquery:
$('#notify_checkbox').change(function(){
if($('#notify_checkbox').attr('checked'))
{
$.post("/update_notify", { checked: "y", email: "<?php echo $this->session->userdata('email');?>" });
$( "#notifyresult" ).html( "<p>Awesome, we'll send you an email!</p>" );
}
else
{
$.post("/update_notify", { checked: "n", email: "<?php echo $this->session->userdata('email');?>" });
$( "#notifyresult" ).html( "<p>Okay, we won't email you.</p>" );
}
});
And finally the PHP:
function update_notify()
{
// Passed through AJAX
$notify = $_POST[checked];
$email = $_POST[email];
$this->load->model('musers');
$query = $this->musers->update_user_notify($email, $notify);
}
RESOLUTION: The comments below were helpful but not the ultimate solution. The solution was to add the following around my code.
$(document).ready(function() {
{);
Why not use .click() instead?
JSFIDDLE
Also, as you can see in my JSFiddle example, use .is(':checked') instead of attr('checked').
edit after #Rocket commented on your post:
You should indeed quote your $_POST values in your php! Didn't notice it myself, credits to rocket
What's the name of your controller? You need to put that in the URL.
$.post("/controller/update_notify", ...
The problem is with the redefinition of the attr function in jQuery 1.6, and with the difference between attributes and properties.
With attributes (retrieved with attr), the value of checked="checked" or its absence stays the same, regardless of whether the element is actually checked or not.
With properties (retrieved with prop as of jQuery 1.6), the actual state of the element is found. This is equivalent to checking the checked property of the element (which is preferable because you don't need to do a new jQuery selection). The best soltion would be as follows:
if (this.checked) {
See jsFiddles showing this:
your current solution
using prop
using this.checked