Check if a javascript has loaded and then call another javascript - javascript

I have a javascript which gets JSON data from URL and loads the data on to the page, then I want to call another javascript to add the slide effects.
There is a simpler solution, i.e using setTimeout. But this solution is not complete because getting data from a URL does not have a fixed amount of time. It varies on every call.
Hence I want to check if my first javascript has loaded and then I want to call the second javascript.

JavaScript is an asynchronous language, or at least, its HTTP API is (mostly) asynchronous.
You shouldn't use settimeout, but you should use asynchronous chaining instead for building a list of causal events. There's a big bunch of libraries out there to assist this, like http://www.infoq.com/articles/surviving-asynchronous-programming-in-javascript
If you're loading content from your own site, then there'll be an onsuccess/oncomplete event when the JSON finally gets loaded, you can assign a callback to it. How it is actually called depends on your javascript framework if you use one.
If you're using data from a remote site in a format called JSONP, you're to define a callback to it, it should be a public function name, like onMyDataArrived. You should add your callback code there. Some frameworks hide this detail from you, they generate a random function which they remove when the data has arrived, and provide an API similar to onSuccess / onComplete instead.
Nowadays, the most popular javascript framework is jQuery, where you can do such things, like:
$.ajax({
url: 'give_me_my_json.php',
dataType: 'json',
success: function(data){
//call your second javascript
},
error: function(){
//WHOOOPSIE... data could not be loaded
}
});

Related

How to avoid synchronous AJAX without spawning sessions

My page loads all necessary data from the server at startup via AJAX. This includes user's language settings, various classifiers, some business data etc.
The problem I am facing is that when the user first comes to the page, all these different AJAX calls are kicked off at the same time. This means that on the server side, most of them are assigned different JSESSIONID-s (I am using Spring on Tomcat 8 without any complex configuration). As a result, some of the data is initialized on the server side in one session, but the browser might end up using a different session in the end and does not have access to the data set up by earlier ajax calls.
I wanted to solve this by using a fast synchronous AJAX call in the very beginning so that after it returns and gets a JSESSIONID, all subsequent calls would be made in this original session.
$.ajax("api/language", {
type: "GET",
cache: false,
async: false,
success: function(data) {
//do stuff;
}
});
// more AJAX calls
It works, but I get warning messages that synchronized XMLHttpRequest on main thread is deprecated. Now - I understand the reasons why such a synchronized call is bad for UI in general, but what other options are there available for me if I want to force all AJAX calls to use the same server side session?
I can achieve the same result by using a callback and just placing all the rest of my page initialization code in there, executing it in the 'success' section of the first AJAX call, but that wouldn't that have exactly the same effect as synchronizing on main?
I'd initiate the session when loading the HTML document rather than when requesting something from the API.
Alternatively, trigger the subsequent API calls from the success callback of the first one.
"Hacky" solution
You really give your own solution at the end: wrap everything in an asynchronous AJAX call. It is similiar to the synchronous solution, but this way you can set up a loading animation, or something similar.
"Nice" solution
Another, possible nicer solution. When the user arrives, you can redirect to the starting page of your web application with the generated jsessionid. This can be done with a servlet. I am quite sure that Tomcat can be configured to do this without writing your own code.

Javascript Dynamically Communicate with PHP

I'm creating a system where a Javascript script extracts data from a Sage extract, and stores it in a Javascript object (JSON I guess). I need to then upload the data to an SQL database via PHP.
I had thought of using an Iframe, by changing the src to the PHP pages URL, then pass GET variables to the page via the url. I was wondering if I could actually use tags to do this too? By creating new images and setting the src to the PHP pages URL (again, passing GET variables to it), then the PHP page could do the rest? I know the image wouldn't display anything, it doesn't need to. I just need a way to pass data to the PHP page.
Best practices?
The modern way of using JavaScript to communicate with a server is XMLHttpRequest. By default it is asynchronous and does give you the option to change this, though synchronous requests may be considered bad practice.
Here is a basic example
function sendObject(object, uri, callback) {
var xhr = new XMLHttpRequest(),
data = new FormData();
data.append('object', JSON.stringify(object));
if (callback) xhr.addEventListener('load', callback);
xhr.open('POST', uri);
xhr.send(data);
}
// ex. usage
sendObject(
{foo: "bar"},
"/somepage.php",
function () {console.log('completed with code:', this.status)}
);
Using a FormData saves you a little time, too. If you can't expect it to be available, simply do
postData = encodeURIComponent(key) + '=' + encodeURIComponent(value) + '&' + etc;
As the two other answer have said, for an HTML page with Javascript to communicate with the server, a PHP page, you would need to use XMLHttpRequest, aka AJAX. Paul S.'s answer is the best answer with respect to how to directly use XMLHttpRequest with Javascript.
However, one thing to keep in mind is that if you have to support older browsers, especially Internet Explorer version 9 or below, you'll run into quirks and it's advised to use a library for this. For the all purpose library, which includes not only AJAX methods but also form data handling and manipulating the DOM before, during, and after your request, your best bet is to use jQuery. For example, for an AJAX request to send data from a form:
$.ajax({
url: 'http://www.example.com/data.php',
data: $(form).serialize(),
dataType: 'JSON', // JSON will be returned if possible
type: 'POST'
}).then(function(data) {
...
});
jQuery is great, but it is also a big library and if you only really want or need AJAX requests, it's better to find a smaller library or use a function that's known to work cross browser. It's also important to note that jQuery has strange handling of promises, which is the way a function would say it will return a value but not right away. These promises are necessary if you chain AJAX functions together without making your code contain many nested functions. Two of the most well known promise libraries are rsvp.js and q.

What is the right way for Searching functions in a Website with Javascript?

Its known that interactions between Javascript and SQL-Databases are not very secure. But most Websites use it cause the Webside doesent reload to show matches in a search.
With PHP it isn't possible to change Page-Contents without a completely Page-Refreshing.
Witch is the right way to get Data from SQL with Javascript without security-neglects.
Aspeccialy for a Searching function with directly matches in a list.
You can use 2 way to get data from db by using js;
1. Ajax:
function refresh() {
$.ajax({
url:"your url",
method: "GET",
data: your_params,
success: function(response) {
$("#specific_div_id").html(response);
}
});
}
You can do this within an interval like;
setInterval(refresh, 5000);
in order to get content in every 5 sec.
2. Websockets
In AJAX, you are requesting in every 5 secs to get updated content from server. Think that, you are not getting content server pushes updated content to you. In other words, server notifies you on any updated data. You can have a look at Socket.io for an example implementation of websockets. When server notifies you, you can take data and put it related html area
As mention in the commentaries, the best way is to use AJAX, which is an acronym that stands for Asynchronous Javascript and XML.
The last part, XML, is a bit misleading. It kept that name because that's what is was first use for. But AJAX can now be use to make HTTP request and interface with any language, including PHP.
Depending on the technology you are built on, there are several implementation available. Chances are you have jQuery installed already. In that case, jQuery Ajax, and particularly jQuery.get() would address your concerns.
If you are using a router on the backend, you can simply call a route, specifying it as the url, first argument of the function. Otherwise, you can directly call a file by using the relative path from the html page the javascript is embedded in.
jQuery.get will return anything you echo within you server script. In other words, anything that is directly rendered on the page. You can use a callback catch the data returned and process it.
Example :
$.get('/path/to/file.php', function (data) {
console.log('Here is the data received from the server!', data)
// Process data here
});

jquery load vs ajax for form post submission

If all I want to do is submit a form to a PHP processor with POST data and get the result, is there any reason to use the ajax method over the jQuery load method?
Using Ajax requires a bunch of code versus something very simple on one line in jQuery like this:
$("#myDIV").load("myProcessor.php", {field1: target.value});
Hmmm, maybe this only works well with one field? Sorry, just getting back into JS.
$(element).load(...) will automatically insert the server response into the selected element as html (jQuery documentation for .load()). This might result in your server exposing information about the request directly to the user, which is probably not what you're looking to do.
$.ajax() also allows very fine control over what happens during the request. You can accurately intercept exceptions and produce a callback when the request finishes succesfully. These are all reasons to use $.ajax() over $(element).load(...). However, if your only concern is sending the data in the POST header and working with the response, then using $.post with a callback function will probably be the simplest approach. http://api.jquery.com/jQuery.post/
The .load method is is roughly equivalent to $.get(url, data,
success) (src).
The .get method is a shorthand Ajax
function (src).
For a simple ajax call, .load is appropriate. Use .ajax if you want to deal with specials parameters.
PS: If you don't want a fat framework like jQuery, look here : http://microjs.com/#ajax
From jQuery website about load
This method is the simplest way to fetch data from the server. It is
roughly equivalent to $.get(url, data, success) except that it is a
method rather than global function and it has an implicit callback
function. When a successful response is detected (i.e. when textStatus
is "success" or "notmodified"), .load() sets the HTML contents of the
matched element to the returned data.
you can read difference between load ajax on StackOverflow.
But, load is not for submitting a form using post method. Both POST and GET are different methods and works differently, data submitted using GET method will be available in the $_GET array but not in the $_POST.

How to hide details in jquery ajax from browser page source

I am using jquery for all my ajax thing, I don't know if that is fine but I use that for now.
I have one text input when user type characters in it I call server side get some values and add them on the view.
Code that I use bellow works fine but I want to improve it a little.
How can I make this ajax call so that users that want to investigate my page source code can't see what I call here?
So basically I want to hide from page source what url, what type and data send I use here, is it possible?
$(function () {
$("#txtSearch").keyup(function (evt) {
$.ajax({
url: "/Prethors/Users/SearchUsers",
type: "POST",
data: "text=" + this.value,
success: function (result) {
$("#searchResult").prepend("<p>" + result + "</p>");
}
});
});
});
No, a user will always be able to figure out what calls you are making if you include it in javascript.
You can compress and minify the javascript, but a determined person will always be able to find your url calls.
Here's a js compression site, for example.
http://jscompress.com/
overall, you shouldn't worry about this. there is no way I'm aware of to hide your ajax calls, but you shouldn't need to.
-you could encrypt the info.
-you could use comet to stream the data on a persistent connection. (super complicated).
-follow good server security practices and not worry about it.
source: here
If you are really worried about this, you could set up kind of an anonymous URL, which will then redirect to where you really want to go based on some variable which is arbitrary.
for example, instead of going to "/Prethors/Users/SearchUsers"
go to "/AnonymousCall?code=5"
from which you could execute the code you want for searchusers
You can't hide client-side code. You can disguise it with minification but sensitive data should always be stored and processed on the server-side.
Use console.clear(); after you ajax calls :P
It just clears the reqs from the console but you still cannot hide client side calls.

Categories

Resources