getJSON Synchronous
Asked Answered
M

4

46

GOAL: What I'm after is to get data from database and refresh main.php (more evident through draw_polygon) every time something is added in database (after $.ajax to submit_to_db.php).

So basically I have a main.php that will ajax call another php to receive an array that will be saved to database, and a json call another php to return an array will be used by main.php.

$(document).ready(function() {
    get_from_db();
    $('#button_cancel').click(function(){
       $.ajax({
          url: 'submit_to_db.php',
          type: 'POST',
          data: {list_item: selected_from_list},

          success: function(result){
             ...
             get_from_db();
          }
       });
    });
    function get_from_db(){
         $.getJSON('get_from_db.php', function(data) {
             ...
             draw_polygon(data);
         });
    }
 });

In my case, what I did was a get_from_db function call for getJSON to actually get data from database, with the data to be used to draw_polygon. But is that how it should be done? I'm a complete newbie and this is my first time to try getJSON and ajax too to be honest. So my question: How does asynchronous work actually? Is there another workaround for this instead of having to call function get_from_db with getJSON (it isn't synchronous, is it? is that why it doesn't update the page when it isn't within a function?) All the time - like $.ajax with async: false (I couldn't get it to work by the way). My approach is working, but I thought maybe there are other better ways to do it. I'd love to learn how.

To make it more clearer, here's what I want to achieve:

  1. @start of page, get data from database (currently through getJSON)
  2. Paint or draw in canvas using the data
  3. When I click the done button it will update the database
  4. I want to AUTOMATICALLY get the data again to repaint the changes in canvas.
Morganica answered 22/10, 2012 at 10:44 Comment(1)
A nice solution can be found here: #934213 (look for Jonathan's answer using ajaxSetup)Valuator
D
30

Asynchronusly does mean the Request is running in the background, and calls your function back when it got a response. This method is best if you want to have a result but allow to use your app within the request. If you want to have a direct response, take a look at a synchron request. this request will pause script execution until it got a response, and the user can not do anything until the response was recieved. You can toggle it via:

async: false,

So for example:

$.ajax({
    url: "myurl",
    async: false,
    ...
})
Dissidence answered 22/10, 2012 at 10:48 Comment(7)
I could just put async: false with $.getJSON('get_from_db.php', function(data) { ... }); ? More importantly, does sync mean it will resume (you say it pauses) when there is a change in the database getJSON is accessing to?Morganica
yes, this should work. Then the function will get called directly, not after a delay.Dissidence
I also have to change comma to semi-colon then? $.getJSON('get_from_db.php', function(data) { async: false, }); doesn't work. EDIT: it doesn't work with semi-colon also - async: false;Morganica
yes, because it has to be { async: false } :) in the Options the last option must not have a comma behind.Dissidence
Yes, there are no errors now. But maybe it's just that sync or async:false isn't just how I understand it to be. Thanks for the help. Async: false didn't let me achieve what I'm after, but at least I learned something new.heheMorganica
Please show where you add the parameter async: false or show an example.Pitarys
@PeterKrauss the answer is given below, where @Previous says // Set the global configs to synchronous $.ajaxSetup({ async: false }); Place this bit of code in the top of your file.jsSpectrum
P
64

Since $.getJSON() uses ajax configurations, just set the global ajax configs:

// Set the global configs to synchronous 
$.ajaxSetup({
    async: false
});

// Your $.getJSON() request is now synchronous...

// Set the global configs back to asynchronous 
$.ajaxSetup({
    async: true
});
Previous answered 14/4, 2014 at 9:56 Comment(4)
Great solution, rally love this one! Thanks allot, as this sets and unsets the variable and does not leave Ajax in async mode. Work brilliantly!Folly
I would not use a global-config-approach to avoid unpredictive behavior. Quote from jQuery docs: "we strongly recommend against using this API. Instead, set the options explicitly in the call or define a simple plugin to do so". See my answer how to do this.Selfcontent
@R.Oosterholt, it is best to use all ajax commands asynchronously. (That is what the a in ajax stands for after all.) But the fact that the question was asked and several people have found this useful, means that there are some cases in which this is desirable behavior...Previous
"it is best to use all ajax commands asynchronously"; that's why I though a warning / information notice would be in place.Selfcontent
D
30

Asynchronusly does mean the Request is running in the background, and calls your function back when it got a response. This method is best if you want to have a result but allow to use your app within the request. If you want to have a direct response, take a look at a synchron request. this request will pause script execution until it got a response, and the user can not do anything until the response was recieved. You can toggle it via:

async: false,

So for example:

$.ajax({
    url: "myurl",
    async: false,
    ...
})
Dissidence answered 22/10, 2012 at 10:48 Comment(7)
I could just put async: false with $.getJSON('get_from_db.php', function(data) { ... }); ? More importantly, does sync mean it will resume (you say it pauses) when there is a change in the database getJSON is accessing to?Morganica
yes, this should work. Then the function will get called directly, not after a delay.Dissidence
I also have to change comma to semi-colon then? $.getJSON('get_from_db.php', function(data) { async: false, }); doesn't work. EDIT: it doesn't work with semi-colon also - async: false;Morganica
yes, because it has to be { async: false } :) in the Options the last option must not have a comma behind.Dissidence
Yes, there are no errors now. But maybe it's just that sync or async:false isn't just how I understand it to be. Thanks for the help. Async: false didn't let me achieve what I'm after, but at least I learned something new.heheMorganica
Please show where you add the parameter async: false or show an example.Pitarys
@PeterKrauss the answer is given below, where @Previous says // Set the global configs to synchronous $.ajaxSetup({ async: false }); Place this bit of code in the top of your file.jsSpectrum
F
20

$.getJSON(), doesn't accept a configuration, as it says in the docs it's a shorthand version of:

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

So just rewrite your request in terms of that and async:false will work just as you expect.

Forearm answered 13/5, 2013 at 16:37 Comment(0)
S
15

$.getJSON() is a shorthand notation for $.ajax() which can be configured to be synchronous (see jQuery.getJSON and JQuery.ajax):

$.ajax({
  dataType: "json",
  url: url,
  data: data,
  async: false, 
  success: function(data) {
      ...
      draw_polygon(data);
  }
});

Try to avoid synchronous calls though. Quote from jQuery doc (see async prop):

Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

You might want to try jQuery Deferreds like this:

var jqxhr = $.getJSON(url);
jqxhr.done(function(data) {
    ...
    draw_polygon(data);
});
Selfcontent answered 23/2, 2015 at 15:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.