0

this is my first question at stackoverflow, speaking specifically ... i am using the result of my PHP file ("myphp.php") ...

<?php
echo "Hello"
?>

now the javascript code that was called :

function functionX()
{

var result;
$.post("myphp.php",function(data)
{
result=data; /// result should be Hello
});
alert(result); /// the msgbox shows "Undefined"
// i am enable to access the result i got from PHP file
}

So my problem is how to access the result , so that i can use it at other parts of my code ... OR can you suggest some other ways .. THANXX

as i am a newbie to ajax .. i want to use this concept for checking username availability as shown

var result;
function functionX(username)
{

$.post("check_username.php",{usn:username},function(data)
{
if(data=="OK"){result="yes";}
if(data=="FAIL"){result="no";}
});
alert(result); // Now i want the result here .. its important
}

<?php
$usn=$_POST['usn'];
$flag=0;
$q=mysql_query("SELECT * FROM accounts");
while($row=mysql_fetch_assoc($q))
{
if($row['usn']==$usn)
{
$flag=1;break;
}
}
if($flag==1)
{
echo "OK";}
else
echo "FAIL";
?>

i know these methods for detecting username existence can be silly .. so that's what i did

Zafta
  • 655
  • 1
  • 10
  • 26

2 Answers2

0

It's because if you just put the code below it doesn't mean after as raina77ow mentioned.

If you don't need the data later just use this:

function functionX(){
  $.post("myphp.php",function(data)    {
    alert(data);
  });
}
Nergal
  • 985
  • 1
  • 14
  • 29
  • The first code snippet here fixes the problem that the alert is not called within the callback - but the second example doesn't change the behaviour - the scope of 'result' is the callback function (i.e. it does not store the result) – symcbean Jun 09 '13 at 12:31
  • You're right I deleted that part. – Nergal Jun 09 '13 at 13:28
0

try this

var result;

$.ajax({
       type: "POST",
       url: 'myphp.php',
       success: function (data) {
           result=data;
       }

});​
alert(result);
sharif2008
  • 2,716
  • 3
  • 20
  • 34