Reputation: 21
<?php //load.php
$myid = $_POST['id'];
if($myid == 1){
echo '1';
}else if($myid == 0){
echo '0';
}
?>
<html>
<input id="id" />
<div id="result"></div>
<input type="button" id="submit" />
<script type="text/javascript">
$('#submit').click( function(){
var send = 'id=' + $('#id').val();
$.post('load.php', send, function(data){
if(data == 1){
$('#result').html('Success');
}else if(data == 0){
$('#result').html('Failure');
}else{
$('#result').html('Unknow');
}
});
});
</script>
</html>
I test this script in some free host and it work but in my real host jquery unidentified data return and it alway show 'Unknow'.
When i change if(data == '1') it show 'Unknow' too
EX: input id = 1 click submit & data return is 'Unknow'
Why ?? I think this error from host, because i test it in some free host and it work, but now in my real host i got this error, how i can fix it ?
Upvotes: 1
Views: 113
Reputation: 178285
You use #result but have resurl
you need to not return anything but your value if myid is set. As Rob points out, you return 1<html>...
or 0<html>....
For some reason, echo "1" actually returns data ="1 "; so a trailing space.
The reason is outlined here http://ellislab.com/expressionengine/user-guide/development/guidelines/general.html#php-closing-tag
The PHP closing tag on a PHP document ?> is optional to the PHP parser. However, if used, any whitespace following the closing tag, whether introduced by the developer, user, or an FTP application, can cause unwanted output, PHP errors, or if the latter are suppressed, blank pages. For this reason, all PHP files should OMIT the closing PHP tag, and instead use a comment block to mark the end of file and it’s location relative to the application root. This allows you to still identify a file as being complete and not truncated.
Alternatively trim the result:
<?php //load.php
if(isset($_POST["id"])){
$myid = $_POST['id'];
if($myid == "1"){
echo "1";
}else if($myid == "0"){
echo "0";
}
}
else {
?>
<!DOCTYPE html>
<html>
<head>
<title>Post something</title>
<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script type="text/javascript">
$(function() {
$('#submit').click( function(){
$.post('load.php', {"id":$('#id').val()}, function(data){
window.console&&console.log(data,data=="1");
var val = $.trim(data);
if(val == "1"){
$('#resurl').html('Success');
}else if (val == "0"){
$('#resurl').html('Failure');
}else{
$('#resurl').html('Unknown:[<span>'+val+'</span>]');
}
});
});
});
</script>
</head>
<body>
<input id="id" />
<div id="resurl"></div>
<input type="button" id="submit" />
</html>
<? } /* end php tag can be left out to avoid trailing spaces after it */
Upvotes: 2