Page 1 of 1

[SOLVED] how to "return" true/false from PHP to AJ

Posted: Fri Jun 29, 2007 5:43 pm
by martinco
hi!

i made a ajax script that needs to know if it has to reload the information shown on the page.

i wrote a php script that compares an id with the last id on a db table,... but how can i "return" a true/false expresion :?: and how can ajax catch that :?:

thanks!
"Pura Vida!"

Posted: Fri Jun 29, 2007 6:54 pm
by JellyFish
The only way to return true within a response from php is to have php echo something like:

Code: Select all

exit("true");
And for false:

Code: Select all

exit("false");
And in you Ajax callback:

Code: Select all

if (data = "true")
{
// do something
}
else
{
// do something else
}

Posted: Sat Jun 30, 2007 12:30 am
by martinco
that's new for me... almost everything about php is new for me...

i did the following in my php script:

Code: Select all

echo "true"
and in ajax:

Code: Select all

if(ajax.responseText.indexOf("true") != -1) {
...
} else {

...
}
maybe it is better using exit(), i'll try.

thanks and "Pura Vida!"

Posted: Sat Jun 30, 2007 12:57 am
by JellyFish
Could we see some of your PHP script?

Posted: Mon Jul 02, 2007 9:59 pm
by martinco
sorry, i was out all the weakend...

what part of the php code do you want to see? Here's what i do to "return" a boolean value from PHP:

Code: Select all

...
$row=mysql_fetch_array($result);
if($row["id"] > $lastid) {
	echo 'true';
} else {
	echo 'false';
}
...
And here's the other (AJAX) side which makes the request and gets the boolean value:

Code: Select all

...
if (ajax.readyState==4) {
	if(ajax.responseText.indexOf("true") != -1) {
		if(debug) alert("Update? Yes");
		getLastId();
		loadMessages(div_id);
	} else if(debug) alert("Update? No");
	setTimeout('update("'+div_id+'")',speed);
}
...
what does exit() do? and i don't understand the javascript line if (data = "true") JellyFish posted.

"Pura Vida!"

Posted: Tue Jul 03, 2007 2:27 am
by JellyFish
exit() pretty much exits the current script.

What I meant by (data = "true"), and I really meant (data == "true"), was that data be the responseText of the Ajax request. Anyways you did better utilizing the indexOf() method rather then a straight comparison(which is what I suggested).

You might want to use the exit() function rather then echo, but it really depends on you php script.

What exactly are you having trouble with?

Posted: Tue Jul 03, 2007 6:55 pm
by martinco
thanx jellyfish!
i actually have no problem. my script is running fine and i got what i wanted with the script i posted.
a read about exit() but in this case i'll use echo because after this i have to close a mysql connection.
indexOf and charAt are just two great js functions, just keep that in mind, and sometimes you'll find great usages for them