1

My problem should be very easy to resolve, I just can't get it together.

I have a simple working php file. It retrieves data from a database and assigns it to an array. It does not requires parameters and such. It gives a straight array:

PHP

...PDO connection code...
...SQL code....

$query = $dbc->query($sql);
$db_data = $query->fetchAll();

//I added the code below to send to JQuery:
echo json_encode($db_data);

No problems here, it gives me a nice multidimensional array

The problem is in my JQuery:

$(document).ready(function () {
    var ajaxURL = 'ajax.php';
    var ajaxData = {};

    $.get(ajaxURL, function (data) {
        ajaxData = data;
    });

        //For testing
        alert( ajaxData );

        //JQuery code to be used with ajaxData...
});

$.get is retrieving the array, without problems. data is 100% OK, but... When I want to use ajaxData it's empty or undefined (if I remove var ajaxData = {};). I need ajaxData to get the contents of $db_data to use on other stuff latter on.

The core of the problem is: JQuery loads and runs all the other code first (Past $.get). And THEN, it runs $.get code last. How can I get it to run $.get FIRST, and then to run whatever code is below? Is that what you call a synchronous ajax request?

Omar
  • 11,783
  • 21
  • 84
  • 114
  • You could try http://api.jquery.com/jQuery.getJSON/ – Rob Schmuecker May 21 '14 at 07:16
  • @RobSchmuecker It took me hours to figure out a "working" $.get request. How can I code .getJSON? – Omar May 21 '14 at 07:18
  • You can't run `$.get` first, unless you want synchronous javascript, which is totally different from AJAX (A for asynchronous). Just code whatever you want inside the function you pass to `$.get`, or better yet, call a function within the function you pass to `$.get`, and pass data to that function. – serakfalcon May 21 '14 at 07:33

8 Answers8

3

$.get is asyncronous

If you do the following:

var ajaxData = {};

$.get(ajaxURL, function (data) {
    ajaxData = data;
});

alert( ajaxData );

The request and response from the server will almost certainly happen after the alert because the call is asyncronous - it's not practical to ever make assumptions like the above as to when a callback will be fired.

You'll need to use the success callback to do whatever it is you want to do i.e. for the alert example in the question:

var ajaxData = {};

$.get(ajaxURL, function (data) {
    ajaxData = data;
    alert( ajaxData );
});

Note that if data is a string and not an object it's because the response from the server is the wrong mime type - ensure it is served with appropriate headers:

header('Content-Type: application/json');
Community
  • 1
  • 1
AD7six
  • 63,116
  • 12
  • 91
  • 123
  • How do I do that? To use a synchronous request? Or the success call back you mentioned? – Omar May 21 '14 at 07:35
  • Since I should not, what approach should I take to get $db_data from php into Javascript/JQuery? – Omar May 21 '14 at 07:42
  • There isn't enough code in the question to say specifically - put or call whatever from in the success callback (don't forget to account for the success callback never being called because of an error...). – AD7six May 21 '14 at 07:45
2

The simpliest way is better:

$.getJSON(ajaxURL, function (data) {
    ajaxData = data;
});

With this, jQuery parses automatically the json and retrieves an object that you can use into your app.

Paul Marti
  • 151
  • 5
  • Know that that's just [shorthand for calling $.ajax with specific options](http://api.jquery.com/jquery.getjson/) - that may actually cause the call to fail depending on whether the response is served as json or not. +1 anyway. – AD7six May 21 '14 at 07:37
  • @paul-marti What is the difference between $.getJSON? I thought that by using in php: `echo json_encode($db_data);` it wont make a difference? – Omar May 21 '14 at 07:51
  • @Omar, Use $.getJSON only if you receive json from PHP. This function receives data and parses it automatically. The difference with $.ajax is that is not necessary to specify $.parseJSON(data) or dataType = json; As AD7six says, it's a shorthand function to use when you are expecting to retrieve json from PHP. – Paul Marti May 24 '14 at 08:13
  • @PaulMarti My last PHP line of code is `echo json_encode($db_data); `. My guess is, that it qualifies as JSON data... – Omar May 25 '14 at 06:56
1

Try this code:

$.ajax({
   url: '/ajax.php',
   success: function (data) {
      // To return a JS object form JSON string
      data = $.parseJSON(data);

      //For testing
      alert( data );
   }
});

Hope that helps...

J.T.
  • 135
  • 11
  • You're implicitly assuming here that data is a string - if it is "silently" correcting for that isn't really the right thing to do. – AD7six May 21 '14 at 07:38
1

The problem is ajaxURL is declared within the context of an anonymous function that is called on document.ready, whereas the AJAX request won't resolve until later.

So, your alert will be empty, because the function got triggered, it resolved, and in the meantime, the AJAX function is running, and will resolve later. You have to write anything you want to do with data into the function you pass to $.get. Does that make sense?

serakfalcon
  • 3,501
  • 1
  • 22
  • 33
  • `$.get` "works". It's taking ajaxURL OK and it's getting the array just fine. But it's running after the rest of the code (`alert(ajaxData)`)` – Omar May 21 '14 at 07:48
  • For the reasons explained in the answer (+1 for the explanation). – AD7six May 21 '14 at 07:49
1

I hate when this happens (to answer my own question), since the credit is not mine but a collective of many of your answers, comments and How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

$.ajax({
    url:     ajaxURL,
    success: function( data ) { ajaxData = $.parseJSON(data); },
    async:   false
});

A "simplified"/short hand version (Thanks @paul-marti):

$.ajaxSetup({async:false});
$.getJSON(ajaxURL, function (data) {
    ajaxData = data;
});

Either one works.

Community
  • 1
  • 1
Omar
  • 11,783
  • 21
  • 84
  • 114
  • +1 for solving your own problem _however_ if you want that it's a clear indicator the existing js should really be refactored. – AD7six May 21 '14 at 10:55
0
$(document).ready(function () {
    var ajaxURL = 'ajax.php';
    var flag=[];
    $.get(ajaxURL, function (data) {
        flag[]=data;  // if data not parsed from php page then use JSON.parse(data)
    });
    alert(flag);
});
SagarPPanchal
  • 9,839
  • 6
  • 34
  • 62
0

You should use your developer console for debugging purposes like this instead of firing an alert.

Then you would have seen, that your variable data is only a string and not yet an object. You still need to parse your result with sth like this:

var result = JSON.parse(data);

Daniel
  • 3,541
  • 3
  • 33
  • 46
-1

Directly saying no you cannot here is similar question Make AJAX "get" function synchronous / how to get the result?

you will have to use a global variable instead.

window.ajaxData = data;

instead of

ajaxData = data;

http://snook.ca/archives/javascript/global_variable

Community
  • 1
  • 1
  • @AD7six No. I meant that it donot have access to ajaxData because of scope.So he should use a global scoped variable. – Madhurendra Sachan May 21 '14 at 07:31
  • suggesting the use of a global variable is even worse (there isn't one in the question, you're saying to add one) =). unless there's a local variable with the same name, there is no scope confusion [further reading (see 5. Advanced: Closure)](http://stackoverflow.com/questions/500431/javascript-variable-scope). – AD7six May 21 '14 at 07:32
  • So the answer is no if you read this http://stackoverflow.com/questions/10972892/make-ajax-get-function-synchronous-how-to-get-the-result – Madhurendra Sachan May 21 '14 at 07:33
  • @AD7six WIll you please remove the downvote.I hate them :( – Madhurendra Sachan May 21 '14 at 07:37
  • The reason for the downvote still exists in the answer - no. – AD7six May 21 '14 at 07:39