javascript - Prepare SQL - AJAX return Data -
i need setting db marker retrieval. got bit confused on pass back. here have far:
data returned:
["chatswood nsw au","chippendale nsw au"]
js:
var opdata = []; function markers() { $.post("id.php", {id: <?php echo $id; ?>}) .done(function(data) { //data array returned opdata = data; //tried $(opdata) = data; //tried opdata.push(data); //tried $.each(data, function(i) { //tried opdata.push(data[i]); }); }); console.log(opdata); //shows [] empty array regardless }
php:
$arr = array(); while ( $selectdata -> fetch() ) { $arr[] = $address; } echo json_encode($arr);
how go retrieving data? none of above working.
this driving me nuts.. should $.ajax instead?
the call .done
asynchronous, meaning .done
finishes right away, before ajax call made, , console.log
called right after, if http call not finished yet.
based on use case , context can choose between 3 options return opdata
caller function:
///// option 1: synchronous call function markersusingsynchronouscalltoajax() { var opdata = []; $.ajax({ type: "post", url: "id.php", async: false, // disable asynchronous call ajax data: {id: <?php echo $id; ?>}, success: function(data) { opdata = data; } }) return opdata; } var opdata = markersusingsynchronouscalltoajax(); console.log("using synchronous ajax call", opdata); ///// option 2: callback function markersusingcallback(callback) { $.post("id.php", {id: <?php echo $id; ?>}) .done(function(data) { callback(data); }); } markersusingcallback(function(opdata){ console.log("using callback", opdata); }); ///// option 3: promise function markersusingpromise(callback) { return $.post("id.php", {id: <?php echo $id; ?>}); } markersusingpromise().done(function(opdata){ console.log("using promise", opdata); });
Comments
Post a Comment