Execute unobtrusive Javascript after Ajax call - javascript

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.)

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){

Ajax Call Confusion

before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>

Load .txt file using JQuery or Ajax

How can I fix the script below so that it will work EVERY TIME! Sometimes it works and sometimes it doesn't. Pro JQuery explains what causes this, but it doesn't talk about how to fix it. I am almost positive it has to do with the ajax ready state but I have no clue how to write it. The web shows about 99 different ways to write ajax and JQuery, its a bit overwhelming.
My goal is to create an HTML shell that can be filled with text from server based text files. For example: Let's say there is a text file on the server named AG and its contents is PF: PF-01, PF-02, PF-03, etc.. I want to pull this information and populate the HTML DOM before it is seen by the user. A was ##!#$*& golden with PHP, then found out my host has fopen() shut off. So here I am.
Thanks for you help.
JS - plantSeed.js
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init:function () {
$.ajax({
url: "./seeds/Ag.txt",
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
HTML - HEAD
<script type="text/javascript">
pageExecute.init();
</script>
HTML - BODY
<script type="text/javascript"> alert(pageExecute.fileContents); </script>
Try this:
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init: function () {
$.ajax({
url: "./seeds/Ag.txt",
async: false,
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
Try this:
HTML:
<div id="target"></div>
JavaScript:
$(function(){
$( "#target" ).load( "pathToYourFile" );
});
In my example, the div will be filled with the file contents. Take a look at jQuery .load() function.
The "pathToYourFile" cand be any resource that contains the data you want to be loaded. Take a look at the load method documentation for more information about how to use it.
Edit: Other examples to get the value to be manipulated
Using $.get() function:
$(function(){
$.get( "pathToYourFile", function( data ) {
var resourceContent = data; // can be a global variable too...
// process the content...
});
});
Using $.ajax() function:
$(function(){
$.ajax({
url: "pathToYourFile",
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
var resourceContent = data; // can be a global variable too...
// process the content...
}
});
});
It is important to note that:
$(function(){
// code...
});
Is the same as:
$(document).ready(function(){
// code
});
And normally you need to use this syntax, since you would want that the DOM is ready to execute your JavaScript code.
Here's your issue:
You've got a script tag in the body, which is asking for the AJAX data.
Even if you were asking it to write the data to your shell, and not just spout it...
...that's your #1 issue.
Here's why:
AJAX is asynchronous.
Okay, we know that already, but what does that mean?
Well, it means that it's going to go to the server and ask for the file.
The server is going to go looking, and send it back. Then your computer is going to download the contents. When the contents are 100% downloaded, they'll be available to use.
...thing is...
Your program isn't waiting for that to happen.
It's telling the server to take its time, and in the meantime it's going to keep doing what it's doing, and it's not going to think about the contents again, until it gets a call from the server.
Well, browsers are really freakin' fast when it comes to rendering HTML.
Servers are really freakin' fast at serving static (plain-text/img/css/js) files, too.
So now you're in a race.
Which will happen first?
Will the server call back with the text, or will the browser hit the script tag that asks for the file contents?
Whichever one wins on that refresh is the one that will happen.
So how do you get around that?
Callbacks.
Callbacks are a different way of thinking.
In JavaScript, you perform a callback by giving the AJAX call a function to use, when the download is complete.
It'd be like calling somebody from a work-line, and saying: dial THIS extension to reach me, when you have an answer for me.
In jQuery, you'll use a parameter called "success" in the AJAX call.
Make success : function (data) { doSomething(data); } a part of that object that you're passing into the AJAX call.
When the file downloads, as soon as it downloads, jQuery will pass the results into the success function you gave it, which will do whatever it's made to do, or call whatever functions it was made to call.
Give it a try. It sure beats racing to see which downloads first.
I recommend not to use url: "./seeds/Ag.txt",, to target a file directly. Instead, use a server side script llike PHP to open the file and return the data, either in plane format or in JSON format.
You may find a tutorial to open files here: http://www.tizag.com/phpT/fileread.php

Synchronous jQuery calls, without putting everything in the callback

Is it possible to get a JSON in jQuery synchronously without using the async: false option (which apparently has been deprecated)? I also would prefer not to put everything into the success function.
No, there is no other option than async: false. I wouldn't recommend it if there were.
For the success function, you can simply pass another function that will be executed.
For example:
$.ajax( {
url: myUrl,
type: 'POST',
success: myFunc
} );
function myFunc( datas ) {
// do what you should do in a success function
}
Since ajax methods on jQuery return a Deferred Object (jQuery 1.5+) you could also write
$.ajax({
url: myUrl,
type: 'POST'
}).done(function() {
// do what you should do in a success function
});
Not reasonably. Trying to force the request to be Synchronous without using asyc:false is possible, but a waste of effort in my opinion. In pretty much every scenario you want to use async:true, you will be able to accomplish all of the same things with async:true as you can with async:false. It's just a matter of how you structure your code.
If you look at the current version of the source file that executes the AJAX request:
https://github.com/jquery/jquery/blob/master/src/ajax/xhr.js
You will see it still uses the async field on the settings object, this field is passed directly into the Open method of the XMLHttpRequest object. So using the default implementation all you can do, is set "async: false".
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
Now assuming you are really stubborn and want to do this without setting "async:false", you could get really bold and write a custom ajaxTransport and register it with a custom data type.
Here is an example I wrote that creates a custom transport object with a send and abort method, and registers it with the dataType 'mine'. So when you specify dataType 'mine' in your ajaxSettings object it will use this custom transport instead of the one built into jQuery. http://jsfiddle.net/xrzc7/ Notice there are two ajax requests one with the 'mine' dataType that show the alert, and one without the data type that does not show the alert. My ajaxTransport in this example isn't fully functional, its just to illustrate that you can swap in your own send function.
I wouldn't advise writing your own ajaxTransport for jQuery because it really isn't neccessary in my opinion, but to answer your question I'm suggesting it as an option.
You should pay close attention to how the default ajaxTransport in jquery is written, and how it interacts with the settings object and callback methods when writing your custom ajaxTransport. Your send function would obviously force a "false" value as the async parameter of the XMLHttpRequest.open method.
https://github.com/jquery/jquery/blob/master/src/ajax/xhr.js - this is the current source code for the default ajaxTransport mechanism.
Hope this helps, or perhaps persuades you to always use async:true. :-D

Jquery Live Load - Load form via ajax

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);
});

Categories

Resources