2

I have a little problem. I want to pass two variables from PHP to $.ajax success function

I have this code written in JS:

$.ajax({
                        type:"POST",
                        url:path,
                        data: "value="+info,
                        success:function(data,data1)
                        {
                            if(data==1)
                            {
                                $(id).css("backgroundColor","green");
                                $(id).attr("readonly","readonly");
                                $(image).attr("src",data1);
                            }
                            else
                            {
                                $(id).css("backgroundColor","red");
                            }
                        } 
                });

And my PHP code is :

if(isset($_POST['value']) and !empty($_POST['value']))
{
$result=0;
$image="src/photo1.jpg";
$value=trim($_POST['value']);

if($value=="Abracadabra" or strcmp($value,"Abracadabra")==0)
{
$result=1;
$image="src/abracadabra.jpg";
}
else
{
$result=0;
$image="src/photo1.jpg";
}

echo $result;
echo $image;
}

There, I want to "echo" two variables simultaneously to pass to $.ajax success function.

It is possible ? I don't refer to JSON, I refer only PHP with POST method.

Thank you

Teodorescu
  • 148
  • 5
  • 15

2 Answers2

2

the response from php code will be something like:

0src/photo1.jpg

and you will have to parse it with the javascript (probably with regex or substring)

success:function(data,data1) {
   var result = data.substring(0,1);
   var image = data.substring(1);
   // ... your code
}

keep in mind that it could cause you trouble if the $result variable is more than one character long :)

Teneff
  • 30,564
  • 13
  • 72
  • 103
  • thank you Teneff, you opened my brain :D...I understand,if result is more than 1 character long (for example 3 characters), I will do : var result=data.substring(0,3) and var image=data.substring(3).I got it. – Teodorescu Jun 11 '11 at 08:49
0

have PHP echo a string like "value1|value2|etc" (or whatever other character(-sequence) is unlikely to wind up in the actual data)

then on the javascript side do a string.split('|') to break the returned string up into a neat little array. you could even do key1:value1|key2:value2 and then use the solution presented here to split the key:value pairs up into an object.

WdeVlam
  • 129
  • 4