Javascript doesn't affect html code added with javascript - javascript

I'm using jquery and uploadify to upload photos to server. After uploading photos they are added to a div container using ajax. Everything works great except DELETE button. All delete buttons work on page load but those added via ajax don't work. I suppose that's because I defined function that enables image deletion and didn't use 'classic' way of deleting (form deletion):
// Delete photo
$(".blog_slike .delete_slika").click(function() {
var commentContainer = $(this).parent().parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "./include/ajax-edit/delete.php?polje=blog_slika",
data: string,
cache: false,
success: function(){
commentContainer.fadeOut("slow");
$('#load').fadeOut();
}
});
return false;
});
Any idea how to make button work after it's added to html code using append() function?
One more thing... to add photos to tinymce editor I use this function:
Ubaci sve slike u blog
...which was also added on page load. How can I add content to place where is $slike_u_sadrzaj located and how to delete it?
Thanks,
Ile

You need the jquery live method.
Added in jQuery 1.3: Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.
jQuery documentation
Sample code:
$(".blog_slike .delete_slika").live('click',function() {

Related

Attach jquery events to dynamically created elements (jquery load php file)

I have a php employee directory website that lists all our employees in a table (connected to mysql), and you are able to click each employee to open up their details in another div.
$('.emptab').click(function(event) {
var status = $(this).attr('id');
$("#empview").load("employee.php", {'data': datastring, 'current': status});
});
I originally had the above code, but needed to be able to attach events to dynamic elements, so I changed to the following code:
$('tbody').on('click', 'tr.emptab', function() {
var status = $(this).attr('id');
$("#employeedetails").load("employee.php", {'data': datastring, 'current': status});
});
I did it that way as I read in another question (In jQuery, how to attach events to dynamic html elements?) that you can use that format to attach events to dynamic elements. Just to clarify, this code continues to work with the initial page, but fails after the search filter is used.
My dynamic elements comes from a filter/search function I have that will change the list of employees based on a search text box which changes the list of employees based on a filter.php document I created.
$('#search').on('input propertychange paste', function() {
var string = $('#search').val();
$("#employeelist").load("filter.php", {'data': datastring, 'search': string});
});
However, when those elements are created from that php file, I am unable to access the elements through my jquery, I'm not sure what I'm doing wrong. There were about 4 other questions I saw where the answer was to use the jquery on function, which I've tried with no success.
Thanks for your time.
You can use following code for this
$(document).on('click', '.emptab', function() {
var status = $(this).attr('id');
$("#employeedetails").load("employee.php", {'data': datastring, 'current': status});
});

Passing loop data as variable from JavaScript to AJAX via Bootstrap modal

My code below was used to retrieve records from a loop using JavaScript. Everything works fine. Each of the records button has a unique id that when click
should alert users_id in a Bootstrap Modal popup.
The problem is that the looped button that contains users_id is not alerting anything when each button is clicked.
Below is the code for retrieving records in JavaScript along with Bootstrap modal button:
<script>
$(document).ready(function () {
$.post('users.php', function(response){
$.each(JSON.parse(response).items, function(i,v) {
$('.userslist').append('<span>'+v.id+'</span> Profile');
});
});
});
</script>
Below is the code for posting the users_id and then alert it:
<script>
$(document).ready(function(){
$(".modalLink").click(function() {
var id = $(this).attr("id");
alert(id);
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "ajax_modal.php",
data: dataString,
cache: false,
success: function(data) {
$("#rmm").html(data);
}
});
});
});
</script>
but if I take the Modal button outside the retrieve records in a javascript loop
it will alert users_id and everything will work fine as in code below
Profile
Can someone help me make each of the JavaScript looped button to post its own unique users_id and then alert it in a Bootstrap modal popup. I have attached a screen shot of the result obtained from the JavaScript loop.
Thanks
If I understand your question properly;
Try changing
$(".modalLink").click(function() {
to
$(document).on('click', '.modalLink', function() {
Without seeing the rest of your code or a working fiddle, I suspect your content is dynamic and JQ cannot bind the click handler, simply because there is no content to bind to. this answer does a good job of explaining the difference between .on and .click.
If you get the expected result, I would drop the document selector and use the closest parent static element.

Javascript for CActiveForm isnt available after renderPartial

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.

Access DOM elements on HTML page loaded with AJAX

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.

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