How can I make an AJAX link work once it is moved out of the iFrame? - ajax

I am using an iFrame with a form that return some content with an AJAX link.
I am then moving the returned content out of the iFrame into the main page.
However, then the ajax link does not work and the error "Element is null" is created once the link is clicked.
How can I move content from the iFrame and still have the AJAX link working?
Here's the code returned by the iFrame:
<span id="top">
<a id="link8" onclick=" event.returnValue = false; return false;" href="/item_pictures/delete/7">
<img src="/img/delete.bmp"/>
</a>
<script type="text/javascript">
parent.Event.observe('link8', 'click', function(event) {
new Ajax.Updater('top','/item_pictures/delete/3', {
asynchronous:true, evalScripts:true,
onCreate:function(request, xhr) {
document.getElementById("top").innerHTML = "<img src=\"/img/spinner_small.gif\">";
},
requestHeaders:['X-Update', 'top']
})
}, false);
</script>
</span>

I see two problems with your code.
First the solution (I think :-))
When your iframe loads, the javascript in it runs. Javascript attaches an observer to parent document's link8.
Inside the observer you define another function (onCreate). This function will run in iframe context, making document object refer to iframe and not to main document. When you remove link8 from iframe to move it to main document, document.getElementById("top") will become null - hence error.
Perhaps change it to:
parent.document.getElementById("top").innerHTML = "<img src=\"/img/spinner_small.gif\">";
Second problem (that is not really a problem in this particular case) is, if you move whole span (including the script) to main document, the javascript will run again in main document's context. In your case, you should see an error or warning after you move the content, stating that parent is null (or similar).
To remove the second problem, return your iframe data in two divs or similar. Then copy only div with html to main document.

What I did was move the AJAX call out to an external js file and called the function once the link was clicked. It works now.

Related

Calling ajax function from another js script

I have a ajax function that is called by button tag
<button id="of_save" type="button" class="button-primary">
<?php echo __('Save All Changes', 'optionsframework');?>
</button>
$('#of_save').live('click',function() {
...
...
...
}};
The problem is that theme author put a single button on top of settings page and a million of settings, so every time I want to hit save, I must scroll whole page.
I found a little JS script that intercept CTRL+S or another browser combination and is working wonderful
http://www.openjs.com/scripts/events/keyboard_shortcuts
The problem is I don't know how to call the ajax function from this JS
shortcut.add("Ctrl+Shift+X",function() {
alert("Hi there!");
// not working...
live('click',function());
});

How can I change the style of a div on return from a form submit action in Razor MVC3?

I have a Razor/ASP/MVC3 web application with a form and a Submit button, which results in some action on the server and then posts back to the form. There is often some delay, and it's important that users know they should wait for it to complete and confirm before closing the page or doing other things on the site, because it seems users are doing that and sometimes their work has not been processed when they assume it has.
So, I added a "Saving, Please Wait..." spinner in a hidden Div that becomes visible when they press the Submit button, which works very nicely, but I haven't been able to find a way to get the Div re-hidden when the action is complete.
My spinner Div is:
<div id="hahuloading" runat="server">
<div id="hahuloadingcontent">
<p id="hahuloadingspinner">
Saving, Please Wait...<br />
<img src="../../Content/Images/progSpin.gif" />
</p>
</div>
</div>
Its CSS is:
#hahuloading
{
display:none;
background:rgba(255,255,255,0.8);
z-index:1000;
}
I get the "please wait" spinner to appear in a JS method for the visible button, which calls the actual submit button like this:
$(document).ready(function () {
$("#submitVisibleButton").click(function () {
$(this).prop('disabled', true);
$("#myUserMessage").html("Saving...");
$("#myUserMessage").show();
$("#hahuloading").show();
document.getElementById("submitHiddenButton").click();
});
});
And my view model code gets called, does things, and returns a string which sets the usermessage content which shows up fine, but when I tried doing some code in examples I saw such as:
// Re-hide the spinner:
Response.write (hahuloading.Attributes.Add("style", "visibility:hiddden"));
It tells me "hahuloading does not exist in the current context".
Is there some way I am supposed to define a variable in the view model which will correspond to the Div in a way that I can set its visibility back from the server's action handler?
Or, can I make the div display conditional on some value, in a way that will work when the page returns from the action?
Or, in any way, could anyone help me figure out how to get my div re-hidden after the server action completes?
Thanks!
Is this done with ajax? I would assume so because the page is not being redirected. Try this:
$(document).ready(function () {
$("#submitVisibleButton").click(function () {
$(this).prop('disabled', true);
$("#myUserMessage").html("Saving...");
$("#myUserMessage").show();
$("#hahuloading").show();
document.getElementById("submitHiddenButton").click();
});
$("#hahuloading").ajaxStop(function () {
$(this).hide();
});
});
As an aside, you no longer need runat=server.

save ajax response to a element that was not on the DOM

I have some results on the page (firts 10), then with a "load more result" button, I send the "id" of the last report to a PHP page.
I'v read here that I have to use .on (because .live is depreciated) so click event on new elements added to the DOM (through AJAX) can work.
My question is ... can I display somehow the content that came through AJAX on a div that was not on the initial DOM ?
$("#jokesWrap").on('click', 'a.share', function(event) {
var joke_id = $(this).attr('name');
var msgbox = $("#success[name='" + joke_id + "']");
$("#post-to-wall[name='" + joke_id + "']").hide();
msgbox.html('<img src="includes/images/load.gif"> Loading...');
$.ajax(
{
type: "POST",
url: "includes/php/ajax.php",
data: "joke_id=" + joke_id,
success: function(msg)
{
if(msg == 'OK')
{
msgbox.html('<img src="includes/images/success.png" /> DONE!');
}
} // function(msg)
}); // ajax
event.preventDefault(); });
This is the HTML part:
<div id="jokesWrap">
<div class="joke" id="1">
<p class="txt">
some text
</p>
<div class="joke-options-bar">
Post to wall
<span id="success" name="1" class="share floatL"></span>
<br class="floatClear" />
</div>
</div>
// the above area comes through loop from the ajax call
PS: Everything is ok: the ajax call (The tetxt is posted to the wall) the #post-to-wall is hidden. The "loding..." and the success message it's not shown.
PS2: the "Loading..." text and success message it's shown when I click on link that was on the DOM before the AJAX call ( because the #success was there)
Any help it's apprecied!
As long as the element exists in the DOM when the success callback of the AJAX is executed, you can use jQuery to select and manipulate it in the same way as you would an element that did exist in the DOM when the page was initially loaded. Or you can use jQuery to create the element as part of the success callback, manipulate it using the response from the AJAX request, then append your newly created element to the DOM in the required position. Something like so:
var div = $('<div/>').attr('id', 'new-div-id').html(data);
$('body').append(div);
That creates a new div, gives it an id of new-div-id, then sets its innerHTML to be whatever data was (assuming data is the name of the variable that contains the response text from the AJAX), then finally appends it as a new child of the <body> tag of the page.
Looking at what seem to be edits to the question: Element IDs (specified with the id attribute) have to be unique throughout the entire document; that includes elements added later as part of an AJAX callback. You can't have multiple elements with an id of success - make them unique by doing away with the name attribute, and adding the value to the end of the id instead, so you'd have success1, success2, etc as your IDs.
Add it to the DOM before writing to it?

Reloading everything but one div on a web page

I'm trying to set up a basic web page, and it has a small music player on it (niftyPlayer). The people I'm doing this for want the player in the footer, and to continue playing through a song when the user navigates to a different part of the site.
Is there anyway I can do this without using frames? There are some tutorials around on changing part of a page using ajax and innerHTML, but I'm having trouble wrapping my head aroung getting everything BUT the music player to reload.
Thank you in advance,
--Adam
Wrap the content in a div, and wrap the player in a separate div. Load the content into the content div.
You'd have something like this:
<div id='content'>
</div>
<div id='player'>
</div>
If you're using a framework, this is easy: $('#content').html(newContent).
EDIT:
This syntax works with jQuery and ender.js. I prefer ender, but to each his own. I think MooTools is similar, but it's been a while since I used it.
Code for the ajax:
$.ajax({
'method': 'get',
'url': '/newContentUrl',
'success': function (data) {
// do something with the data here
}
});
You might need to declare what type of data you're expecting. I usually send json and then create the DOM elements in the browser.
EDIT:
You didn't mention your webserver/server-side scripting language, so I can't give any code examples for the server-side stuff. It's pretty simple most of time. You just need to decide on a format (again, I highly recommend JSON, as it's native to JS).
I suppose what you could do is have to div's.. one for your footer with the player in it and one with everything else; lets call it the 'container', both of course within your body. Then upon navigating in the site, just have the click reload the page's content within the container with a ajax call:
$('a').click(function(){
var page = $(this).attr('page');
// Using the href attribute will make the page reload, so just make a custom one named 'page'
$('#container').load(page);
});
HTML
<a page="page.php">Test</a>
The problem you then face though, is that you wouldnt really be reloading a page, so the URL also doesnt get update; but you can also fix this with some javascript, and use hashtags to load specific content in the container.
Use jQuery like this:
<script>
$("#generate").click(function(){
$("#content").load("script.php");
});
</script>
<div id="content">Content</div>
<input type="submit" id="generate" value="Generate!">
<div id="player">...player code...</div>
What you're looking for is called the 'single page interface' pattern. It's pretty common among sites like Facebook, where things like chat are required to be persistent across various pages. To be honest, it's kind of hard to program something like this yourself - so I would recommend standing on top of an existing framework that does some of the leg work for you. I've had success using backbone.js with this pattern:
http://andyet.net/blog/2010/oct/29/building-a-single-page-app-with-backbonejs-undersc/
You can reload desired DIVs via jQuery.ajax() and JSON:
For example:
index.php
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="ajax.js"></script>
<a href='one.php' class='ajax'>Page 1</a>
<a href='two.php' class='ajax'>Page 2</a>
<div id='player'>Player Code</div>
<div id='workspace'>workspace</div>
one.php
<?php
$arr = array ( "workspace" => "This is Page 1" );
echo json_encode($arr);
?>
two.php
<?php
$arr = array( 'workspace' => "This is Page 2" );
echo json_encode($arr);
?>
ajax.js
jQuery(document).ready(function(){
jQuery('.ajax').click(function(event) {
event.preventDefault();
// load the href attribute of the link that was clicked
jQuery.getJSON(this.href, function(snippets) {
for(var id in snippets) {
// updated to deal with any type of HTML
jQuery('#' + id).html(snippets[id]);
}
});
});
});

jquery ajax post callback - manipulation stops after the "third" call

EDIT: The problem is not related to Boxy, I've run into the same issue when I've used JQuery 's load method.
EDIT 2: When I take out link.remove() from inside the ajax callback and place it before ajax load, the problem is no more. Are there restrictions for manipulating elements inside an ajax callback function.
I am using JQuery with Boxy plugin.
When the 'Flag' link on the page is clicked, a Boxy modal pops-up and loads a form via ajax. When the user submits the form, the link (<a> tag) is removed and a new one is created from the ajax response. This mechanism works for, well, 3 times! After the 3rd, the callback function just does not remove/replace/append (tested several variations of manipulation) the element.
The only hint I have is that after the 3rd call, the parent of the link becomes non-selectable. However I can't make anything of this.
Sorry if this is a very trivial issue, I have no experience in client-side programming.
The relevant html is below:
<div class="flag-link">
<img class="flag-img" style="width: 16px; visibility: hidden;" src="/static/images/flag.png" alt=""/>
<a class="unflagged" href="/i/flag/showform/9/1/?next=/users/1/ozgurisil">Flag</a>
</div>
Here is the relevant js code:
$(document).ready(function() {
$('div.flag-link a.unflagged').live('click', function(e){
doFlag(e);
return false;
});
...
});
function doFlag(e) {
var link = $(e.target);
var url = link.attr('href');
Boxy.load(url, {title:'Inappropriate Content', unloadOnHide:true, cache:false, behaviours: function(r) {
$("#flag-form").live("submit", function(){
var post_url = $("#flag-form").attr('action');
boxy = Boxy.get(this);
boxy.hideAndUnload();
$.post(post_url, $("#flag-form").serialize(), function(data){
par = link.parent();
par.append(data);
alert (par.attr('class')); //BECOMES UNDEFINED AT THE 3RD CALL!!
par.children('img.flag-img').css('visibility', 'visible');
link.remove();
});
return false;
});
}});
}
Old and late reply, but.. I found this while googling for my answer, so.. :)
I think this is a problem with the "notmodified" error being thrown, because you return the same Ajax data.
It seems that this is happening even if the "ifModified" option is set to false (which is also the default).
Returning the same Ajax data three times will cause issues for me (jQuery 1.4). Making the data unique (just adding time/random number in the response) removes the problem.
I don't know if this is a browser (Firefox), jQuery or server (Apache) issue though..
I have had the same problem, I could not run javascript after I call boxy. So I put all my javascript code in afterShow:function one of boxy attributes. I can run almost except submit my form. My be my way can give you something.

Resources