AJAX appended content does not execute Javascript - javascript

I've seen this problem posted on Stack Overflow couple of times, but the solution I found is usually very old and talks about delegate method which is deprecated.
I am looking for a solution for jQuery 3.x. This is my AJAX call:
$.ajax({
type: "get",
url: "/content",
data: {
name: {{ name }}
},
success: function(data) {
$("#appendsection").append(data);
}
});
Here I am appending the success data to a div called appendsection
This appendsection div does not execute any javascript, it executes CSS, but no javascript and no jquery. I see this problem most of the time, any data I get from ajax call does not want to execute javascript.
This is the appended content
<div class="sortingbuttons">
<select id="sort">
Sort By
<option value="name">Relevance</option>
<option value="price">Cheapest</option>
<option value="recommend">Recommended</option>
</select>
</div>
The #sort id is executed on app.js
$('#sort').change(function(){
$('.section').hide();
$('#' + $(this).val()).show();
});
So, the sorting does not work on the appended content, so the javascript is not working on the appended content.

the solution to your problem is still delegation but not the method delegate.
here is the structure for event delegation in jQuery 1.7+
$( elements ).on( events, selector, data, handler );
try this I hope it will work
$('body').on('change', '#sort', function(){
$('.section').hide();
$('#' + $(this).val()).show(); //do anything
})

I apparently, solved this problem by running the necessary javascript code on the success function
$.ajax({
type: "get",
url: "/content",
data: {
name: {{ name }}
},
success: function(data) {
$("#appendsection").append(data);
//execute necessary javascript after this
$('#sort').change(function(){
$('.section').hide();
$('#' + $(this).val()).show();
});
}
});
This might be one of the ways to delegate the javascript, but I am sure that this is not the best way to do it. But for the moment, this is the only solution that worked for me.

Related

Call event after script in external html loaded by Ajax

I have an Ajax Loaded Div in my page and, inside that div, a Jquery plugin load my Google Spreadsheet. I need to add some "event listening" to detect when that spreadsheet is loaded, but there is a problem with the unpredictable time to load and the fact that a event INSIDE my div (with external html content), as far as I know, can't be listened on my "parent" window. I've tried many ways to do that, by the way.
I'll post my code, but I don't think it can help. What can I say is: The height of my div change when the content is loaded. The Callback function can't work in this case 'cause my script (inside div) only get the spreadsheet after load the page.
index.html
$.ajax({
url : "test/index.html",
type : "get",
async: true,
success : function(result) {
$('.mailcontrol').html(result);
},
error: function() {
alert("Error");
}
});
test/index.html
<script type="text/javascript">
$('#dat').sheetrock({
url: 'https://docs.google.com/spreadsheets/ssid'});
</script>
Any ideia about some event listening in my case? Thanks!
EDIT:
jrummell answer gave me the ideia to ignore the external html file using the plugin inside the same page, so, I could use the callback function of "sheetrock", as suggested by Andre.
Thanks for the answers!!
New code:
$("#target2").click(function () {
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'sheetrock.min.js';
$("#dat").append(script);
$('#dat').sheetrock({
url: 'https://docs.google.com/spreadsheets',
callback: function() {
}
});
});
Try initializing your spreadsheet plugin after the content is loaded:
$.ajax({
url : "test/index.html",
type : "get",
async: true,
success : function(result) {
$('.mailcontrol').html(result);
$('#dat').sheetrock({
url: 'https://docs.google.com/spreadsheets/ssid'});
},
error: function() {
alert("Error");
}
});
You can use Jquery on() event listening, like this:
$('.mailcontrol').on('eventName', '#dat', callbackFunction);
The "selector" parameter is a selector string to filter the descendants of the selected elements that trigger the event. In your case "#dat". I suggest using "resize" as eventName.
Reference: http://api.jquery.com/on/
Have you tried the original sheetrock callback?
$('#dat').sheetrock({
url: 'https://docs.google.com/spreadsheets/ssid',
callback: function() {
//trigger event to be caught
}
});
Reference: https://github.com/chriszarate/sheetrock#callback

how to run javascript code that included through ajax process

I have a php page which has lot's of code of html and javascript inside it.Ihe other page use ajax to send an id to the first page and get the results and put it inside a div element. Now I want to run those returned codes which contains javascript and html codes.
How should that be done?
This is my ajax request to the first page:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "showing.php",
data: "s_id="+s_id+"&submit=true",
success: function(msg){
str=$.trim(msg)
document.getElementById('tabs-2').innerHTML = str;
document.getElementById("ui-id-2").click();
}
})
I think event delegation can solve your problem.
Like below:
Use $.on(). Instead of registering events on the element you register on a parent which will not be removed
Ex:
$('#tabs-2').on('click', '#ui-id-2', function(){
//do something
})

A javascript/jquery function to delete itself after execution

I am sending an ajax request to one of my controller to update the user interaction (which page he visits/likes) for an very insight analytics. I am storing these information in my mongo db.
All I want is, on success of this request, delete this script. But all the alert works, but the script never deletes. The following is my code
<div id="delete_this">
<script>
$(document).ready(function() {
$.ajax({
url: weblink+'user-interactions',
type: 'POST',
dataType: 'html',
data: {
//some post data
},
})
.done(function(html) {
alert("works");
var status = "executed";
alert("works here");
$("#delete_this").remove();
})
.fail(function(html) {
console.log("error");
});
});
</script>
</div>
WHAT I HAVE DONE TILL NOW:
1) tried with adding a div as the parent and pointing to delete that div as shown in script.
2) separated out the .remove() from the script into a new script tag and used something like this.
<script>
$(document).ready(function() {
$("#delete_this").remove();
});
</script>
tried to specify the parentnode and delete the child.
I failed in all three attempts. I am really stuck out here.
Any reasons why it is not working?
I also have another question relating to this.
This link says that the javascript stays in the session till the page is refreshed. So why are'nt we following a standard where we can execute the scripts and delete them
By doing so, we will be able to achieve building a bit more secured webpages. Is'nt it?
You could use plain Javascript to do this (not tested this)
var domNode = document.getElementById('delete_this');
var nodeParent = domNode.parentNode;
nodeParent.removeChild(domNode);
Not sure this is ideal but it should remove it completely from the DOM.
This works :
<button>remove</button>
<script id="test">
$( "button" ).click(function() {
$( "#test" ).remove();
alert("removed " + ($( "#test" ).length == 0));
});
</script>
try it here: http://jsfiddle.net/4ungb/
So either you have a) other errors that prevent that script to complete or b)
your criteria for testing deletion is not correct.

One code to turn all forms into AJAX forms?

So I use the following code to manipulate my 'login' form so that it submits it, to the url of action="" and the data responded goes into id specified by target="". The submit method is specified by method=""
I like this. It's neat. But I was wondering if there was a way of having a script that meant that all forms were submitted through Jquery, without having to re-write this code for every form every time. That's just messy.
Much appreciated!
<script type="text/javascript">
$(document).ready(function(){
$("#login").submit(function(){
var thistarget = this.target;
$(thistarget).html('Submitting...');
jQuery.ajax({
data: $(this).serialize(),
url: this.action,
type: this.method,
error: function() {
$(thistarget).html("Form failed to submit");
},
success: function(results) {
$(thistarget).html(results);
}
})
return false;
}
);
});
</script>
Sure, just replace "#login" with "form". It will then affect all forms that currently exist on the page (but not future forms).
$("#login").submit(function(){...
For future forms AND current forms, you would need event delegation.
$(document).on("submit","form",function(){...
If I were you I'd use the $.post method of Jquery. http://api.jquery.com/jQuery.post/
But answering your question and as Kevin B said: change #login by form

Replace the content of a div several times

I have a select with my servers and I load information on the selected server without reloading the page. I am using ajax and ReplaceWith().
I tried using live() to replace the information several times, but it only works once, why?
<script>
$(function(){
$('select').live('change', function(){
$.ajax({
type: "POST",
url: "server.php",
data: "hostname=" + $(this).val(),
success: function(data){
$("#results").replaceWith(data);
}
})
});
});
</script>
It is because you are replacing the #results container with the data. The next time the $("#results") selector will not match any elements (because the container was replaced by the previous call).
.html() does not replace the container, but updates the content of the container.
I do not really understand why it works with html() and not with ReplaceWith(), but it works!
<script>
$(function(){
$('select').live('change', function(){
$.ajax({
type: "POST",
url: "serveur.php",
data: "hostname=" + $(this).val(),
success: function(data){
$("#results").html(data);
}
})
});
});
</script>
Sorry to answer my own question.
live() method is kind of deprecated and might work not properly. Try on() instead of.

Categories

Resources