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!') });
Related
Is there a way to pause the rest of a function when you are waiting for a value to be returned from an asynchronous call with jQuery?
To achieve this "paused" behavior, you want to put the behavior inside the promise object. https://api.jquery.com/jQuery.ajax/
$.ajax({
url: "test.html",
data: myData
}).success(function() {
//put your code here this will only fire after it returns successfully
}).error(function() {
//This will fire if there is an error
});
What you are talking about would be a synchronous call, which is not recommended as it will freeze the UI.
Instead, use the callback provided in the jQuery call to perform the rest of your code:
function DoSomeCall()
{
$.post( "ajax/test.html", function( data ) {
//Do your follow on code in here, in the callback.
});
//Don't do any code here that relies on the AJAX being finished first.
}
I have a problem, that I have several pages in my project and I used a lot of ajax requests in my project, but now I think that whenever an ajax request is called a function will called and whenever that request ends another function will call. How can I do this globally I know I can put this in every ajax request but I need a solution which I do in one place and it works all over the project.
$(document).read(function(){
// Suppose this document load function is written on layout page and every page is inherited from this page
});
Use ajaxSetup, for example
$.ajaxSetup({
beforeSend: function() {
console.log('test');
},
complete: function() {
console.log('completed');
}
});
will setup beforeSend handler for every ajax request. Note that ajaxSetup can take any option that $.ajax can.
You should create a wrapper function for your ajax, then use that function. that way, you have "central" control over the ajax call. something like:
//fast and crude way to extend jQuery
$.fn.customAjax = function(params){
//contains defaults and predefined functions
var defaults = {
complete : function(){...default complete hander...},
beforeSend : function (){...default beforeSend handler}
...
}
//merge settings
var finalParams = $.extend({},defaults,params);
//call ajax and return the deferred
return $.ajax(finalParams);
}
//use it like
$.customAjax({
url : ...,
method : ...,
data: ...,
complete : function(){...} //redefining in the call will override the defaults
});
.ajaxStart
Register a handler to be called when the first Ajax request begins.
.ajaxSucess
Attach a function to be executed whenever an Ajax request completes successfully.
for Detail doc:
http://api.jquery.com/category/ajax/
Try something like this:
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$.ajax({
url: "anotherMethod.html",
context: document.body
});
});
});
That means whenever ajax call completed successfully call your desire call.
It doesn't have a bug when complete. Click on Like, if work for you
$(document).ajaxSend(function(event, jqXHR, settings) {
$('#general-ajax-load ').fadeIn();
});
$(document).ajaxComplete(function(event, jqXHR, settings) {
$('#general-ajax-load ').fadeOut();
});
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.)
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);
});
I have a web application that gets data with a get call. When it is called, it sets a static variable. After the call is complete I want to get the value, but the complete function that I call is not working, its calling it to fast because its null.
$.get('../Controls/myfullcontrol.aspx', {}, function (data) {
$('#SiteFullControl').html(data);
}).complete(function () {
$('#FullControlCount').html('Full Control (<%=GlobalClass.GlobalVariables.User.Count %>)');
$('#LoadingAjax').dialog('close');
});
Using Firebug or Chrome's Inspector, look at the XHR and ensure that the script is actually returning something.
Are you looking for data returned to the complete function?
Then you need a parameter in the function:
}).complete(function (data) {
You don't need the $.complete() method because the $.get() contains allready an success callback.
http://api.jquery.com/jQuery.get/
You could work with jQuery the Promise interface (introduced in 1.5).So you can chain multiple callbacks on a single request...
Take look: http://api.jquery.com/jQuery.get/#jqxhr-object
jQuery.get( url, [data,] [success(data, textStatus, jqXHR),] [dataType] )
$.get('ajax/test.html', function(data) {
//STUFF AT SUCCESS
});