I have a form in Yii and want to load the next step via Ajax. So I have the following request:
$.ajax({
url: jQuery("#form-1").attr("action"),
type: "POST",
data: jQuery(form).serialize()
}).done(function(data) {
jQuery("body").html(data);
});
The url leads us to the following:
$this->render('formStep2', array('model' => $model));
so the complete view will be overwritten.
The problem is, that all event triggered javascript functions don't work. (for example afterValidateAttribute aswell as events with mouseover etc)
How do i get these working?
binding code is for example:
jQuery("#collapsor").mouseover(function(e) {
...
jQuery("#collapsing").collapse('show');
...
}
there the console says: "Uncaught TypeError: Object [object Object] has no method 'collapse'" (bootstrap). When I do collapsing only with the from bootstrap suggested html code (and a click) then it works...
Or like I said the automatic generated Yii functions "afterValidateAttribute" and so on, but there isn't a console-error at all.
edit: when I use document.write(ajaxContnent) the collapse-thing is working, but without animations and the Yii form functions are still not working...
The way to handle dynamically added content, is to attach the event to the document and target the event and selector that you require.
use jquery's on
jQuery('body').on("mouseover","#collapsor", function(e) {
jQuery("#collapsing").collapse('show');
});
Read more here about delegated events :http://api.jquery.com/on/
Related
My Issue I have an issue with a webpage where 1 in 100 page loads gives me an "Undefined is not defined" error. This error is caused by a jquery plugin being initialized before it is actually loaded. My current fix is to use window.load which works great but can take anywhere from 1 second to infinity depending on however long shareaholic decides to load (and it's faster than addthis).
My Question is there some way to initialize a plugin only after it has been loaded, like a Success event or something for including a plugin? I haven't been able to find anything.
Hopefully this will be useful to someone else who has run across this as well.
you can try this:
$.ajax({
url: pluginUrl,
dataType: "script",
success: initializePlugin
});
or just $.getScript()
It sounds like you need to wait for a certain event that is not tied to the DOM, but is tied to the way your code executes. I find jQuery's ability to fire custom events excellent for this purpose.
e.g:
//start of script - do some asynchronous work
$.ajax({})
.done(function() {
//ready to initialize the plugin - trigger an event
$(document).trigger('initializeMyPlugin');
});
//listen for the event and initialize your plugin when it is fired
$(document)
.on('initializeMyPlugin',function() {
// initialization code
});
What i would like to do is trigger a button's click event from within a view that gets returned from an ajax call. This process works fine in a pc browser such as chrome but not so in a mobile browser. (i am using both jquery and jquery mobile).
(there is a lot more code involved in this but i have removed it for clarity)
I have a button in my html page like so.
<input type="button" id="bt1" value="" />
It has an onclick event listener on it defined somewhere else.
I have an ajax call that calls a php script like so:
$.ajax({
url: 'blah.php',
type: 'get',
data: {
id : $('#field').val()
},
dataType: 'html',
success: function (data) {
$('#somediv').html(data);
}
});
It returns "data" which is a segment of html with inline javascript. It containts the following code:
<div>
<script type="text/javascript">
$(document).ready(function () {
$("#bt1").trigger("click");
});
</script>
</div>
What ive noticed is that the trigger event will not be fired when used in a mobile. but works fine in pc.
Is there a different in the DOM when dealing with mobile that it prevents a trigger("click") from working if the object is outside the view?
Try adding the touchstart event along side the click event.
$("#bt1").trigger("touchstart click");
you may need to implement touch events on mobile. Take a look at this SO answer:
Understanding touch events
If you cannot change what comes back from the server then you can listen for a click event and trigger a touch event.
Good luck,
Mike
It cannot find the button since the javascript code and the button element is being created programatically, try:
$(document).find('#bt1').trigger('click');
or
$(document).find('#bt1').each(function(e) {
e.trigger('click');
}
or, better:
success: function (data) {
$('#somediv').html(data).promise().done(){
$('#bt1').trigger('click');
});
}
I'm using jQuery for a small project I have and it's one of my first times using it. Is it safe to put all my UI code in $(document).ready() ? I'm basically creating a form that pops up when a button is pressed, and the form is processed via AJAX. Basically, when I separate my AJAX function from the functions controlling the UI, the AJAX doesn't work. However, when I put both of them in $(document).ready(), everything works fine. Here's my code. Please ignore my comments, as they were for learning purposes.
$(document).ready(function(){ //ready for DOM manipulation
/*FORM UI*/
var container_form=$('#container_form'); //container form box
var addButton=$('.addButton'); //"+" add button
container_form.hide(); //initially hides form
$(addButton).click(function(){
$(container_form).toggle('fast');
/*SUBMISSION AJAX*/
$('form.ajax').on('submit',function() { //Make form with class "ajax" a JQuery object
var that = $(this), //"that"-current form, "url"-php file, "type"-post, "data"-empty object for now
url=that.attr('action'),
type=that.attr('method'),
data={};
that.find('[name]').each(function(index,value){ //search all elements in the form with the attribute "name"
var that=$(this), //legal attribute
name=that.attr('name'); //name of the legal attribute
value=that.val(); //value of text field in legal attribute
data[name]=value; //data object is filled with text inputs
});
$.ajax({
url: url, //url of form
type: type, //type of form
data: data, //data object generated in previous
success: function(response){ //reponse handler for php
if(!response){
console.log("Error");
}
console.log(response);
}
});
return false; //Stops submission from going to external php page.
});
});
});
Generally any selectors such as $('form.ajax')., $('#container_form'), $('.addButton') needs to be in doc.ready to ensure that the DOM is ready before you try to select an element from it, since it may not find the element if the DOM hasn't finished processing. So that pretty much applies to all of your code. If you had a function such as this:
//defines a function
function addThem(first,second)
{
return first + second;
}
You could declare it outside of doc ready, and call it from within doc ready.
$(document).ready(function(){
$('#someInput').val(
addThem( $('#anotherInput').val() , $('#thirdInput').val() )
);
});
The way I think about this, is doc ready is an event, so you should be doing things in response to the "document is now ready for your to query event", not declaring things. Declaring function just says what that function does, but doesn't actually do anything, so it can go outside of the document ready. It'd be pretty silly to declare this function inside of doc.ready since it can be defined at anytime (although it certainly is possible to put it inside doc ready, it just generally clutters things up). Even if it were selecting an element, that code isn't actually running until it is called:
function hideContainer()
{
//this code never runs until the function is called
//we're just defining a function that says what will happen when it is called
return $('#container').hide();
}
$(document).ready(function(){
//here we are calling the function after the doc.ready, so the selector should run fine
hideContainer();
});
Note that the act of wiring up to other events is an action in itself, such as when you subscribed to the click events and form submit events. You are saying, "find the form element with class .ajax, and subscribe to its submit event". You wouldn't want to try and wire up to events of DOM elements until the DOM is done processing. They might not "exist" yet as far as the browser is concerned if it is in the middle of processing the DOM, and thus your attempt to wire up to the click/form submit events may fail. I say may because depending on timing/processing lag it may sometimes work and sometimes not.
There's not only nothing wrong with putting all your code into one $(document).ready(), but there's nothing wrong with putting it into multiple $(document).ready() functions either so that you can separate repeated functionality into individual JS files.
For example, I use $(document).ready() in a script included on all my site's webpages to set up UI elements, prevent clickjacking, etc. At the same time, each page regularly has its own $(document).ready() which sets up page specific user interactions.
It is absolutely OK. If you find yourself needing to abstract your code into multiple function or multiple files, then by all means, but there's nothing wrong with throwing everything in $(document).ready().
I've a simple application, and I decided to use ajax to load levels for simplicity / whatever reason (maybe to learn a bit).
But I'm stuck...
$.ajax({
url: "actions.php",
get: "GET",
data: "show_level=" + 1,
cache: false,
success: function (views){
$(".slides_container").append(views);
}
});
The problem is, views appended to my container is not selectable anymore, basically all jquery functions I had stopped working alltogether.
What is happening?
If you are using bindings like $(".target-element").click(function(){ do something here}); they are only valid for elements already in the DOM when the binding happens.
You would need to use $("#element-already-in-dom").on("click", ".target-element", function(){do something here});
You are a victim of non event bubbling.
When you bind an event to an element you typically do this on window load. If an element is added to the DOM after window load, the event will not be bound to it, despite it meeting all other conditions as laid out by your event handler.
Instead, you must use delegation, this means that events are bound to non changing elements on the page and then bubble up to the correct elements.
$('.appended-view').click(function(event) { ... }
Will not work
$('body').on('click', '.appended-view', function(event) { ... }
Will work
What I need is very simple but, searching the web, I didn't find any example.
I am using the jqModal jQuery plugin for displaying content dynamically (via Ajax) in a modal dialog. Once, this modal content is loaded, I need to bind some event on the dialog DOM elements. Therefore, I would like to assign an handler to the "success" AJAX event for manipulating these DOM elements.
The problem is that, looking into the jqModal documentation, there is no 'success' defined events. For instance, the code:
$('#ex2').jqm({ajax: 'examples/2.html', trigger: 'a.ex2trigger'});
will call the examples/2.html for the Ajax request and the response content will replace ex2 content...
...but how can I define my handler for success (or error) such that I can bind some events on the new content of '#ex2' ?
Thank you in advance for your help,
Fabien.
I'm guessing you're using the jqModel plugin? For success (not sure of error) you can add onLoad(callback) as detailed here
So for instance
$('#ex2').jqm({ajax: 'examples/2.html', trigger: 'a.ex2trigger', onLoad: doStuff});
function doStuff() {
//Do stuff here
}
You can use the onLoad callback, see here: http://dev.iceburg.net/jquery/jqModal/
$('#popup').jqm( { onLoad:onLoadCallback } );