I am loading a form (depending on the selected option of a dropDownList) with an ajaxcall (which triggers a renderPartial)
The ajaxcall looks like:
$("#dropDownList").change(function() {
var selected = $(this).val();
$.ajax({
url: "index.php?r=item/update&category="+selected,
cache: false,
success: function(html){
$("#inputs").html(html);
}
})
});
The action "update":
public function actionUpdate($category){
$model = new Item;
$this->renderPartial($category, array(
'model'=>$model,
), false, true);
}
The form will be renderd in the div "input" without any problems, but there is still no javascript available for the form. I have already used
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
to prevent, that jquery will be loaded twice. But there is still no js available for my form (jquery.yiiactiveform.js).
Edit: I have checked my firebug, that jquery.yiiactiveform.js will be loaded after the ajaxcall (again?). - If I am using:
Yii::app()->clientScript->scriptMap['jquery.yiiactiveform.js'] = false;
jquery.yiiactiveform.js isnt available anymore, so it shouldnt be loaded twice?
Your problem is mostly with scripts being reloaded. The jQuery mess everything a lot, but other scripts like YiiActiveForm also can mess up with your application. It will be best if you could preload all needed scripts on the page you call ajax and disable scripts on the pages you load with ajax. You might want to look at EUpdateDialog extension (disclaimer: written by me) it might give you some additional ideas.
The extension #Andrew mentioned is NLSClientScript.
Related
Im currently struggling with an AJAX related problem on a website.
The goal is as follows:
There is a "simple" HTML page containing some links and content.
If you click on a link I want to open the file that gets includes with the link (from href) within a new div overlayed to the page. The content from the page is of course loaded with AJAX into the new div (the overlayed one).
Within this new overlayed div I want to add some JS code which in general already works.
The problem anyway is that the DOM elements within the page loaded per AJAX cannot be accessed in a way that is comfortable to work with, in my specific case.
I got following piece of code so far:
$$('.add-exercise').addEvent('click', function(e) {
var request_exercise_add = new Request.HTML({
'method' : 'post',
'url' : e.target.get('href'),
onSuccess : function(responseTree, responseElements, responseHTML, responseJavaScript) {
// i know i can access responseElements here..
}
});
request_exercise_add.send('s=true');
return false;
});
I know I can access the elements returned within responseElements but the logic on the included website is somehow quite complex and therefore it should be
possible to add the JS within the HTML code in the dynamically loaded page.
Notice that the JS also cannot be added to the head section because it would not know the elements that are loaded after the dom-ready event.
have you tried iframe ?
or the website that you are trying to add does not have PPP cookie and AllowContentInIframe .. ?
If you want to add the script inside the ajax request you need evalScripts: true and you should remove the quotes around the request options.
$$('.add-exercise').addEvent('click', function (e) {
var request_exercise_add = new Request.HTML({
method: 'post',
url: e.target.get('href'),
evalScripts: true,
onSuccess: function (responseTree, responseElements, responseHTML, responseJavaScript) {
// i know i can access responseElements here..
}
});
request_exercise_add.send('s=true');
return false;
});
I don't know what is the content of the response but you might also want to use Mootools's .set() instead of innerHTML to append new elements (if you are not doing that yet). Maybe worth to check Dimitar's answer here about that.
I have a cshtml page that has a link, and a div to display some content.
<a href="#" onclick="Show_New_Page('#First_Div')>My Link</a>
<div id="First_Div">
#Html.Partial("General_Page") <- This is the default page that gets displayed on load.
</div>
When you click on the link, the javascript function Show_New_Page gets called and the string '#First_Div' gets passed as a parameter. I pass the name of the div I wish for the ajax in Show_New_Page to put its success value. That function looks like this:
function Show_New_Page(div) {
$.ajax(
{
type: "POST",
url: url, //Declared above globally, unimportant
data: data, //Declared above globally, unimportant
success: function (result) {
$(div).html(result);
}
});
}
When you click on this link in Internet Explorer, the new page gets displayed fine with no issues. However, when you click on this link in FireFox, the entire page turns white and never successfully loads.
There are plenty of posts about issues with Ajax and different browsers, but I was unable to see one that helped me. Any hints or tips I can try are much appreciated. I am very unsure of why this is happening, so if I have left out any information I will certainly do my best to provide it.
There seems to be a missing closing ) when you are calling the Show_New_Page function. Also it's recommended to return false from click handlers to cancel default action:
My Link
Also you might prefer to give this anchor an id:
My Link
and then unobtrusively AJAXify it in a separate file to avoid mixing markup with javascript:
$(function() {
$('#myLink').click(function() {
$.ajax({
type: 'POST',
url: url, //Declared above globally, unimportant
data: data, //Declared above globally, unimportant
context: { id: $(this).data('id') },
success: function (result) {
$(this.id).html(result);
}
});
return false;
});
});
The issue here was the fact that my ajax views that were being passed down after clicking on a link were using document.write() statements. I have learned that this is strange to do after the page has already loaded. I've moved these statements up to the files that were not being loaded with ajax, and that fixed the problem. Thank you to everyone who commented and suggested ideas to me. It was the investigation of these ideas that lead me to the core issue!
The lesson: be careful with excessive document.write() statements in firefox!
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.
Basically, I am trying to load the html and JavaScript file for each subpage on my website with ajax. However, the JavaScript file only loads for the first subpage that is clicked on. If I click on the next subpage, only the html document for that loads, but the javascript does not. This is from looking at the firebug console: Clicking on about first, then clicking on contact:
GET http:..../about.html?t=0.19504348425731444
GET http:..../about.js?t=0.8286968088896364
GET http:..../contact.html?t=0.8467537141462976
(!!!NO GET FOR contact.js!!!)
Anyways, I tried using live() to bind the click event but it still doesn't work.Here's the relevant snippets of my code:
$('.subpage').live('click',function(){
$('#main').css({'cursor':'crosshair'});
navsubpage = true;
subpage = $(this).attr('id');
$('.subpage').each(function(index) {
$('#'+$(this).attr('id')).fadeOut('500');
$('#'+$(this).attr('id')+'select').fadeOut('500');
});
$('#'+subpage+'h').css({'background-color':'#000','display':'block'});
$('#'+subpage+'h').animate({'width':'375px','top':'120px','left':'100px','font-size':'400%'},'500');
subtop = $('#'+subpage+'h').css('top');
subleft = $('#'+subpage+'h').css('left');
$('#pane').css({'border-left-width':'0px'});
$('#nav').css({'background':'url("images/'+$(this).attr('id')+'.jpg") no-repeat 0px 0px'});
$('#nav').animate({'left':'0px'},'4000','swing',function(){
$('#reload').show().delay(500).queue(function(){
alert("made it");
$.ajax({
url: subpage+".js?t=" + Math.random(),
dataType: 'script',
type: 'get',
});
});
});
reload(subpage);
});
$('#main').click(function(){
if(navsubpage==true){
$('#main').css({'cursor':'auto'});
$('#reload').hide();
$('#pane').css({'border-left-width':'10px'});
$('#'+subpage+'h').animate({'width':'150px','top':subtop,'left':subleft,'font-size':'200%'},'2000',function(){
$('#'+subpage+'h').css({'display':'none'})});
$('#nav').animate({'left':'415px'},'3000','swing', function(){
$('.subpage').each(function(index) {
$('#'+$(this).attr('id')).fadeIn('3000');
$('#'+$(this).attr('id')+'select').fadeIn('3000');
});});
navsubpage = false;
}
});
the reload function loads the html and is working correctly.
I am really new to ajax, javascript...etc. If any of you can help me out, that'll be great.
It's confusing that you have both the "?t=" + Math.random() combined with cache: true.
The practice of appending a timestamp to a URL is a common method to prevent caching, but then you explicitly tell it that you want it to cache. You might try removing the cache: true option, as it looks to be totally superfluous and can only cause problems (the likes of which would resemble what you're describing here).
I would reccomend trying out a jQuery ajax shortcut function $.get()
It is farly simple and might cut out a lot of uneccesary options you are setting using the full $.ajax() function
Thanks for the help guys - in the end I just decided to not mess with the queue stuff. I still don't understand why it works, but I just took out the ajax and placed it outside of $('#reload').show().delay(500).queue(function(){, eliminating the delay and queue stuff and making the ajax a separate snippet of code. now it loads correctly.
My site operates on an ajax "framework". Whenever a user opens a new page, that page loads in the necessary css and js files to view the page properly and adds them to the current document. The js files are loaded like this in jQuery:
function getJS(jsfiles) {
$.each(jsfiles, function(i, val) {
$.getScript(val);
});
}
My problem is that whenever a js-file is loaded, that file is added to the document permanently and operates across all ajax "sub-sites". Therefore I get problems with reserved function names, functions that requires certain DOM-elements to be present when executed and throws an error otherwise, etc. etc. Is there a way to remove these files from the document again?
I don't know how jQuery attaches new scripts, but you could do an AJAX request and build your own script elements in the callback, giving them a class that can be selected later for removal.
$.ajax({
url:'test.js',
dataType: 'text',
success: function(script) {
var head = document.getElementsByTagName('head')[0];
var scr_elem = document.createElement('script');
scr_elem.setAttribute("class","new_script");
scr_elem.setAttribute("className","new_script");
scr_elem.type="text/javascript";
scr_elem.appendChild(document.createTextNode(script));
head.appendChild(scr_elem);
}
});
// Later on
$('.new_script').remove();
Note that I've only tested this in Webkit and Firefox.
You could scope the contents of the JavaScript files you are loading, using a self-executing function. Or try assigning an ID to the script-blocks and remove them by doing: $("id of the script block").remove();.
You can try to do something like this
$('head').empty();
$('head').append('<script src="yourscript.js" type="text/javascript" />');
Hope this helps