Select2 is not working with elements added via Ajax - javascript

I am trying to add a new <select class="js-select-search"> element on the page through AJAX, but it seems that a standard call in that way doesn't work:
$('.js-select-search').select2();
I understand that it's a new element in the DOM, but I don't get how to make it work.

Select2 is a function. It runs once, and then never again. You can run it again however in the 'success' part of your ajax call.
$.ajax({
success: function () {
$('.js-select-search').select2();
}
})

Related

How to trigger the event manually once the ajax content's script is executed completely?

I am loading a html page with script section(render the JQuery UI) via AJAX. This html page contains more number widgets. In success function of Ajax, I am accessing the UI controls by its JQuery UI class names, but none of the class names are added i.e., script is not executed. If I access the same after 100ms using setTimeOut its working.
Please refer the below code:
var self = this;
$.ajax({
url: url,
dataType: "html",
cache: true,
success: function (str,sta,xhr) {
$("#samplefile").html(str);
setTimeout(function() {
self.reg($("#samplefile .ui-widgetui"));
},100);
}
});
Its working fine but I want to access this without settime out. Can anyone please suggest on this?
It sounds perhaps that you are trying to access the DOM before everything is initialized. Have you tried wrapping the initialization of you ajax request in a jQuery $(document).ready() call? This makes sure that your DOM is in a initialized state before getting triggered.
https://learn.jquery.com/using-jquery-core/document-ready/

Display tinymce textarea dynamically

I have a drop down list that when a selection is made will insert a bunch of elements within a form to the DOM using ajax, within this form I have textareas that I wish to be TinyMCE textareas.
I have this inside of my HTML head:
<script type="text/javascript">
tinymce.init({
selector: "textarea"
});
</script>
This is the ajax function that I use to add a bunch of elements, this is working how I need it to.
function getSecFacility(facsecid, facid) {
$("#new_section_form").hide();
$.ajax({
type: "POST",
url: "facility_section_information.php",
data: 'facility_section_id='+facsecid+'&facility_id='+facid,
success: function(data){
$("#selected_fac_section").html(data);
}
});
//loadTinyMCEEditor();
};
I have other textareas on my page that are not inserted by ajax and they display as WYSIWYG editors no problem, the issue is when I am adding in new elements.
I have checked several other questions trying to find an "answer" but nothing is working.
I tried to make a function called loadTinyMCEEditor() that I was calling within my getSecFacility() function after my ajax call. Within this function I was trying to reinitialize tinyMCE for these newly added textareas.
loadTinyMCEEditor() looks like this:
function loadTinyMCEEditor() {
tinyMCE.init({
selector: "textarea"
});
tinyMCE.execCommand('mceAddControl', false, 'test'); //test is the class name I gave this textarea
//tinyMCE.execCommand('mceAddControl', true, 'test'); //tried setting the bool to true..even tried without these lines
}
No matter what I try I cannot seem to get it to work with newly inserted textareas, How can I get these textareas to be TinyMCE textareas?
EDIT
I can now view the editor to my newly added textareas after I make a selection from my drop down list. However this only works once, if I make a second selection the new textareas only display as plain textareas. Here is what I changed in my ajax function:
function getFacSecFacility(facsecid, facid) {
$("#new_section_form").hide();
$.ajax({
type: "POST",
url: "facility_section_information.php",
data: 'facility_section_id='+facsecid+'&facility_id='+facid,
success: function(data){
$("#selected_fac_section").html(data);
loadTinyMCEEditor();
}
});
};
function loadTinyMCEEditor() {
tinymce.init({
selector: "textarea"
});
}
So after I make a selection this ajax function will run and display new textareas + other form information and I re-initialize the tinymce editors but for some reason this is only working once.
What should I change/do so that I can make multiple selection from my drop down list so that each time the new textareas will display as tinymce textareas?
You need to call tinyMCE.activeEditor.setContent with your incoming ajax-content. In your callback try:
tinyMCE.activeEditor.setContent(data);
Greetings
If you want to convert #selected_fac_section to a tinymce editor, you should call the init function of tinymce in your success function. Ajax calls are async unless you define otherwise. So, if you try to initialize the textarea outside of the ajax call, there still won't be a textarea to decorate with tinymce because the ajax call hasn't been finished yet. Use the id value for the selector this time and you should be good to go.
I am writing this from my phone so writing code here is a pain. Sorry for that. Just wanted to help you out quickly after seing you comment on my another answer. Will check this thread first thing in the morning to make sure if you need more help.

jquery hide a div thats loaded by jquery

I'm creating a website and use jquery to post a form.
When I press the submit button a jquery function posts the form to a php file.
The php file creates a result error or success. The result is echoed by the php file
and jquery file outputs the echo using the .html() method.
I call the html output #result.
So my question is how do I hide the #result using jquery. This has to happen after 5 seconds.
This works fine when #result is loaded with the page. But not when #result is loaded like is said above.
setTimeout(function(){
$('#result').slideUp(500);
}, 5000);
I think the easiest way would be to always have the empty result div in your html and just keep it hidden. This way whenever you get a result from the AJAX you can just change the html, show it, then slide it up again.
$("#result").html(AJAX RESULT);
$("#result").show();
setTimeout(function(){
$('#result').slideUp(500);
}, 5000);
This will change the html of the div then show it. Then hide it after 5 seconds.
You can use $.ajax with the success callback option or use .done() method. Example:
$.ajax({
url:"http://someurl/",
success: function(data){ $('#result').html('success').show(); },
error: function(data){ $('#result').html('error').show(); }
}).done(function(){
setTimeout(function(){
$('#result').slideUp(500);
}, 5000);
})
Thing is #result is sometimes dynamically added to DOM, and jQuery functions are usually loaded when document is ready, to solve this issue you must listen to DOM changes. If for some reason you're not using AJAX or need another approach, you could try this:
function hideMsg(){
// Hide dynamically added div
setTimeout(function(){
$('#result').slideUp(500);
}, 5000);
}
// Listen DOM changes
$('.document').bind("DOMSubtreeModified", hideMsg);
In order for this to work, you must change .document by your document wrapper (where your message will be displayed).
jsFiddle example: http://jsfiddle.net/laelitenetwork/GUxgX/
Cheers.

stellar.js not working with dynamically loaded elements via AJAX

I'm using the fantastic Stellar.js (http://markdalgleish.com/projects/stellar.js/) for parallax on a recent project, but I've run into a challenge:
Stellar isn't noticing when I change content via AJAX (in this case loading in new div's from an html file and using jQuery's replaceWith method). So, my new elements have no parallax, even though they have stellar data attributes.
I've tried calling the .stellar function on my window again after the AJAX is complete, but it doesn't do anything.
How can I get Stellar to correctly apply parallax to the new AJAX'd in elements?
I know this question was posted a long time ago has been accepted, but for me the solution above did not work, so I just wanted to share this which worked for me.
After you AJAX call has been successful you can call Stellar's refresh function like so:
$.stellar('refresh');
Here is the full code:
$.ajax({
type: 'GET',
url: ajaxUrl
}).done(function(data) {
$(targetElement).html(data);
$.stellar('refresh');
}).fail(function() {
// Do something else
});
I found that I can run this code in my jQuery AJAX callback and Stellar will then correctly apply parallax to my new AJAX'd in elements:
$(window).data('plugin_stellar').destroy();
$(window).data('plugin_stellar').init();
I know that the topic is old but I want to share the solution that I found, hoping that it will be useful for people who are still searching.
First create the function:
function init () {
$(window).data('plugin_stellar').refresh();
}
jQuery(document).ready(function () {
// Initialise the plugin when the DOM is ready to be acted upon
init();
});
Second insert this line in your Ajax call:
// Reinitialise plugins:
init();

Execute $(document).ready() after $.load(), is that possible or is there an Alternative

I have page with a form and a table (to show results of the saved data using the form).
The form uses ajax to submit the data, data saved and the table should be reloaded afterwards.
The problem is that the table (which is loaded using AJAX($.load)) is loaded after the execution of $(document).ready(). which implies that the table does not have the required functionality.
Is there any approach where i can postpone the execution of $(document).ready() until the AJAX finish its loading, or shall i use a complete different approach like using iframe?
below is an example of my problem:
$(document).ready(function(){
//some code here that needed for the html in table.html e.g. datepicker, chosen, jqueryui, etc
});
<form>
//Inputs with a button to submit using ajax, where the result is displayed using table.php
</form>
<div id="tableOfContent"></div>
<script>
$('#tableOfContent').load("table.php");
</script>
You can do
$('#tableOfContent').load("table.php",function(){
//completed load actions here
});
But you should note that if you load images, they will not be loaded yet. If that is the case, you can make the contents of table.php initially hidden and do the same again inside for $('#tableOfContent img').load(). This would work for 1 image; multiple images is a bit more complicated, but feel free to ask if that is what you are looking for :)
You can delay the ready event using jQuery.holdReady():
$.holdReady(true);
// Do your custom stuff... the document may already be loaded.
$.holdReady(false); // Now the ready event will fire as soon as the DOM is loaded.
See http://api.jquery.com/jQuery.holdReady/
document.ready is called when the HTML of the page has finished loading, there's no two ways about it.
What you can do, however, is use live binding, which will attach handlers to elements that are not yet on the page.
Example:
$(".datepicker").live("click", function() {
$(this).datepicker();
})
Updated for jQuery >1.7 (this is also faster)
$("#tableOfContent").on("click", ".datepicker", function() {
$(this).datepicker();
})
Load the table data from within the ready function and use the complete event of the load() function to call the remainder
$(document).ready(function() {
// click bindings etc ..
$('#tableOfContent').load("table.php",function() {
// things to do once the table is loaded
});
});
load() documentation
$(document).ready() should be used for scripts that should execute, well, when document is ready.
If you need to execute something after an ajax call, you may write everything within a function and call it with the ajax callback.
function what_i_need() {
// bla bla
}
<script>
$('#tableOfContent').load("table.php", {}, what_i_need);//code had syntax error; '{)'
</script>
I'm not sure. Plus, you can call the function when document is ready too.
$(document).ready(function(){
what_i_need();
});

Categories