.on('click') doesn't work, but all other handlers do - php

I recently asked a question about triggering dynamically created divs, and was introduced to the .on() function.
'keyup' works great, 'mouseover' works, a few others I've tested work but 'click' just will not fire.
I created added information to a div via ajax and .php which holds some data like this:
function loadNewcomment(divID) {
$.ajax({
url: templateUrl+"/enternote.php",
cache: false,
success: function(html){
$("#"+divID).append(html);
}
});
}
I wanted to trigger on keyup for an element within that created div and this code works for that:
$("#notebox").on('keyup', '.note-field', function(event){
var thisString = $(this).val();
$keyLength = thisString.length;
$rowCount = Math.ceil($keyLength/40);
$currentRow = $(this).attr("rows");
if($currentRow < $rowCount){
$(this).animate({rows:$rowCount},50);
}
});
This code however does NOT work:
$("#notebox").on('click', '.note-field', function() {
alert("clicked");
});

dynamic DOM and jQuery is a pain. I know its deprecated but I have used in the past with great results: http://api.jquery.com/live/
FWIW - you could also try using bind() - http://api.jquery.com/bind/

I had an .stopPropagation(); somewhere else in the code in the encompassing div, I commented it out for now and it works, thanks.

Is it possible to attach click event after html is appended.
function loadNewcomment(divID) {
$.ajax({
url: templateUrl+"/enternote.php",
cache: false,
success: function(html){
$("#"+divID).append(html).bind('click', function() { /* Click event code here */ }); // id divID is #notebox
}
});
}

You can just use click like this:
$("#notebox").click( function() {
alert("clicked");
});
http://jsfiddle.net/7MBw4/

Related

TINYMCE not sending editor content via AJAX [duplicate]

I m using tinyMCE for textareas and POSTing form through AJAX.
But when I m trying to save textarea value, it is taking old values on first click, but it takes updated values on second click.
I have tried using tinyMCE.triggerSave() but it didn't work.
I have also tried tinyMCE.get('myid').getContent(), still it takes old values.
My code is as follows.
$(".submit").live("click", function () {
tinyMCE.triggerSave();
var f = $(this).parents("form");
var action = f.attr("action");
var serializedForm = f.serialize();
//tinyMCE.triggerSave(); also tried putting here
$.ajax({
type: 'POST',
url: action,
data: serializedForm,
async: false,
success: function (data, textStatus, request) {
$(".divform").html(data);
},
error: function (req, status, error) {
alert&("Error occurred!");
}
});
return false;
});
Please help, any help would be appreciated
You can configure TinyMCE as follows to keep the values of hidden textareas in sync as changes are made via TinyMCE editors:
tinymce.init({
selector: "textarea",
setup: function (editor) {
editor.on('change', function () {
tinymce.triggerSave();
});
}
});
With this in place, you can access up-to-date values directly from the textarea elements at any time.
This has been tested on TinyMCE 4.0
Demo running at: http://jsfiddle.net/9euk9/
Use this instead of tinymce.triggerSave();
$('#' + 'your_editor_id').html( tinymce.get('your_editor_id').getContent() );
An alternative implementation to the one posted by Dan Malcolm, for TinyMCE 3.x, would be as follows:
tinymce.init({
selector: "textarea",
setup: function (editor) {
editor.onChange.add(function() {
editor.save();
});
}
});
As well as working on 3.x, this version uses editor.save instead of tinymce.triggerSave, which means it only updates the current editor rather than all editors in the page.
user this script before posting data by using Ajax. This is javascript code before use please load tiny mce js file and user it.
tinymce.triggerSave();
$.ajax({
type: 'post',
url: 'autoSaveReport.php',
data: $('form').serialize(),
success: function (result) {
var redirectURL = window.location.pathname;
var redirectURL1 = redirectURL+"?incid="+result;
window.location = window.location+"?incid="+result;
}
});
For me works fine with
tinymce.triggerSave();
Put it before the ajax post
I know time passed but i found this solution today.
Before serialize the form you must save the editor just using the method:
tinymce.activeEditor.save();
var serializedForm = f.serialize();
Maybe this helps some comrade.
For multiple instances:
tinymce.init({
mode : "specific_textareas"
,body_class: 'tinymceclass'
,setup: function (editor) {
editor.onChange.add(function() {
$('#' + this.id).html( tinymce.get(this.id).getContent() );
});
}
});

jquery add toggle function to div after adding html to it

How can I add toggle function to a div which is populated with ajax response on click. Right now i can achieve the both functions but I need two clicks to get the div displayed after getting populated. Can I get this done at one click (i.e populating the div and adding toggle function)?
Any help would be greatly appreciated.
My code:
$(document).ready(function(){
$(".ex2").on('click', '.spnSelected', function() {
var self = $(this).closest("tr");
var col1_value = self.find(".col1").text();
$.ajax({
type: 'GET',
url: 'reportForm.php',
data: { propid: col1_value },
success: function(response) {
$('#form'+col1_value).html(response);
$('#form'+col1_value).toggle();
}
});
});
});
Second line $(".ex2").on('click', '.spnSelected', function() { change to $("body").on('click', '.ex2 .spnSelected', function() { should work like charm.
in you code you attached event on .ex2 click, so if you adding more .ex2 elements with ajax. you don't have event attached on new elements. when you attact click event on body and then check if .spnSelected clicked this shuld work with new elements.

jQuery .change() not responding as expected

I have a select that I am trying to do a jQuery .change event on. For some reason it is not recognizing the id of the select. It is built through another AJAX call to a php file that creates the select and its options.
<script>
$(document).ready(function()
{
$("#unitselector").on('change', function()
{
console.log('made it');
var unit=$('#unitselector').filter(':selected').val();
var dataString = {unit:unit};
console.log(dataString);
$.ajax({
type: "POST",
url: "classes/unit_info.php",
data: dataString,
cache: false,
success: function(html)
{
$('.unitinfo').html(html);
}
});
});
});
</script>
relevant PHP:
echo '<select id="unitselector" name="units">';
while( $row = mysqli_fetch_assoc($result))
{
$units[] = $row['unit_name'];
echo '<option value="'.$row['unit_name'].'">'.$row['unit_name'].'</option>';
}
echo '</select>';
It is built through another AJAX call to a php file that creates the select and its options.
That means it's dynamically added to the DOM and as such requires event delegation. jQuery 1.7+ uses the .on() method in order to bind properly.
$("#unitselector").on('change', function()
to
$(document).on('change', '#unitselector', function()
Further, there's really no reason to try and get the value like you're doing. You're inside of the element and therefore can access it through this which is the native javascript object, or $(this) which is a jQuery object, either way will work fine.
var unit = $(this).val();
//or
var unit = this.value;

Issue with using a value in JQuery/Javascript

I have a PHP populated table from Mysql and I am using JQuery to listen if a button is clicked and if clicked it will grab notes on the associated name that they clicked. It all works wonderful, there is just one problem. Sometimes when you click it and the dialog(JQuery UI) window opens, there in the text area there is nothing. If you are to click it again it will pop back up. So it seems sometimes, maybe the value is getting thrown out? I am not to sure and could use a hand.
Code:
$(document).ready(function () {
$(".NotesAccessor").click(function () {
notes_name = $(this).parent().parent().find(".user_table");
run();
});
});
function run(){
var url = '/pcg/popups/grabnotes.php';
showUrlInDialog(url);
sendUserfNotes();
}
function showUrlInDialog(url)
{
var tag = $("#dialog-container");
$.ajax({
url: url,
success: function(data) {
tag.html(data).dialog
({
width: '100%',
modal: true
}).dialog('open');
}
});
}
function sendUserfNotes()
{
$.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data:
{
'nameNotes': notes_name.text()
},
success: function(response) {
$('#notes_msg').text(response.the_notes)
}
});
}
function getNewnotes(){
new_notes = $('#notes_msg').val();
update(new_notes);
}
// if user updates notes
function update(new_notes)
{
$.ajax({
type: "POST",
//dataType: "json",
url: '/pcg/popups/updateNotes.php',
data:
{
'nameNotes': notes_name.text(),
'newNotes': new_notes
},
success: function(response) {
alert("Notes Updated.");
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
});
}
/******is user closes notes ******/
function closeNotes()
{
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
Let me know if you need anything else!
UPDATE:
The basic layout is
<div>
<div>
other stuff...
the table
</div>
</div>
Assuming that #notes_msg is located in #dialog-container, you would have to make sure that the actions happen in the correct order.
The best way to do that, is to wait for both ajax calls to finish and continue then. You can do that using the promises / jqXHR objects that the ajax calls return, see this section of the manual.
You code would look something like (you'd have to test it...):
function run(){
var url = '/pcg/popups/grabnotes.php';
var tag = $("#dialog-container");
var promise1 = showUrlInDialog(url);
var promise2 = sendUserfNotes();
$.when(promise1, promise2).done(function(data1, data2) {
// do something with the data returned from both functions:
// check to see what data1 and data2 contain, possibly the content is found
// in data1[2].responseText and data2[2].responseText
// stuff from first ajax call
tag.html(data1).dialog({
width: '100%',
modal: true
}).dialog('open');
// stuff from second ajax call, will not fail because we just added the correct html
$('#notes_msg').text(data2.the_notes)
});
}
The functions you are calling, should just return the result of the ajax call and do not do anything else:
function showUrlInDialog(url)
{
return $.ajax({
url: url
});
}
function sendUserfNotes()
{
return $.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data: {
'nameNotes': notes_name.text()
}
});
}
It's hard to tell from this, especially without the mark up, but both showUrlInDialog and sendUserfNotes are asynchronous actions. If showUrlInDialog finished after sendUserfNotes, then showUrlInDialog overwrites the contents of the dialog container with the data returned. This may or may not overwrite what sendUserfNotes put inside #notes_msg - depending on how the markup is laid out. If that is the case, then it would explains why the notes sometimes do not appear, seemingly randomly. It's a race condition.
There are several ways you can chain your ajax calls to keep sendUserOfNotes() from completing before ShowUrlInDialog(). Try using .ajaxComplete()
jQuery.ajaxComplete
Another ajax chaining technique you can use is to put the next call in the return of the first. The following snippet should get you on track:
function ShowUrlInDialog(url){
$.get(url,function(data){
tag.html(data).dialog({width: '100%',modal: true}).dialog('open');
sendUserOfNotes();
});
}
function sendUserOfNotes(){
$.post('/pcg/popups/getNotes.php',{'nameNotes': notes_name.text()},function(response){
$('#notes_msg').text(response.the_notes)
},"json");
}
James has it right. ShowUrlInDialog() sets the dialog's html and sendUserOfNotes() changes an element's content within the dialog. Everytime sendUserOfNotes() comes back first ShowUrlInDialog() wipes out the notes. The promise example by jeroen should work too.

How to request page content by clicking a div with jQuery mobile?

I am trying to fetch data form a callback page (php) and load it into a html div with jQuery mobile. This should happen if a user clicks on another div.
What I actually got is
$.('#home-button').bind('vclick', function( e ) {
$.get('homeCallback.php',function(data){
$('#displayContent').append(data).trigger('create');
},'html');
});
Where #home-button is the div that should trigger the event and #displayContent the div where the content should be put in.
The request should be able to pass some parameters, too. Like homeCallback.php?param=1 but it could also use the post method.
The callback does not have to be html only, it could also be possible that the callback php script provides JSON data or anything.
I am not a JS crack so I have problems solving this issue. Thanks for your help!
Edit:
So I found a solution on my own:
$(document).ready(function() {
$.ajaxSetup ({
cache: false
});
var ajaxLoader = '<img src="images/ajax-loader.gif" alt="loading.." />';
var loadUrl = "homeCallback.php";
$('#home-button1').click(function(){
$('#displayContent').toggle('fast', function() {
$(this).html(ajaxLoader);
$(this).toggle('fast', function() {
$.get(loadUrl + '?option1',function(data){
$('#displayContent').html(data);
},'html');
});
});
});
$('#home-button2').click(function(){
$('#displayContent').toggle('fast', function() {
$(this).html(ajaxLoader);
$(this).toggle('fast', function() {
$.get(loadUrl + '?option2',function(data){
$('#displayContent').html(data);
},'html');
});
});
});
});
And this is what homeCallback.php simply does..
<?php
if( isset($_GET["option1"] ))
echo "option1";
if( isset($_GET["option2"] ))
echo "option2";
So far.
$.('#home-button').bind('click', function() {
$.ajax({
url: "homeCallback.php",
type: "POST",
data: ({param: 1, param2: 2}),
success: function(html){
$("#displayContent").html(html);
}
});
});

Categories