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.
Related
I have the following code: There are 18 listelements which I want to click on. After I clicked on all of them, I need a modal to pop-up. If a do this way, it wont work, it works only on the 19th click
listPoints.each(function(i){
$(this).attr('id', "list-point-" + i);
$(this).click(function(){
addPoint("list-point-" + i);
if (checkPoints()) {
$.ajax({
type: 'GET',
url: 'modal.html',
dataType: 'html',
success: function(html){
$("body").append(html);
}
});
$('#exampleModal').modal();
}
});
});
However if I put the modal show part in the ajax success part, without changing anything else, it works, the modal shows on the 18th, the last click, which is exactly I wanted
listPoints.each(function(i){
$(this).attr('id', "list-point-" + i);
$(this).click(function(){
addPoint("list-point-" + i);
if (checkPoints()) {
$.ajax({
type: 'GET',
url: 'modal.html',
dataType: 'html',
success: function(html){
$("body").append(html);
$('#exampleModal').modal();
}
});
}
});
});
I can't realize the difference. Why is one working while the other isn't?
#exampleModal might be coming from html you are getting in succes.
From your first code :-
As $('#exampleModal').modal(); is executed before the ajax success and hence it might not find that element.
You are iterating through list item and $('#exampleModal').modal(); is repeating in all iteration however compiler will attach the modal to the last item only as id cannot be duplicate.
But in second scenario, id ("exampleModal") is not executed initially by the compiler because ajax will be executed by browser and success part will be executed in later part.so whenever you click list item, it gets attach to that list item.
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.
I have a json implemented page where I am displaying a list of videos. I am getting the video <embed> codes as a javascript. While in the loop of creating the list, I use the $.ajax jquery function to initialize the javascript to get teh video flash player. but the problem is that the player is not getting appended to the supposed <div>. Instead it gets appended at teh end of the document.
$.ajax({
url: item.ImagePath,
dataType: "script",
success: function(data){
alert(data);
var sResultFigure = $(document.createElement('figure')).append(result);
}
})
how do i solve this thing?
Well, you have to append it to the supposed div, like this:
var sResultFigure = $('<figure></figure>').append(result);
$('#supposedDiv').append(sResultFigure);
Assuming you are looping over divs and triggering an AJAX request for each div you could use the context parameter of the AJAX call to provide the current div to the success handler:
$('div.foo').each(function(index, div) {
$.ajax({
url: item.ImagePath,
dataType: 'script',
context: div,
success: function(data) {
// here $(this) points to the div over which we were looping
// when we triggered the AJAX request
$(this).append($('<figure/>').append(result));
}
});
});
i assume your div's id is "holder".
var sResultFigure = $("<figure></figure>").append(result);
$('#holder').append(sResultFigure);
I want to make a few divs on the same page work similar to iframes. Each will load a URL which contains links. When you click on those links I want an AJAX request to go out and replace the div's html with new html from the page of the clicked link. It will be very similar to surfing a page inside an iframe.
Here is my code to initially load the divs (this code works):
onload:
$.ajax({
url: "http://www.foo.com/videos.php",
cache: false,
success: function(html){
$("#HowToVideos").replaceWith(html);
}
});
$.ajax({
url: "http://www.foo.com/projects.php",
cache: false,
success: function(html){
$("#HowToProjects").replaceWith(html);
}
});
This is a sample of code that I'm not quite sure how to implement but explains the concept. Could I get some help with some selectors(surround in ?'s) and or let me know what is the correct way of doing this? I also want to display a loading icon, which I need to know where the right place to place the function is.
$(".ajaxarea a").click(function(){
var linksURL = this.href; //
var ParentingAjaxArea = $(this).closest(".ajaxarea");;
$.ajax({
url: linksURL,
cache: false,
success: function(html){
$(ParentingAjaxArea).replaceWith(html);
}
});
return false;
});
$(".ajaxarea").ajaxStart(function(){
// show loading icon
});
Assuming you want to listen to click events for all anchor tags inside all elements with class ajaxarea, then your selector works fine:
$(".ajaxarea a").click(function(){ .. });
And this line of code, while not a selector (you're just accessing a property on the DOM element that was clicked), should work fine as well:
var linksUrl = this.href;
As for ParentingAjaxArea, you'll need to use $(this).closest() with a selector to determine which parent you want, but it's hard to give a specific example without knowing your HTML structure. It looks like you want ParentingAjaxArea to be either the element with id #HowToProjects or #HowToVideos, so you could write:
var ParentingAjaxArea = $(this).closest("#HowToProjects, #HowToVideos");
As for the loading dialog, I think this answer explains a good method (using ajaxStart and ajaxStop).
Edit: I also noticed you're using the click event--If you plan on being able to attach event handlers to links that will be inserted into the DOM via AJAX later, look at delegate or live.
$(".ajaxarea a").live('click',function(e){
e.preventDefault(); //*
var URL = $(this).attr('href');
var parentFrame = $(this).parent(".ajaxarea"); //**
$.ajax({
url: URL,
cache: false,
success: function(html){
parentFrame.replaceWith(html); //***
}
});
});
* - added preventDefault to prevent click action (see e in function's arguments)
** - instead of closest, i used parent – like it more for it's descriptive qualities
*** - the var containing parent AJAX frame should be jQuery object, no need to wrap it in $(..)
This should work fine, but beware, it's untested.
edit:
You probably need a live (okay, I'm sure you need it). what click() does it's that it adds to all elements at the time in DOM an onClick event. What live() does, it's that it waits for any change in DOM and runs used selector (.ajaxarea a) again and if it fits for any of new elements, it adds the action. In pseudocode, it does basically this:
DOM.hasChanged{
$('selector').click(..)
}
I used this example for my own web page:
http://www.queness.com/post/328/a-simple-ajax-driven-website-with-jqueryphp
It works quite well and uses hash tags and jQuery.history.js for the history of your browser. It works very nice, because you can let something like a media player just continue playing. Take a look at my own site elsewise, where you can find the javascript file: ajaxpages.js. I haven't used live(), but maybe I should.
Figured it out! The problem was I was using the function ".replacewith()" which was removing my AJAXed div(class="ajaxarea") entirely instead of replacing the content. The proper function to use here was ".html()".
Here is my working code to make an AJAXed div work like an iframe:
//onload to initialize the div
$.ajax({
url: "http://www.foo.com/projects.php",
cache: false,
success: function(html){
$('#HowToProjects').html(html);
}
});
$(".ajaxarea a").live('click',function(e){ // must use live instead of .click()
e.preventDefault();
var URL = $(this).attr('href');
var parentFrame = $(this).closest(".ajaxarea");
$.ajax({
url: URL,
cache: false,
success: function(html){
parentFrame.html(html);
}
});
});
I have several javascripts at the head of my document, as well as at the bottom, near the body closing tag. I use jQuery to call an ajax element into place and the elements that are called, require these javascripts to function. How can I include these javascripts to work with the ajax call?
Example:
jQuery(document).ready(function(){
jQuery("a[rel=VideoPreview1]").click(function(){
jQuery("a[rel=VideoPreview1]").hide();
jQuery("a[rel=HideVideoPreview1]").show();
jQuery.ajax({
type: "POST",
url: "/Classes/Video.php",
data: "action=getYoutubeVideos&artist=B.o.B&track=Nothin On You",
success: function(data){
jQuery("#VideoPreview1").html(data);
}
});
jQuery("#VideoPreview1").show();
preventDefault();
});
jQuery("a[rel=HideVideoPreview1]").click(function(){
jQuery("a[rel=VideoPreview1]").show();
jQuery("a[rel=HideVideoPreview1]").hide();
jQuery("#VideoPreview1").hide();
preventDefault();
});
});
So that ajax function loads the content inside of the proper DIV element. The head contains the core files (i.e. jquery, tooltip, lightbox) and near the bottom of the code, the javascripts are referenced (i.e. load.tooltip(VideoPreview1))
Hope this is enough information now
Ok here is what I ended up doing:
<script>
function BottomVideoPlayer(){
// MY JAVASCRIPT HERE
}
jQuery(document).ready(function(){
init: BottomVideoPlayer();
});
</script>
And then when I want to call it into Ajax:
<script>
jQuery.ajax({
type: "POST",
url: "/Classes/Video.php",
data: "action=getYoutubeVideos&artist='.$Artist.'&track='.$Track.'",
success: function(data){
jQuery("#VideoPreview'.$SongID.'").html(data);
init: BottomVideoPlayer();
}
});
</script>
Just wrapped my script around a function and initiate the function whenever I need it.