I have a web application where I want to get some data from an API right when the document is ready to execute javascript. I want to store this data in an Object for later access. When a user clicks on a certain link on the page, I will need access to this Object.
I'm wondering what the safest/most accepted pattern for achieving this is, since it involves to events to listen for (the success of the AJAX request and the later possible click). I don't really want to wrap all of my code in the AJAX request if I don't have to, but I also don't want to run the risk of the user clicking before the AJAX request has finished (it's a fairly small API call, but still).
Deferred objects to the rescue!
(function($){ // this prevents polluting the global scope
var request = $.ajax({...});
//... later on...
$(someelement).on("click",function(){
request.done(function(data){
console.log(data);
});
});
})(jQuery);
Related
I want to run an XMLHttpRequest to grab information from an API and then use it to populate variables in PHP code that gets executed (without jQuery). While I would like to inject the information after the page loads, that's not possible in this case for various reasons. In essence, we're populating non-HTML PHP code with no CSS ID to select.
I tried creating a Promise and using then to inject the results of the API call into session variables, but I discovered that XMLHttpRequest deprecated synchronous requests on the main thread (e.g. you can no longer use false for the last parameter in the open function.
E.g.
xhr.open("GET", "https://www.myapi.com/api/v1/objects/1.json", false);
So, how would I go about setting these variables from XMLHttpRequest before the page is rendered? Is there a good way to do that or is it deprecated for a reason and we need to consider a deeper change?
Thanks in advance for any help!
Using synchronous calls was deprecated because is almost always possible to circumvent and it slows page loading and user's experience. Is it really necessary to do it before the page rendering? You can place a loader until the request is done and the callback has the data and then remove it.
Or even better if this happens only on page load PHP can just put the result in the output HTML, if you need to store it for JavaScript use you can echo something like:
<script type="text/javascript">
var globalVar = ['stuff'];
</script>
You can use it from other scripts, and also use window.globalVar to get the value because it is global.
If it is an api with a private key then it MUST be called by PHP rather than JavaScript, otherwise whoever analyzes the code could gather the API KEY, else if it is public and you don't want to overload the server with this requests the callback method is the way to go: place a loader with an overlay on the rest of the page, when the request is completed, do your calculations and delete or hide loader and overlay elements.
In my webpage, the user can write a post and the data the user enters is then stored in the database. I want that data to be Selected by a query and posted into the webpage but without the page being reloaded.
I am aware that I need to use Ajax, but I do not know how to use it. I need the post to be added to the page when the post button available in the webpage is clicked.
If you do not know how to use it, why not try to read up on it? :)
To give you a gist of what you need to do, the button needs to be tied to an event handler in Javascript/JQuery. That event handler will be responsible for making the AJAX call and retrieving the information from the server. The call would be something like:
$.ajax({type: 'GET', url: '/path/to/information'})
Calling .done() on this particular AJAX call will execute the callback function specified in the parameter. Usually it's done like so:
$.ajax(...).done(function(data) { ... });
Where data is the response data on a successful (200) response. Once you receive the data, you would just use Javascript to update the html/text of an element on the DOM. How you implement this is solely up to you, but I suggest reading up and trying to get it to work before asking!
I am trying to use knockout and I wonder myself how it works REALLY from a network point of view : where can I see the "calls" from the browser client to the server to retrieve data?
I mean : I used to use Ajax calls to populate forms, tables... => we can see the ajax calls to the server. Same thing when I need to submit a form : I can see the ajax calls.
That means I can debug with Firefbug and see the parameters sent/ the response received, inluding the headers (request/response).
With knocknout, the data in the form are "binding" automatically by the framework ko. So, does someone know how it works really? how the calls are done? is there any way to "see" the data flow?
From a network point of view, nothing changes when using knockout. You'll still need to make AJAX calls to populate your view models, but they're outside the framework, not part of it. This means that you can still put a breakpoint on your AJAX calls and observe the stuff being sent and received.
A major code departure is that your network calls will probably now exist within a knockout viewmodel.
var someVm = function(data) {
var self = this;
self.Id = ko.observable(data.Id);
// ...
self.getItems = function() {
// AJAX call here, now method on a vm
}
}
However, as TJ Crowder points out - the key mechanic of knockout is binding a client side view model to a user interface, either for data population or visibility control in a single page application. Networking is something you'll have to handle, but it's not part of knockout. Most likely, you'll make small changes in your placement of AJAX calls.
It's based on the publish-subscribe pattern.
Whenever something is changed it notifies about it.
Here's some info about it http://msdn.microsoft.com/en-us/magazine/hh201955.aspx
I have a web page and I am associating a note with the page storing it in my database, so that the whenever the next time the page is loaded that notice can been seen till it is deleted by some other user authorized to do the same. However, say I associate a note with the page after some content is loaded through AJAX. I want the note to appear only after that particular content has loaded next time on the web page. I would like to track the AJAX request and attach the note to it? I want to do it all through simple JavaScript code put at the bottom of any web page. How can it be done?
jQuery ajax provides methods to fire events before, during and after the ajax request. Please check the api here for complete list.
Here are couple of methods that are called after completion of every ajax request.
jQuery.ajaxComplete() - Register a handler to be called when Ajax requests complete.
jQuery.ajaxSuccess() - Show a message when an Ajax request completes successfully
These functions allows you to pass a callback function to trigger after event occurs. In that call back function check if content you want is loaded or not, then show the note.
Sample code for the above methods can be found here:
http://api.jquery.com/ajaxComplete/
http://api.jquery.com/category/ajax/
Hope this helps.
You'd need to write a wrapper for all of your ajax calls that checks the result and sees if it should add a note. Here's an example, assuming you're using jQuery to handle the ajax requests:
function ajaxWrapper(settings){
var old_callback = settings.complete;
settings.complete = function(request, status){
if(status == "200"){
// check the request.responseText and add your note if appropriate
}
if(old_callback){
old_callback(request, status);
}
}
jQuery.ajax(settings);
}
And then instead of calling jQuery.ajax() directly, call ajaxWrapper() instead.
An alternate option would be to include the note in your ajax response.
Is it possible to kill a previous ajax request?
We have tabular data very adjacent to each other. On mouseover event of each data we are making a request to our server using JQuery Ajax object and showing in popup.
But as frequently we move mouse to other tabular contents previous Ajax responses are being displayed inside popups prior exact response being displayed which is meant for that tabular content.
I need when new Ajax request is generated previous request/response should be killed, so that always expected latest response is available inside popup.
I am using JQuery, PHP and Mysql to server the request.
Could you create a custom Javascript Sync object which would be shared by the function making subsequent ajax calls?
Assign a sequentially generated id as a parameter to the request call going in. Include the same id in response. On firing every request assign a new id, incremented by 1 or whatever logic. If the current id in response is not same as the one in shared object; ignore the response else render the response.
this would cleanly solve the race condition. I am not sure myself if there is a way to kill the request prematurely but it would at least not create rendering problem that you face now.
Another option would be not to initiate another request until the first is completed.
Yes and no. That is the point of Ajax. To be able to do something asynchronously. What you are wanting to do is to abort a request which destroys the idea of asynchronously. Perhaps what you can do is, if you send another request, set a value somewhere indicating the number of requests, then in the callbacks to your requests, check if the amount of request is higher than 1, if so ignore the response.
Check this AJAX Manager plugin. The XmlHttpRequest has an abort() function but jQuery doesn't have a wrapper for it.