function to use query data

Asked

Viewed 63 times

1

I am building a function that via ajax queries a query in the database and via json returns the result. But everything works but I can’t use the json object anywhere else except within the function.

I have tried to use declared global variable in and out of function, Return and nothing right. follows 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 Alert inside the sql function works normally.

need to have access to this json anywhere in the script

  • There’s enough material in the community about it!

  • See if this question helps you! I even answered it too! http://answall.com/questions/182500/return-true-ou-false-no-success-do-jquery

2 answers

2

It is the old problem of asynchronous javascript. Let’s assume that the whole process of connection takes about 2 seconds.

When Voce calls the function sql(query) the block success will only be called 2 seconds later (remembering that this time is only an example), but the rest of the code continues normally, when it arrives in your return sqls you have not yet got the answer from the server, so Alert inside the success works and out not.

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

Try putting a console.log() before the return sqls and one within the success, will realize that inside the Success will always be called after.

What you need to do is put the code that depends on the sqls inside the block success.

ASYNC false

You can also use the option async: false jquery, but the problem with this is that it will "lock" the Rower while the request does not finish, which is why the request is done in the same thread, so it is used as the.

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>

  • I have tried to sync using async: false. the question is to be able to access the information of the json object outside the sql function because inside its {} works the problem and outside it

  • I do not know exactly what is happening or how it is accessing the data out of function, but I edited and put an example with async:false. You can note that the log comes in the correct order and the data too.

-1

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

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

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

Programming with asynchronous calls requires a paradigm shift. No longer makes sense the approach of storing global variables and trying to access them from anywhere and especially at any time.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.