Tuesday, 15 February 2011

php - Why is this returning me 'undefined' -



php - Why is this returning me 'undefined' -

this question has reply here:

how homecoming response asynchronous call? 11 answers

trying run script, (test.al();) , within test.al, called getcrypt.php();, php script on webserver, , working. currently, these scripts

js

var getcrypt = { php: function () { $.ajax({ url: "server.com/return.php", type: "post", async: true, data: "id=getit", success: function (msg) { var v = msg.match(/^.*$/m)[0]; homecoming v; } }); } } var test = { al: function () { = getcrypt.php(); alert(a); } }

php

<?php $id = $_post['id']; if ('getit' == $id){ $value = 'value'; echo $value; }else{ echo 0; } ?>

in way, show alert 'unidefined', , if add together alert(v); right before homecoming v, show me 'value', not able utilize outside variable...

var getcrypt = { php: function () { $.ajax({ url: "server.com/return.php", type: "post", async: true, data: "id=getit", success: function (msg) { var v = msg.match(/^.*$/m)[0]; alert(v); homecoming v; } }); } }

this give me alert right value (after 'undefined')

this because of asynchronous phone call you're making. homecoming success function , not php function.

to value out need write:

var value; var getcrypt = { php: function (callback) { $.ajax({ url: "", type: "post", async: true, data: "id=getit", success: function (msg) { var v = msg.match(/^.*$/m)[0]; alert(v); callback(v); } }); } } getcrypt.php(function(v) { alert(v); // happens later below value = v; }); // below still not work since execution has passed place // alert still homecoming undefined alert(value);

php javascript jquery ajax scope

No comments:

Post a Comment