Optimal way to use Ajax - ajax

i have a web page that once it loads, it sends a lot of Ajax calls to fill some parts of the page. It's a Django template, it's sending around six calls with code similar to this :
$.get("http://127.0.0.1:8000/purchase/?name="+me.username, function(data){
$("#purchase").append(data);
});
sometimes they are called when the user clicks on a button, but they are mostly called when the page is refreshed.
Im new to Ajax, and I want to know if it's the right way to use this technology in an optimal manner. Is it alright to send Ajax calls similar calls that are separate ?
Thanks

For now i think just put those $.get() scripts into a jQuery ready function if you want them to fire when page loads and not on refresh... And yes its normal for a page to behave like this. That's what AJAX is meant for.
$(document).ready(function(){
$.get("http://127.0.0.1:8000/purchase/?name="+me.username, function(data){
$("#purchase").append(data);
});
//other $.get 's
});
Also use the jQuery ready() documentation.

Related

$.ajax in wordpress - Slow and not caching

I'm having troubles with a script, related to wordpress and ajax.. I think it loads really slow, and if I click a clicked link, it takes the exact same time (not caching)
What I'm doing is, loading single.php in other page. Each time a link-post is clicked, that post is loaded through Ajax inside a div.
jQuery.ajax({
'url':post_link,
'type':'POST',
'beforeSend': function(){
jQuery(".container").html('<img src="ajax-loader.gif" />');
},
'success':function(results){
// some functions
}
});
Any ideas what's the problem here?
HTTP POST instructions aren't cached; you need to use HTTP GET/HEAD if you want caching to occur.
As for why it's "slow", the information you've given isn't enough to go on.

How to trigger unobtrusive javascript when the content is dynamic with ajax (Lightbox)

I've got some links coming in from ajax that need lightbox functionality:
<img src='...'>
Normally this is given behavior via an on page load handler, but since the content is coming from ajax, the UJS isn't getting triggered.
Any way to do this?
If the content is coming from AJAX, then din't setup the event handling during page load. Instead, let the event bubble to the topmost container that is not being changed or replaced by AJAX. Worst case, use document as the topmost node.
$('<root element selector>').on('click', 'a.lightbox', function() {
// activate lightbox on the clicked element.
});
I'm not sure how you're triggering the ajax requests, but if it's with jQuery which seems likely, you can bind the lightbox in the success callback:
$.ajax({
url: '/route',
success: function (response, status) {
$('.lightbox').lightbox();
}
});
You can pass in a context to the jQuery selector so you don't re-attached the lightbox to links that are already in the page, for example if your ajax call is adding the links to a div with id 'lightbox_links', use this selector instead:
$('.lightbox', '#lightbox_links').lightbox();

Use Ajax in Prototype.js to load PART of an external page into a div

I'm looking for a way to load a part of an external page (possibly selected by an id in the external page) into a div. Something similar to Ajax.Updater, but with the option of specifying an id to look for in the external page.
Does anything like this exist in prototype. I've been googling for examples without luck. If I can't find it soon I'll have to do some "gymnastics" with Ajax.Request and some function tied to onSuccess.
You could do something like this, though it is by no means an elegant solution.
new Ajax.Updater("container", 'www.babes.com', {
onSuccess: function() {
$("container").update( $('idOfSomeLoadedElement') );
}
});
I don't think there is an actual elegant way of doing this purely in js. Ideally, you'd make your AJAX request only for what you need. You might be able to do some server-side stuff to lop out what you don't need (basically, offload the onsuccess functionality above to the server).
Instead of AJAX you might get by with an iframe.
// dollar function calls Element.extend
var iframe = $(document.createElement('iframe'));
// control how and what it loads
iframe.addEventListener('onLoad', function() {
$('container').update(iframe.contentDocument.select('#someID').first());
});
iframe.setAttribute('src', 'http://URL');
// add it as invisible, content isn't loaded until then
iframe.setAttribute('hidden', true);
document.body.appendChild(iframe);
From a minimal test it's clear that you'll have to be as concious about cross-origin policies as any AJAX method, that is, it's a PITA.

how to get information from php without refreshing the page

hi
sorry for the bad title but I'm not 100% sure what I need for this problem
I created a welcome page and then when you click on links you get more information, for example:
Click Me
And then the php would get the information based on the id.
so the information received is reloaded on the page after the pages refreshes
what I would like to be able to do is when user clicks on the link, use jquery to not allow the link to run but still run the url in the background (without refreshing the page)
I have no idea where to start from so I really hope you could help
thanks
In a nutshell, it's called Ajax: sending an HTTP request to your server through javaScript, and receiving a response which can contain results, data, or other information.
You mention jQuery, here are the docs about that:
http://api.jquery.com/jQuery.get/
http://api.jquery.com/jQuery.post/
are convenience methods, which encapsulate $.ajax with preset options.
http://api.jquery.com/category/ajax/ is an overview of the whole system in jQuery.
The basics go like
//include jquery, etc.
$(document).ready(function(){
$('#some_element').click(function(){
$.get('some_url_on_your_server.php',{'data':'whatever params'},function(data){
do_something();//
},'json');
});
This will bind an element to make an Ajax call on click, and then you use the function ('success' function, in $.ajax) to handle the json data.
Have your server send back the data in JSON by using json_encode in php. Be sure to send the right header back, like
<?php
header('Content-Type: application/json');
echo json_encode($some_array);
exit;
There's a lot of resources on the web and SO for learning about Ajax, it's a big topic. Best of luck.
Make a JavaScript function, like sendData(linkId) and then each tag would have an onclick event called sendData(this). SendData(linkId) can then do an HTTPRequest (also known as an asynchronous or AJAX request) to a php file, let's call it handler.php, which receives GET or POST methods. I prefer using the prototype framework to do this kind of thing (you can get it at prototypejs.org).
Okay, now that I have said all that, let's look into the nitty-gritty of how to do this (way simplified for illustrative purposes).
Download the prototype script, save it on your server (like prototype/prototype.js, for example) and then put somewhere in your html <script type='text/javascript' language='Javascript' src='prototype/prototype.js'></script>
Your tags would look like this:<a id='exampleLink' onclick = 'sendData(this)'>Click me!</a>
You need JavaScript to do this: function sendData(tagId){
var url = 'handler.php?' + 'id=' + tagId;
var request = new AJAX.Request(url, {method = 'get'});
}
Finally, you need a php file (let's call it handler.php) that has the following: <?php
$tag_to_get = $_GET['tagId'];
do_a_php_function($tag_to_get);
?>
That's it in a nutshell, but it's worth mentioning that you should give your user some sort of feedback that clicking link did something. Otherwise he will click the link furiously waiting for something to happen, when it is actually doing just what its supposed to but in secret. You do that by making your php script echo something at the end, like 'Success!', and then add an onSuccess parameter to your JavaScript's new Ajax.Request. I'll let you read how to do that on your own because the prototype website explains how to receive a response from the handler and put the feedback somewhere in your HTML without making the user refresh.
you can achieve that behavior with a jquery function called $.get ... you can get more information on how to use here http://api.jquery.com/jQuery.get/
If you really want to (and I don't think you really do), you can use XMLHTTPRequest (wrapped in jQuery.get) to facilitate loading content into the page without page refreshing. You want an id or class on that tag, i.e. Click Me, and then:
<script>
$(".fetch").bind("click", function(evt)
{
$.get(this.attr("href"), function(data)
{
$("#whereIWantMyContent").html(data);
});
evt.preventDefault();
});
</script>
I would recommend you use AJAX to start with. A good place to being is http://www.w3schools.com/Ajax/Default.Asp
The link comes with a handy AJAX ASP/PHP Example too =))
Good Luck.

How do I detect the start of a ajax call?

In JQtouch, any link is automatically convert into ajax call. I want to detect the moment the ajax call was send. This is so that i could insert a loading screen to let users know that the system is processing the submission.
I search through jqTouch API and apparently they only have callback events for page animation. Am i missing out on anything?
You can use the core jQuery global AJAX functions, for example $.ajaxStart() for the start of a batch of requests, or $.ajaxSend() to detect the beginning of each request. Something like this:
$(document).ajaxSend(function() {
alert("Request sending...");
});
Ready up on jQuery's Ajax Events: http://docs.jquery.com/Ajax_Events .
You may bind these to elements as follows:
$("...").bind("ajaxSend",myFunction) ;
every element specified this way will then react to a Ajax call being made with the specified callback function.

Resources