function to use query data

1

I'm building a function that via ajax makes the query a query in the database and via json returns the result. But everything else works I can not use the json object anywhere except inside the function.

I have tried to use global variable declared inside and outside the function, return and nothing is right. follow the code.

var sqls;
function sql(query){
    $.ajax({
    type: "POST",
    url: "php/lookup.php",
    dataType: "json",
    data: {query: query},
  success:function(dados){
   sqls = dados;   

    }
    });
return sqls;
};

If I give an alert (sqls.informacao_que_quero); the message appears undefined however if I put the alert inside the sql function it works normally.

I need to access this json anywhere in the script

    
asked by anonymous 27.03.2017 / 22:41

2 answers

2

It's the old problem of javascript asynchronous. Let's assume that the entire connection process takes about 2 seconds.

When you call the function sql(query) the block success will only be called 2 seconds later (remembering that time is only an example), but the rest of the code continues normally, when it arrives in your return sqls you still did not get the response from the server, so the alert inside success works and not out.

The success will wait until the server responds successfully, and only then is it called.

Try to put a console.log() before return sqls and one within success , you will realize that within success it will always be called after.

What you need to do is to place the code that depends on sqls within block success .

ASYNC false

You can also use the async: false option of jquery, but the problem is that it will "hang" the browser while the request does not finish, this is because the request is made in the same thread, so it is used asynchronously.

jQuery('document').ready(function() {
	var sqls;
	function sql(query){
		$.ajax({
			type: "GET",
			url: "https://jsonplaceholder.typicode.com/posts/1",
			dataType: "json",
			data: {},
			async: false,
			success:function(dados){
				sqls = dados;
				console.log('callback');
			}
		});
		
	  console.log('fim da funcao');
		return sqls;
	}
	
	sql('SELECT * FROM table;');
	console.log('resultado', sqls);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
27.03.2017 / 23:00
-1

It seems to me that the main problem is to be trying a classical synchronous programming approach using jquery, which in this particular use case, uses an asynchronous approach via callbacks. I recommend reading a 101 about asynchronous calls using callbacks.

The ajax function, for example, allows for distinct syntaxes that can simplify reading. For example, in this situation, successful callbacks can be added to the posthumous call (decorating the function); something like:

'$.ajax(...).success(function callbackSucesso(dados) { ... });

Programming with asynchronous calls requires a paradigm shift. It makes no sense to save global variables and try to access them from anywhere, and especially at any time.

    
28.03.2017 / 11:06