What happens when ajax call is invoked? - ajax

What happens when we create setTimeout or Ajax call?
I have a problem with invoking autoplay in HTML5 player on iPad.
If I call thing like that:
function playItem()
{
var playerArea = $('#playerArea');
var flowplayerAjdi = getFlowplayerId();
playerArea.empty();
playerArea.append(createQualityChooserHTML()+'');
clipProperties.url = 'http://192.168.100.107:1935/ia/live/playlist.m3u8';
playLiveFlowplayer(flowplayerAjdi, getWowzaUrl('ia'), '', '', true, true);
}
everything works fine. But you can see that url is hardcoded - it has to be assigned by ajax call. So here is what I did:
function playItem()
{
$.ajax({
url : 'playVODServlet',
type : 'GET',
data : JSON.stringify(playItemParams),
timeout : 5000,
dataType : "json",
error : function(xhr, ajaxOptions, thrownError)
{
console.error("Error");
},
success : function(searchResult)
{
var playerArea = $('#playerArea');
var flowplayerAjdi = getFlowplayerId();
playerArea.empty();
playerArea.append(createQualityChooserHTML()+'');
clipProperties.url = searchResult.assetId;
playLiveFlowplayer(flowplayerAjdi, getWowzaUrl('ia'), '', '', true, true);
}
});
}
An how autostart doesn't work. So my question is: what could be the problem? It looks it is related with ajax call breaks normally code execution and creates error and success function. Same thing happens if I put player constructor to setTimeout.

Phones & tablets do not allow you to autoplay audio/video. This is precaution so the user doesn't get a hefty bill because your application automatically streamed video/audio.
You could try triggering a click event on the player once your page has loaded, but I doubt it'll work.

Related

Making simultaneous AJAX calls to separate Django views

I have a Django view that runs a particular function when a POST request is received.
Snippet:
def run_function(request):
if request.method == 'POST':
run_some_function()
This is called via AJAX as follows:
$.ajax({
'type' : 'POST',
'url' : '/run_function/',
'data' : data,
'success' : function(json) {
// Display results to user
}
});
This works as expected. However, this particular function can take a while to run, so I want to display progress information to the user.
Luckily, I have another function that can return the progress (an integer between 0-100) of the task.
Snippet:
def get_progress(request):
progress = calculate_progress()
return HttpResponse(json.dumps(progress), content_type="application/json")
I can then make an AJAX call every X seconds to get the progress and update my progress bar:
function check_progress() {
$.ajax({
'type' : 'POST',
'url' : '/get_progress/',
'success' : function(response) {
if (response >= 100) {
// Update progress bar to 100% and clearInterval
} else {
// Update the progress bar based on the value returned by get_progress
}
}
});
}
var check = setInterval(check_progress, 500);
The problem is...how can I do both simultaneously? I need to be able to make the AJAX call to run the function and make the AJAX calls to monitor progress, at the same time.
Are there any suggestions for how to accomplish this? Or perhaps a better design than making two AJAX calls?
Thanks for any help!
The A in AJAX stands for Asynchronous. You don't need to do anything special. If you have your views and progress sorted out, all you need to do is:
$.ajax({
'type' : 'POST',
'url' : '/run_function/',
'data' : data,
'success' : function(json) {
// Display results to user
}
});
var check = setInterval(check_progress, 500);

Phonegap and AJAX bad performance

I'm loading data to my application using an async AJAX call. This call takes some time as the server is very slow. Loading the application on the desktop or a phone as a web site shows the expected behaviour: Page loaded - some delay - site update with loaded data. Executing the page using phonegap is showing the splash screen, than a black screen and after a very long time (the time for executing the ajax call) the normal screen. I assume there's any reason that Phonegap is waiting for the call to be finished before displaying the content. Can this be prevent/configured?
Code sample:
function connect(){
var username = window.localStorage.getItem( 'username' );
var password = window.localStorage.getItem( 'password' );
if(username!=null&&password!=null){
jQuery.ajax({
async: true,
type : "GET",
dataType: 'json',
url : loginURL,
success : function(data) {
token=data.token;
connected=true;
oSettingsTile.setInfo("Connected");
oSettingsTile.setInfoState(sap.ui.core.ValueState.Success);
var oFeedModel=new sap.ui.model.json.JSONModel();
jQuery.ajax({
type : "GET",
url : feedURL,
dataType : "json",
async: true,
success : function(data,textStatus, jqXHR) {
oFeedModel.setData(data);
oFeedTile.setInfoState(sap.ui.core.ValueState.None);
oFeedTile.setNumber(oFeedModel.getProperty("/list/length"));
},
error : function(err){
oFeedTile.setInfo("Error loading");
oFeedTile.setInfoState(sap.ui.core.ValueState.Error);
}
});
var oGroupModel=new sap.ui.model.json.JSONModel();
jQuery.ajax({
type : "GET",
url : groupURL,
dataType : "json",
async: true,
success : function(data,textStatus, jqXHR) {
oGroupModel.setData(data);
oGroupTile.setInfoState(sap.ui.core.ValueState.None);
oGroupTile.setNumber(oGroupModel.getProperty("/list/length"));
},
error : function(err){
oGroupTile.setInfo("Error loading");
oGroupTile.setInfoState(sap.ui.core.ValueState.Error);
}
});
feedView.setModel(oFeedModel);
feedDetailView.setModel(oFeedModel);
groupView.setModel(oGroupModel);
groupDetailView.setModel(oGroupModel);
},
error : function(err,status,errT){
token="";
oGroupTile.setNumber(0);
oFeedTile.setNumber(0);
connected=false;
oSettingsTile.setInfo("Error");
oSettingsTile.setInfo(sap.ui.core.ValueState.Error);
}
});
}
}
you may think, that page is being loaded while splashscreen is on, but its not. Whole html/css/js is loaded after splashscreen is gone, thus if you have slow server, it will last some time until you see the content.

How to stop AJAX calls if there's an error on a field with a keyup trigger

I have this jquery ajax call that is trigger on keyup. It has error handling which (with Firefox for e.g.) is triggered multiples times if the user enters keystrokes fast. Is there a quick way to stop multiple alert windows to be shown?
$('input[name$="_LOC"]').keyup(function(){
if ($(this).val().length >=4){
$.ajax({
type: 'POST',
url: 'red.asp?q='+$(this).val(),
beforeSend: function() {
[...]
},
success: function(data) {
[...]
},
error: function() {
alert("Oops!")
}
});
}
});
Restart a timer each time the onkeyup is triggered, this means the event only happens when the user has finished typing (or, at least, paused for a second or whatever).
Use timer = setTimeout(yourFunction, yourDelay);
To rest the timer user clearInterval(timer) and start the setTimeout again.
var typing = false;
var timer;
$('input[name$="_LOC"]').keyup(function(){
if(typing) {
clearInterval(timer);
}
timer = setTimeout(sendAjax, 500, [this]);
typing=true;
});
function sendAjax(element)
{
if ($(element).val().length >=4){
$.ajax({
type: 'POST',
url: 'red.asp?q='+$(element).val(),
beforeSend: function() {
[...]
},
success: function(data) {
[...]
},
error: function() {
alert("Oops!")
}
});
typing = false;
}
Here's JSFiddle example: http://jsfiddle.net/X8US5/, you'll need your browsers console.log viewer ready to see stuff (otherwise edit the console.logs to be alerts though they interrupt JS so times will be off)
Edit:
IE9 compatible (hack) version http://jsfiddle.net/5ndM5/1/
Tried to find a jQuery alternative but none it seems.
THe overriding the function alternative is good if you don't want the global var, but if you only plan to use this code on one form then the global is acceptable (JS code is usually rife with them by accident anyway)

AJAX avoid repeated code

I'm using Symfony2.1 with Doctrine2.1
I'd like to use AJAX for many features on my site , editing a title , rate an article , create an entity on the fly , etc.
My question is simple :
Do I need to create a JQuery function for each functionnality , like this :
$('#specific-functionality').bind('click', function(e){
var element = $(this);
e.preventDefault();
// the call
$.ajax({
url: element.attr('href'),
cache: false,
dataType: 'json',
success: function(data){
// some custom stuff : remove a loader , show some value, change some css
}
});
});
It sounds very heavy to me, so I was wondering if there's any framework on JS side, or a specific method I can use to avoid this. I was thinking about regrouping items by type of response (html_content , boolean, integer) but maybe something already exists to handle it nicely !
From what I understand, you are asking for lighter version of JQuery ajax method. There are direct get/post methods instead of using ajax.
$.get(element.attr('href'), {'id': '123'},
function(data) {
alert(data);
}
);
To configure error function
$.get(element.attr('href'), {'id': '123'}, function(data) {alert(data);})
.error(function (XMLHttpRequest, textStatus, errorThrown) {
var msg = jQuery.parseJSON(XMLHttpRequest.responseText);
alert(msg.Message);
});
Also, you can pass callback function to do any synchronous operations like
function LoadData(cb)
{
$.get(element.attr('href'), { 'test': test }, cb);
}
And call
LoadData(function(data) {
alert(data);
otherstatements;
});
For progress bar, you use JQuery ajaxStart and ajaxStop functions instead of manually hiding and showing it. Note, it gets fired for every JQuery AJAX operation on the page.
$('#progress')
.ajaxStart(function () {
//disable the submit button
$(this).show();
})
.ajaxStop(function () {
//enable the button
$(this).hide();
});
Instead of $('#specific-functionality').bind('click', function(e){, try this:
$(".ajax").click(function(){
var url = $(this).attr("href") ;
var target = $(this).attr("data-target") ;
if (target=="undefined"){
alert("You forgot the target");
return false ;
}
$.ajax(....
And in html
<a class="ajax" href="..." data-target="#some_id">click here </a>
I think it is the simplest solution. If you want some link to work via ajax, just give it class "ajax" and put data-target to where it should output results. All custom stuff could be placed in these data-something properties.

jQuery.ajax() sequential calls

Hey. I need some help with jQuery Ajax calls. In javascript I have to generste ajax calls to the controller, which retrieves a value from the model. I am then checking the value that is returned and making further ajax calls if necessary, say if the value reaches a particular threshold I can stop the ajax calls.
This requires ajax calls that need to be processes one after the other. I tried using async:false, but it freezes up the browser and any jQuery changes i make at the frontend are not reflected. Is there any way around this??
Thanks in advance.
You should make the next ajax call after the first one has finished like this for example:
function getResult(value) {
$.ajax({
url: 'server/url',
data: { value: value },
success: function(data) {
getResult(data.newValue);
}
});
}
I used array of steps and callback function to continue executing where async started. Works perfect for me.
var tasks = [];
for(i=0;i<20;i++){
tasks.push(i); //can be replaced with list of steps, url and so on
}
var current = 0;
function doAjax(callback) {
//check to make sure there are more requests to make
if (current < tasks.length -1 ) {
var uploadURL ="http://localhost/someSequentialToDo";
//and
var myData = tasks[current];
current++;
//make the AJAX request with the given data
$.ajax({
type: 'GET',
url : uploadURL,
data: {index: current},
dataType : 'json',
success : function (serverResponse) {
doAjax(callback);
}
});
}
else
{
callback();
console.log("this is end");
}
}
function sth(){
var datum = Date();
doAjax( function(){
console.log(datum); //displays time when ajax started
console.log(Date()); //when ajax finished
});
}
console.log("start");
sth();
In the success callback function, just make another $.ajax request if necessary. (Setting async: false causes the browser to run the request as the same thread as everything else; that's why it freezes up.)
Use a callback function, there are two: success and error.
From the jQuery ajax page:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
// Do processing, call function for next ajax
}
});
A (very) simplified example:
function doAjax() {
// get url and parameters
var myurl = /* somethingsomething */;
$.ajax({
url: myurl,
context: document.body,
success: function(data){
if(data < threshold) {
doAjax();
}
}
});
}
Try using $.when() (available since 1.5) you can have a single callback that triggers once all calls are made, its cleaner and much more elegant. It ends up looking something like this:
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2){
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively
var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
alert( jqXHR.responseText )
});

Resources