jquery ui dialogue not working with AJAX content - ajax

I am loading AJAX content into jquery UI dialogue by clicking on a link, but it doesn't seem to work. Problem is with the popup, the link returns ajax content fine. Trying to implement this example
$.fx.speeds._default = 1000;
$(document).ready(function(){
$( "#dialog" ).dialog({
autoOpen: false,
show: "blind",
hide: "explode"
});
$('#<url_id>').live('click', function(evt) {
//evt.preventDefault();
$.ajaxSetup({
async: false,
"error":function() {
alert("error");
}});
$.getJSON("<url>",
function(data) {
if(data[0][0] != null){
var html = '';
html += '<div id="dialog" title="Basic dialog">';
//concatenating html
html += '</div>';
}
});
$( "#dialog" ).dialog( "open" );
return false;
});
});

You havent added the element with that ID to the page yet, so your selector gets no results. You need to do something like this:
var element = $(html);
$('body').append(element);
$('#dialog').dialog();
Also:
You really shouldnt set ajax defaults on every click event (it's a global setting). If you need to specify additional parameters that $.getJSON doesnt provide, you should just call $.ajax directly.

Related

Ajax function call not working second time

Need help to resolve ajax call issue
In my view page ( working on codeigniter), there is a dropdown and a div
section. Based on dropdown value, data will get change in div section. I am
using ajax call ( to call method in controller) to upload data in div tag on
dropdown change event. Ajax call working fine on first change event of
dropdown but when i select value for second time in dropdown, ajax function
call is not working ( second select and so on).
My code is:
VIEW PAGE =>
$(document).ready(function() {
$("body").on('change','#assettype_id',function(e){ // "assettype_id" is
dropdown id
//e.preventDefault();
var categoryval = $('#assettype_id :selected').val();
$.ajax({
type: 'POST',
cache: false,
url: 'http://my_path/index.php/assetcontroller/assignpc/'+ categoryval, // Based on "categoryval" data will change in div tag
dataType: 'html',
success: function(data) {
$( "#result" ).load( "http://my_path/index.php/assetcontroller/assignpc/"+ categoryval); // "result" is div tag id
$( "#result" ).html(categoryval);
},
});
return false;
});
});
Why ajax call is not working in dropdown 'second time' change event?
You need to wrap the .on('change') event into a function, so it can be called anytime later.
That's because once you have added new html output through Ajax, this html doesn't yet know about your change event!
So the function my_change_event() needs to be re-called, once your Ajax output has been added to DOM with your $( "#result" ).load()
something like this:
$(document).ready(function() {
my_change_event();
});
function my_change_event(){
$( "#assettype_id" ).on( "change", function() {
$.ajax({
type: 'POST',
cache: false,
url: your_url,
success: function(data) {
// do something with data
// html output
my_change_event();
}
});
}

jQuery UI Ajax Tabs Loading not showing

I'm using jQuery UI Vertical Tabs and the content is loaded via AJAX. I tried almost everything from posts around here, and nothing helped me so far .. :/
I want to display a css3 loading animation placed in <div id="loading-image">...</div>. So far almost nothing is happening.
My code
$(function() {
$( "#messages_tabs_div" ).tabs({
beforeLoad: function( event, ui ) {
console.log(ui);
ui.jqXHR.error(function() {
ui.panel.html("Couldn't load your messages. Try refreshing your page."+
" If you think this is bug you can help us by submitting it at bugs#go-out-sport.com " );
});
ui.jqXHR.complete(function(response){
console.log(response);
});
},
disabled: [6],
select: function(event, ui) {
alert('ASDAD');
}
}).addClass( "ui-tabs-vertical ui-helper-clearfix" );
$( "#messages_tabs_div li" ).removeClass( "ui-corner-top" ).addClass( "ui-corner-left" );
});
//jQuery MINE
$(document).ready(function(){
$('#loading-image').hide();
//Set loading bar for all ajax requests
$('#loading-image').bind('ajaxStart', function(){
alert('AJAXXX');
$(this).show();
}).bind('ajaxStop', function(){
$(this).hide();
});
$('#loading-image').bind('tabsselect', function(event, ui) {
alert('TABSSSSS');
$(this).show();
}).bind('tabsload', function(event, ui) {
$(this).hide();
});
});
The only thing I get is the AJAX alert. I tried removing $('#loading-image').hide(); and the loading was always there.
Please help ....
Thank you in advance
I recommend to use a global ajax loading..
$(document).ajaxStart(function() {
$("#loading").fadeIn(200);
}).ajaxStop(function() {
$("#loading").fadeOut(300);
}).ajaxSuccess(function() {
});
but, if you want personalize for multiple events, see this questions:
How to call .ajaxStart() on specific ajax calls
jQuery should I use multiple ajaxStart/ajaxStop handling

AJAX avoid repeated code

I'm using Symfony2.1 with Doctrine2.1
I'd like to use AJAX for many features on my site , editing a title , rate an article , create an entity on the fly , etc.
My question is simple :
Do I need to create a JQuery function for each functionnality , like this :
$('#specific-functionality').bind('click', function(e){
var element = $(this);
e.preventDefault();
// the call
$.ajax({
url: element.attr('href'),
cache: false,
dataType: 'json',
success: function(data){
// some custom stuff : remove a loader , show some value, change some css
}
});
});
It sounds very heavy to me, so I was wondering if there's any framework on JS side, or a specific method I can use to avoid this. I was thinking about regrouping items by type of response (html_content , boolean, integer) but maybe something already exists to handle it nicely !
From what I understand, you are asking for lighter version of JQuery ajax method. There are direct get/post methods instead of using ajax.
$.get(element.attr('href'), {'id': '123'},
function(data) {
alert(data);
}
);
To configure error function
$.get(element.attr('href'), {'id': '123'}, function(data) {alert(data);})
.error(function (XMLHttpRequest, textStatus, errorThrown) {
var msg = jQuery.parseJSON(XMLHttpRequest.responseText);
alert(msg.Message);
});
Also, you can pass callback function to do any synchronous operations like
function LoadData(cb)
{
$.get(element.attr('href'), { 'test': test }, cb);
}
And call
LoadData(function(data) {
alert(data);
otherstatements;
});
For progress bar, you use JQuery ajaxStart and ajaxStop functions instead of manually hiding and showing it. Note, it gets fired for every JQuery AJAX operation on the page.
$('#progress')
.ajaxStart(function () {
//disable the submit button
$(this).show();
})
.ajaxStop(function () {
//enable the button
$(this).hide();
});
Instead of $('#specific-functionality').bind('click', function(e){, try this:
$(".ajax").click(function(){
var url = $(this).attr("href") ;
var target = $(this).attr("data-target") ;
if (target=="undefined"){
alert("You forgot the target");
return false ;
}
$.ajax(....
And in html
<a class="ajax" href="..." data-target="#some_id">click here </a>
I think it is the simplest solution. If you want some link to work via ajax, just give it class "ajax" and put data-target to where it should output results. All custom stuff could be placed in these data-something properties.

Render 'like' button after ajax call

there were a few question similar to mine on the stack but none that answered my question, so...
An ajax call returns the standard html code for creating the like button:
<div class="fb-like" data-href="http://www.website.com" data-send="true" data-width="450" data-show-faces="true"></div>
This html does show up in the source when looked at with 'inspect element', but it is not rendered, i.e. the space where the button should be is blank. Is there some rendering function that I should be using?
Any hints would be greatly appreciated!
EDIT: Here's the ajax request and parseing - the 'like' button is put in '#thequestion' along with some other text (it is echoed from question.php).
$("#thequestion").load("/thought/question.php", { ans: choice, id: questionId } );
$("#graph").load("/thought/graph.php", { id: questionId } );
$("#fbCommentsPlaceholder").html("<div class='fb-comments' data-href='http://qanai.com/thought/#" + questionId + "' data-num-posts='2' data-width='470'></div>");
FB.XFBML.parse();
eval(document.getElementById('thequestion').innerHTML);
eval(document.getElementById('graph').innerHTML);
(I know eval is evil)
EDIT 2: The like button appears if FB.XFBML.parse(); is executed manually (in the console) after the ajax call.
Thanks
You have to call FB.XFBML.parse(); after the ajax call.
Documentation: https://developers.facebook.com/docs/reference/javascript/FB.XFBML.parse/
Edit: now I see that you're trying to load content into $('#thequestion'). .load takes a callback that runs after the request completes. You should do something like:
$('#thequestion').load('/my/url', { my: 'params' }, function() {
FB.XFBML.parse();
});
Documentation: http://api.jquery.com/load/
Not sure anyone needs it, but my complete code looks like this now and renders both FB page and Like button appropriatelly (LikeLink button created with material icon):
<i id="LikeLink" class="material-icons actionButton"></i>
var fbloaded = false; // if SDK is loaded, no need to do it again (though cache should do this?
var fbpageid = "myPageId"; // FB page id
// ajax call to FB SDK script
if (!fbloaded) {
$.ajax({
type: "GET",
url: "//connect.facebook.net/en_US/sdk.js",
dataType: "script",
cache: true,
success: function () {
fbloaded = true;
FB.init({
appId: '{myAppId}',
version: 'v2.3' // or v2.0, v2.1, v2.0
});
// parse button after success
FB.XFBML.parse();
}
});
}
var FBDivAppended = false; // if already done, do not call and render again
PostUrl = window.location.href; // like button needs this... or not :)
// when LikeLink is clicked, add the divs needed and at the end fire the FB script ajax call (resetFB)
$("#LikeLink").click(function () {
if (!FBDivAppended) {
var $pagediv = $("<div class=\"fb-page\" data-href=\"https://www.facebook.com/" + fbpageid + "\" />");
var $fblikediv = $("<div class=\"fb-like\" data-href=\"" + PostUrl + "\" />");
var $fbdiv = $("<div id=\"fbDiv\" />");
var $fbroot = $("<div id=\"fb-root\" />");
$fbdiv.append($pagediv).append($fblikediv);
$(".Header").append($fbdiv).append($fbroot);
FBDivAppended = true;
}
resetFB();
}

Ajaxify hyperlink so on success will load content otherwise redirect as default

I have a <a href> hyperlink. I used JQuery so clicking the link will load contents into a div in the current page (i.e. stay in the same page), and it works now.
However I also want that, if the request fails, the link act normally and go to the href url.
I tried e.preventDefault(); and return false; in the success: callback function, but they are not in the correct scope. If I place e.preventDefault() in the calling function, I can't reverse that effect later.
Here is my code:
$('a.more-link').click(function(e){
var postId=$(this).closest('div.post').attr("id").replace(/^post-(.*)$/,'$1');
var postContent=$(this).parent();
$.ajax({
url:"?action=ajax_load_post&id="+postId,
success:function(data){
postContent.html(data);
// Can't access e.preventDefault, nor return false;
},
error:function(data){
}
});
e.preventDefault();
});
Don't worry about the preventDefault(), just redirect the user in the error function like this:
$('a.more-link').click(function(e){
var postId=$(this).closest('div.post').attr("id").replace(/^post-(.*)$/,'$1');
var postContent=$(this).parent();
var _this = $(this);
$.ajax({
url:"?action=ajax_load_post&id="+postId,
success:function(data){
postContent.html(data);
},
error:function(data){
window.location = _this.attr('href');
return false;
}
});
});

Resources