Ajax response how to Reload JQuery(JavaScript) - javascript

Our application is JSF2 framework when we make Ajax Calls in certain scenarios we need to re-invoke the java-script(jQuery-for UI style) ,when the Ajax response returns back from server.
The javascripts are not getting called ,when the Ajax response come back..
Is there any way to enable this ?

Either use jQuery.delegate() or jQuery.on() (depending on jQuery version) instead to reapply the functions on every change in the HTML DOM tree, e.g.:
jQuery(selector).on(eventName, callbackFunction);
or let JSF re-invoke the JS functions by specifying an JSF ajax event handler by jsf.ajax.addOnEvent, e.g.:
jsf.ajax.addOnEvent(function(data) {
if (data.status == "success") { // Can be 'begin', 'complete' and 'success'.
// Re-invoke your JS functions here.
}
});

Related

Reload html page with AJAX

I have a very simple html page with one table that I would like to reload in the background every 5 seconds. In the background means that solution <meta http-equiv="refresh" content="5"> can not be accepted, because the user can observe reloading process then.
I tried the code below, but I observed that RAM usage was quickly raising and after 2-3 minutes firefox browser consumed 70-80% of available memory:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function autoRefresh_div()
{
$("#employee_table").load("index.html");// a function which will load data from other file after x seconds
}
setInterval('autoRefresh_div()', 5000); // refresh div after 5 secs
</script>
Could you please suggest something more efficient?
EDIT:
I forgot to add that in the body of html I have:
<div id="employee_table">
<table>
...
</table>
</div>
And what I wasn't sure is that I use load("index.html") so I'm loading whole page instead of just a div...?
you can also use $.ajax instead of $("").load("url");
as it will only replace the content of the given element in success function means when the AJAX request is successful, so flickering can be prevented.
function autoReload() {
setTimeout(function() {
$.ajax({
url: '/index.html',
success: function(data) {
document.getElementById("employee_table").innerHTML = data;
}
});
autoReload(); // calling again after 5 seconds
}, 5000);
}
autoReload(); // calling the function for the first time
or you can also use $.get
$.get("index.html", function(data, status){
if(status == "success"){
document.getElementById("employee_table").innerHTML = data;
}
});
$.ajax() is the most configurable one, where you get fine grained control over HTTP headers and such. You're also able to get direct access to the XHR-object using this method. Slightly more fine-grained error-handling is also provided. Can therefore be more complicated and often unecessary, but sometimes very useful. You have to deal with the returned data yourself with a callback.
$.get() is just a shorthand for $.ajax() but abstracts some of the configurations away, setting reasonable default values for what it hides from you. Returns the data to a callback. It only allows GET-requests so is accompanied by the $.post() function for similar abstraction, only for POST
.load() is similar to $.get() but adds functionality which allows you to define where in the document the returned data is to be inserted. Therefore really only usable when the call only will result in HTML. It is called slightly differently than the other, global, calls, as it is a method tied to a particular jQuery-wrapped DOM element. Therefore, one would do: $('#divWantingContent').load(...)
It should be noted that all $.get(), $.post(), .load() are all just wrappers for $.ajax() as it's called internally.
More details in the Ajax-documentation of jQuery: http://api.jquery.com/category/ajax/
Hope this will help you.

How can I retrieve data from 'any' ajax request being completed using jQuery? [duplicate]

I have a page where I can insert some javascript / jquery to manipulate the output. I don't have any other control over the page markup etc.
I need to add an extra element via jquery after each present on the page. The issue is that the elements are generated via an asynchronous call on the existing page which occurs after $(document).ready is complete.
Essentially, I need a way of calling my jquery after the page has loaded and the subsequent ajax calls have completed. Is there a way to detect the completion of any ajax call on the page and then call my own custom function to insert the additional elements after the newly created s ?
Unfortunately this doesn't apply since it seems the OP isn't using $.ajax() or any jQuery ajax method for actually loading content, but leaving it here in case future googler's are doing this.
You can use any of the global ajax events that meet your needs here, you're probably after $.ajaxComplete() or $.ajaxSuccess().
For example:
$(document).ajaxSuccess(function() {
alert("An individual AJAX call has completed successfully");
});
//or...
$(document).ajaxComplete(function() {
alert("ALL current AJAX calls have completed");
});
If you want to run just some generic function then attach them to document (they're just events underneath). If you want to show something in particular, for example a modal or message, you can use them a bit neater (though this doesn't seem to be what you're after), like this:
$("#myModal").ajaxComplete(function() {
$(this).fadeIn().delay(1000).fadeOut();
});
This example just shows and hides elements at the start and end of ajax calls using jQuery:
$("#contentLoading").ajaxSend(function(r, s) {
$(this).show();
$("#ready").hide();
});
$("#contentLoading").ajaxStop(function(r, s) {
$(this).hide();
$("#ready").show();
});
#contentLoading is an gif image progress indicator.
As i could understand, you are using some jQuery's Ajax function in your ready handler. So you could just pass it another function, which will be invoked after your Ajax function gets response. For example
$(document).ready(function(){
$("#some_div").load('/some_url/', function(){
/* Your code goes here */
});
});
You could rewrite the send() function of the XMLHttpRequest object.
See a solution for doing just so using pure Javascript here.
You could use .live()/.delegate().

Equivalent of jQuery ajaxStart in Angular 2

I want to know if there is an equivalent of ajaxStart or ajaxStop in Angular 2.
I want to check if there's an ajax which runs into the document.
According the official documentation of ajaxStart, it will be triggered when there is any Ajax Request. And I want something like this in Angular 2.
$( document ).ajaxStart(function() {
$( "#loading" ).show();
});
I do this:
into my app.component.ts, I show my loader
when my ajax is success, I hide my loader
But, some of my page doesn't have ajax call, so if I show my loader using my app.component.ts, it will be impossible to hide this, because, none of ajax request is present into this page.
I think, if I listen if ajax is not present into my page, if will hide my loader.
I use localStorage to save the status of ajax.
If the page has ajax, I set a value to that xhr
Otherwise, I remove the status stored into localStorage.
Each time, the user arrive in the page. My script check, if there is an ajax running into that page.
app.component.ts
if(localStorage.getITem("xhr")) {
// action here
}
request.service.ts
...
let checkForAjax: any = {
setXhr () {
localStorage.setItem("xhr", "1");
},
removeXhr () {
localStorage.removeItem("xhr");
}
}
...
into get request, I do this (before success callback):
checkForAjax.setXhr()
And into callback of get request, I just remove the status.
checkForAjax.removeXhr()
By the way, I haven't the xhr status, after my ajax is successed. So If I check it into my app.component.ts, I just test if there's a property xhrinto my localStorage.
I work now, but I want another way to listen for ajax with angular 2.
Is that way exist?
How can it will be done?
You could make use of Promises
https://stackoverflow.com/a/30008115/3152269 explains it better than i ever could, but it seems right up your alley
What i generally do when i shoot off an ajax request is to make a promise to run some code after it receives a response.
This makes Ajax calls easier to read and ensures the code doesn't run unless you want it to.

How should I deal with an ajax get function, that is reused across multiple pages?

I have a web application with booking/reservation-functionality. One of my core functions is to check whether a booking conflicts with other bookings, and this function is used across multiple pages. Its return data is not usually loaded with a page, as it's request parameters are dependent upon user input. In other words:
I have an ajax function, that gets booking data
It is abstracted away into it's own .js file, for reusability
The ajax function is wrapped in a javascript function.
However, an ajax function is not suitable for my intended use. The wrapper function will return nothing, before the ajax call is complete, due to it's asynchronous nature. If i need to execute something with the returned data, it should be inside the success-function of the ajax call, but as I need different things to happen, based on in which page, and which situation the data is needed.
I see three solutions to my problem. I just can't decide which is the best approach, or if there might be a fourth and better option:
1. Skip the abstraction of the ajax function. In other words, just copy/paste it into every function where I need the data, and voilla; I would have the success-condition function available at all times.
2. Pass a succes-function as a parameter. If i need something dynamic to happen, I could make it so, by passing a function to the ajax-wrapper function, and making sure that the passed function accepts the ajax returned data as it's own parameter.
3. Make the ajax call synchronous. Possible, but kind of ruins the concept of ajax (actually I am also using JSON, so that will make ajax into sjoj).
Honestly, I really can't see that either of the solutions stand out as the winner here. I would greatly appreciate any help.
I suggest using an event based approach.
Inside ajax success you can fire (trigger) an event for example booking-check-complete and the specific page handles the event the way it needs.
This way you keep the benefits of the ajax being well - asynchronous and keep the pages decoupled.
For uses like this I use jQuery event mechanism, but there are also other libraries available. Check it out here - trigger
For example in page one you have:
$( document ).on( "booking-check-complete", function( event, param1, param2 ) {
alert( "Hello from page 1" );
});
On the second page you have:
$( document ).on( "booking-check-complete", function( event, param1, param2 ) {
alert( "Hello from page 2" );
});
And in ajax success:
$( document ).trigger( "booking-check-complete", [ "Custom", "Event" ] );
NOTE
You don't need jQuery to use events as described here
This uses plain javascript, but it is not compatible with IE.
var event = new Event('build');
// Listen for the event.
elem.addEventListener('build', function (e) { ... }, false);
// Dispatch the event.
elem.dispatchEvent(event);
No. That violates DRY.
Yes. This is idiomatic JavaScript.
No. That locks up the UI (and synchronous XHR is deprecated).
Option 2 is the standout winner.

jQuery prevent multiple submisssions before response

I would do this in JS fiddle, but I can't get the POST echoer to work, so I'll make an example here. Let's pretend that someApi returns "bar"
JS / jQuery
$(function() {
$('button').click(function(event) {
getSomeData();
});
function getSomeData() {
$("div").text("Foo = ");
$.get("someApi", function(i) {
$("div").append(i);
});
};
});
HTML
<div></div>
<button>Click Me</button>
There maybe some typos here, but please ignore them as I've written an example on-the-fly. What happens is when <button> is clicked once, all works well. The AJAX function is called and the <div> is appended when the response comes. If I wait for the response and click again, the <div> is overwritten with Foo = and then appended. The issue comes when the user becomes inpatient and clicks <button> multiple times, spawning multiple AJAX requests. This ends up with "bar" being appended multiple times. Is there a feature within JS / jQuery to avoid sending multiple requests to the same URL? I DON'T mean I want a async = false scenario; I know this would work, but would also slow the application down. I also know I could add an if loop that checks if bar has already been appended. What I'm asking for is a proper JS / jQuery .blockMultipleRequest(); kind of thing.
I don't think that there's a plugin for that. You could use .one() in this way:
function bindButton() {
$('button').one('click', function(event) {
getSomeData();
});
}
function getSomeData()
$("div").text("Foo = ");
$.get("someApi", function(i) {
$("div").append(i);
bindButton();
});
}
$(function() {
bindButton();
});
In function bindButton() you define your event handler with one(). Once button has been clicked event is removed until response of AJAX call, then function bindButton() is called again and event handler gets bound again.
You could use the global AJAX event handlers that jQuery provides and then do stuff depending on the request.
.ajaxSend() when any request starts (the event, jqXHR, and settings properties are sent to the handler, so you can then do URL-specific actions by evaluating settings.url
.ajaxComplete() when any request completes.
You could then use an object that keeps track of AJAX calls per URL, which can consult before sending off another request (e.g. only if it not currently in an active/pending state).

Categories