Jquery Live Load - Load form via ajax - javascript

I am simply looking to call a function when a form is loaded via ajax. My current code looks like this:
$('form').live("load",function() {...}
My ajax call looks like this:
jQuery.ajax({
type: "get",
url: "../design_form.php",
data: "coll=App_Forms&form=Step_1_Company_Sign_Up",
dataType: "html",
success: function(html){
jQuery('#Right_Content').hide().html(html).fadeIn(1000);
}
})
I know that i could put my call inside the success portion of the ajax call but i am trying to minimize code and resuse other codes so i would really like to use the live feature.
I am loading a form via ajax and when that form is loaded i want to trigger a function using the jquery live. This works fine when i set it to "click"
$('form').live("click",function() {...}
but it is unnecessary to run this function on every click, i just need it to run once on the form load so that is why i want to use the load listener not the click.
Thank you.

Edit: I think you wanted to have custom code inside success callback which will be used in different pages so you don't want to duplicate the same ajax call in different pages. If so, then you should call a function inside that success callback and implement different version of that in different page.
jQuery.ajax({
type: "get",
url: "../design_form.php",
data: "coll=App_Forms&form=Step_1_Company_Sign_Up",
dataType: "html",
success: function(html){
jQuery('#Right_Content').hide().html(html).fadeIn(1000);
afterFormLoad(); //Implement this function
}
});
function afterFormLoad() { } //dummy function defined in the common code
And in your specific page,
function afterFormLoad () {
//this is from page 1
}
Below just shows you about .live/.die and .one incase if you want to understand how to unbind it using .die.
You can unbind .live inside the click handler using .die,
DEMO
$('form').live("click",function(e) {
alert('clicked');
$('form').die('click'); // This removes the .live() functionality
});
You can use .one if you are using jQuery 1.7. See below code,
DEMO
$(document).one('click', 'form', function() {
alert('clicked');
});

There isn't a dom insert event.
Although, in javascript you can trigger anything
success: function(html){
jQuery('#Right_Content').hide().html(html).fadeIn(1000)
.trigger('ajax-load');
}
Then you can listen to event using
jQuery('#Right_Content').on('ajax-load', callback);
Triggering the event manually might be helpful for use in a couple of pages, but if you need it to use across entire application, you'll be better using a plugin such as provided by Oscar Jara

There is no load to trigger with jQuery live, try to read the API documentation: http://api.jquery.com/live/
On the other hand, you can use a plugin called livequery and do something like this:
$(selector).livequery(function() {
});
Use as reference:
https://plugins.jquery.com/livequery
https://github.com/brandonaaron/livequery

You may want to consider load() method which is a convenience method of $.ajax
http://api.jquery.com/load/
var data= "coll=App_Forms&form=Step_1_Company_Sign_Up"
jQuery('#Right_Content').hide().load("../design_form.php", data,function(){
/* this is the success callback of $.ajax*/
jQuery(this).fadeIn(1000);
});

Related

Other Ajax calls not working after the first

just working on a small blogging system and using multiple ajax calls for updating information without page reloads.
However, after one ajax call the others dont work and instead the form goes to the php page itself.
The ajax calls all follow a similar pattern of:
$(document).ready(function(){
$('.addpost').one("submit",function(e){
$.ajax({
type: "POST",
url: "process/addnewpost.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(response){
if (response.databaseSuccess) {
$("#container").load("#container");
} else {
$ckEditor.after('<div class="error">Something went wrong!</div>');
}
}
});
});
});
On my page, these scripts are loaded like so:
<script src="http://buildsanctuary.com/js/addcomment.js"></script>
I had the same issue with some button events, but got around the issue using .on() however sometimes this doesnt even work so my solution was to put the even in the ajax success response.
Cant find any answers around about how to bind / delegate a whole script?
You use $('.addpost').one("submit",function(e){ to bind the submit event to do your ajax therefore it will ony execute one time, use on instead.
$('.addpost').on("submit",function(e){

Jquery Pjax - Ajax success function

Currently I am translating my ajax calls to regular $.pjax() call. Everything works fine but ajax success function. I can't manage how to call pjax success function with given parameters.
The only thing I can use is defining pjax global success function to be called on each pjax call:
$(document).on('pjax:success', function(event, data, status, xhr, options) {
});
But unfortunately I would like to define per call specific success function.
Ajax call example:
$.ajax({
url:"/myPage/myFunction",
type:"POST",
data:giveMeData(),
success:function(data){$('#right_form').html(data);console.log('Success works!')}
});
Pjax call example:
$.pjax({
url:"/myPage/myFunction",
type:"POST",
container:'#right_form',
data:giveMeData(),
success:function(){console.log('Success works!')}
});
I don't believe that the jQuery PJAX library supports passing a "success" function directly in to a $.pjax call, although I suspect you could work around this using the $(document).on('pjax:success') callback & its options attribute in order to achieve the same functionality.
For example, say your request is like the above, but you want to have a custom success callback you could use something like this:
$.pjax({
url:"/myPage/myFunction",
type:"POST",
container:'#right_form',
data:giveMeData(),
custom_success:function(){console.log('Custom success works!')}
});
Then, in order to run the custom_success method you could hook up the standard pjax success listener, and given that all the parameters provided to $.pjax are made available in options, you can then grab custom_success function and run it. So your listener may look something like example
$('#right_form').on('pjax:success', function(event, data, status, xhr, options) {
// run "custom_success" method passed to PJAX if it exists
if(typeof options.custom_success === 'function'){
options.custom_success();
}
});
Which i *think* would provide the sort of functionality your after?
A late answer but I found the solution here.
$.pjax({
url:"/myPage/myFunction",
type:"POST",
container:'#right_form',
data:giveMeData(),
}).done(function() { console.log('Success works!') });

Calling a javascript function from a link generated from a ajax call

I have a javascript function.
I'm making a AJAX call, and in that recieved content there is a link that I want to call the javascript function with.
MyJavascriptFunction(bla){
alert (bla);
}
Result from ajax = "Click
Do I have to do anything special with the result from AJAX to get this to work or should it just work.
I have tried it like this but with no success with clicking the link.
The AJAX call:
function doSearch() {
var form = $('form');
$.ajax({
url: "doSearch.php",
type: "GET",
data: form.serialize(),
success: function(result){
document.getElementById("result").innerHTML=result;
}
});
}
In the php I'm printing out
Click
First of all, try it. But yes you have to do something with the AJAX result. It has to be put somewhere in the DOM or the user won't be able to click on it.
Plus, make sure that the javascript function is a top level. I would suggest you use event handlers instead though.
Change your <a> tag to:
Click
You are mixing jQuery and DOM. that is not pretty
try this - assuming you do not have more than one link in the html
success: function(result){
$("#result").html(result).find("a").on("click",function() {
MyJavascriptFunction(bla);
return false;
};
}

Listening for the addition of certain elements to the DOM by AJAX

I have a web application which uses a lot of AJAX to display pages.
In my javascript I have a feature which gets all the elements that have a certain class (testClass). It does a bunch of stuff with these classes but that's not necessary for my problem.
At the moment my function runs when the DOM is ready and it works great. However, I need my function to run when AJAX returns a new page to the browser as it could contain elements with testClass.
Is there a way I can listen if a certain DOM element is added? I basically need a way to recognise a DOM change, when this change has happen run my function.
Or is there a way I can listen for the addition of elements with class testClass?
If it help here is a snippet of my code:
execute = function () {
var found = false;
$('.testClass').each(function () {
//bunch of code
});
}
$(document).ready(function () {
execute();
});
Try with ajax success method
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});

Execute unobtrusive Javascript after Ajax call

I want to use John Resig's pretty date for replacing my ugly time stamps with some nice-to-read time specification.
So I thought about using the following unobtrusive html markup:
<span data-type="prettyDate">25.04.2012 10:16:37</span>
Acording to that I use following Javascript/jQuery to prettify the date:
$(function() {
$('[data-type="prettyDate"]').prettyDate();
}
My problem is that I don't know how to deal with markup that is loaded using ajax because that would not be caught since it does not yet exist when the DOM ready event fires. Reacting to events on "ajaxed" elements is pretty easy using the on handler. But this is not an event.
You have to call .prettyDate() after each Ajax response is added to the DOM. A simple way to do that is to set a global complete handler with ajaxComplete.
You can use jQuery to target dynamic content before it's actually been inserted into the document, something like:
success: function(html) {
var $html = $(html);
$html.find('[data-type="prettyDate"]').prettyDate();
$(somewhere in document).append($html);
}
What you want to do to get the best performance out of this is have a function which get called on the data as it gets returned from the ajax callback. That way you can prettify your date before adding them to the DOM.
You don't want to call pretty date on element in the DOM every time as you will process date already done too.
So, something like this.
$.ajax({
url:'someurl',
success: function(data) {
var $content = $(data).find('[data-type="prettyDate"]').prettyDate();
$('#mycontainer').append($content);
}
});
or have an helper function which you call
function prettify(data) {
return $(data).find('[data-type="prettyDate"]').prettyDate();
}
or even better hook into the ajax call so that it is done for all html content
There have been a number of cases where I needed certain code to execute after every AJAX call. I'm not sure if it's considered the "correct" solution but I simply decided to create my own wrapper method and use that whenever I needed to make an AJAX request. It typically looks something like this:
AJAXLoadData: function (url, data, successCallBack) {
$.ajax({
type: "GET",
data: data,
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Code I want to execute with every AJAX call
// goes here.
// Then trigger the callback function.
if (successCallBack) successCallBack(msg);
},
error: function (msg) {
alert("Server error.");
}
});
}
In my case this made it particularly convenient to create a javascript caching system for static HTML files.
You could incorporate this code into your ajax success callback function. When the ajax is done and you update your page, also run the code to prettify the dates.
This is one of the things .on() is for. (In the olden days, .live() would have been used.)

Categories

Resources