php - Global Variables with jQuery -
just got footable responsive table plugin work. trying setup php script pull postgresql , return json encoded array.
everything working fine far. close making jquery script work, i'm not sure why variables not passing along.
here script:
var columns_json; var rows_json; jquery(function($){ $.ajax( { type: "post", datatype:"json", url: "a.php", data: {action: 'test'}, success: function(data) { columns_json = data[0]; rows_json = data[1]; console.log(columns_json); console.log(rows_json); }, failure: function(data) { alert("something went wrong"); } }); $('.table').footable( { "paging": {"enabled": true}, "filtering": {"enabled": true}, "sorting": {"enabled": true}, "columns": columns_json, "rows": rows_json }); });
if @ console, can see 2 data arrays returned correctly... tried output data make sure correct (no issue there):
console.log(json.stringify(columns_json))
so not understanding jquery is: when update variables declared @ top of scripts within $.ajax
function, why json arrays not available @ $('.table').footable(
function?
admitting i've been playing jquery little on month new me.
i did find 1 workaround work , suggestion on post. modified script , got work. console throws warning:
"synchronous xmlhttprequest on main thread deprecated because of detrimental effects end user's experience.".
like always, thoughts , suggestions appreciated.
move logic fills table inside success callback.
alternatively can encapsulate logic in function , call function success callback.
the reason code not working, because $.ajax async, meaning not wait server request finish, instead next code executed immediately.
in answer linked find async: false
- wich (bad) alternative, because make ajax call wait server response - user if browser frozen.
suggestion: show loading animation/overlay, while you're doing ajax calls may take few seconds finish.
after you've modified code, check if variables still need global.
var columns_json; var rows_json; jquery(function($) { $.ajax({ type: "post", datatype: "json", url: "a.php", data: { action: 'test' }, success: function(data) { columns_json = data[0]; rows_json = data[1]; $('.table').footable({ "paging": { "enabled": true }, "filtering": { "enabled": true }, "sorting": { "enabled": true }, "columns": columns_json, "rows": rows_json }); }, failure: function(data) { alert("something went wrong"); } }); });
Comments
Post a Comment