Ajax request success handler - javascript

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);

Related

JQuery hover state for appended elements

I am writing a page that once loaded will go off and make an ajax call, process the json respose data, and then append these elements into the dom as shown in a simplified way below:
$.ajax({
type: 'POST',
url: "http://mysite.dev:32769/getallnews",
success: function(data){
$container.append(item)
.isotope( 'appended', item );
}
});
It should also be noted I am using Metafizzy's Isotope library. http://isotope.metafizzy.co/
To demonstrate my issue I have a <div class="article-block"></div> both in the DOM at load time and one more appended once the ajax call finishes.
this jquery will only capture the first and not the second though!
$(".article-block").hover(function(){
//hover on
$(".article-block div").fadeIn();
},function(){
//hover off
$(".article-block div").fadeOut();
});
I've spent some time debugging this and found that when I type $('.article-block'); into the console. I get both correctly. However when I hover over my first one the fade works, and when I hover over the second, it doesn't.
Any ideas?
Order matters
You are registering your event handler for the initial div when the page loads which is good. Its important to note that if you add dom elements later you will need to apply handlers to the new items.
Try saving a reference to your handlers and applying it later.
function hoverOn() {
$(".article-block div").fadeIn();
}
function hoverOff() {
$(".article-block div").fadeOut();
}
// on page load
$('.article-block').hover(hoverOn, hoverOff);
// later in the ajax call
$.ajax({
type: 'POST',
url: "http://mysite.dev:32769/getallnews",
success: function (data) {
$(item).hover(hoverOn, hoverOff); // register your hover event to the
// new element
$container.append(item).isotope( 'appended', item );
}
});

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
})

showing "loading..." text - only one jquey.ajaxSend() for all divs in the document

How can I show a "loading..." text ONLY into the div that calls jquery.load().
$(document).ready(function()
{
//only one ajaxSend for all divs
$(document).ajaxSend(function()
{
$(this).html('LOADING...'); //'this' doesn't works
});
//...
$("#ranking-content").load("content/ranking.php");
$("#empleados-content").load("content/empleados.php");
//... more and more
});
Inside the ajaxSend callback, how can I get the div's ID that made that ajax request?
I'm sure that there is a better way than doing one ajaxSend per div.
To customize the behavior for a particular div, use the ajax function:
Define beforeSend (script to run before the ajax call) and context (the HTML element):
$.ajax({
context: $('#ranking-content'),
url: 'content/ranking.php',
beforeSend: function (xhr) {
$(this).html('Loading');
}
}).done(function (data) {
$(this).html(data);
});
Using this ajaxSend isn't needed. You can re-use this code by merging the parameters to ajax with settings supplied by a caller.

How to open an html page in and html div?

The question might be a little misleading as I don't want to know how to open a html document in a div ,but I asked the question as I am currently facing a problem where I can't replace the html file which I have already placed in a div
I have already placed a html file in a div using ajax like this:
$.ajax({
url: 'calender.aspx',//this is html.aspx file
cache: false,
dataType: "html",
success: function (data) {
$(".mainBar").html(data);//mainBar is the div
}
});
this file gets placed on page load i.e document.ready function ,till here everything is fine.....my trouble starts when I want to replace the file,what I do is call a javascript function say replaceFile() on button click and write the same code to replace the file (changing the url of course)
like this
function replaceFile()
{
$.ajax({
url: 'Another.aspx',
cache: false,
dataType: "html",
success: function (data) {
$(".mainBar").html(data);
}
});
}
but this doesn't work,please help me out!
I guess your binding is not working when you try to click on the content you loaded via ajax . So you might want to change the binding of onclick from
$("#someButtonId").click(function(){
replaceFile();
});
to
$(document).on("click","#someButtonId",function(){
replaceFile();
});
jQuery on works with current and future elements.
with this function you will load the page into the element named result
.load( url , data, complete(responseText, textStatus, XMLHttpRequest)] )
function replaceFile(url)
{
$('#result').load(url, function() {
alert('Load was performed.');
});
}
replaceFile('htmlfile.html');
You can load this in Firebug and set a break point at $(".mainBar").html(data); to make sure it's being called. You don't have a failure handler, so it's possible that it's actually receiving an HTTP failure code, not a success code.
I'd also look at the network traffic under the Net tab to see what the request/response looks like. That's an easy way to find out what is really going on with most AJAX calls. IE9 has similar developer tools if you want to use it and not Firefox or Chrome.

Help me make a jquery AJAXed divs' links work like an iframe

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);
}
});
});

Categories

Resources