문제

hey there i have this script´s:

$.ajax({
    url: "checkAvailability.php",
    type: 'POST',
    dataType: "json",
    data: 'username=' + $(this).data('id'),
    success: function(data) {
            if (result == 1) {
                    $("#select-err").text(data.error ? data.error : "");
            }
            else {
                    $("#select-err").text(data.error ? data.error : "");
            }
    }
});

in checkAvailability.php:

$availabilityChecker = new AvailabilityChecker($config);

if($availabilityChecker->check_availability($_POST['username'])) {
    echo json_encode(array("error" => "is ok"));
    $result = 1;
} else {
    echo json_encode(array("error" => "Wrong chose"));
    $result = 0;
} 

while testing i found out that this is not the correct way to check if a php-clause is true or false, so i need your help...could anyone show me how to check this via jquery? greetings and thanks!

UPDATE: i changed to:

$availabilityChecker = new AvailabilityChecker($config);

if($availabilityChecker->check_availability($_POST['username'])) {
    echo 1;
} else {
    echo 0;
}

and:

$.ajax({
    url: "checkAvailability.php",
    type: 'POST',
    dataType: "json",
    data: 'username=' + $(this).data('id'),
    success: function(data){
         if(data == 1){
             $("#select-err").text(data.error ? data.error : "is ok");
         }
         else{
             $("#select-err").text(data.error ? data.error : "not ok");
         }
    }
});

it works, BUT: if data == 1, on my page "1" is displayed, why and how can i fix this?

도움이 되었습니까?

해결책

Instead of doing this

if (result == 1) {

do this

if (data.result == 1) {

inside your success callback javascript file.

Then in your PHP file instead of these:

echo json_encode(array("error" => "is ok"));
echo json_encode(array("error" => "Wrong chose"));

do these instead:

echo json_encode(array("error" => "is ok", "result"=>1));
echo json_encode(array("error" => "Wrong chose", "result"=>0));

What I did is I included result as a property in the JSON coming from AJAX call. So instead of only having the error property you also have the result property in the JSON.

다른 팁

in php change to this

$availabilityChecker = new AvailabilityChecker($config);

if($availabilityChecker->check_availability($_POST['username'])) {
  echo json_encode(array("error" => "is ok" , "result"=>1));

} else {

  echo json_encode(array("error" => "Wrong chose" , "result"=>0));
} 

and in jquery

check as

if(data.result==1){
  // do the same
}else{
}

Don't echo json_encode(array("error" => "is ok")); in php in if-else statement, just echo result in both cases. In you ajax it on success callback, it will return everything that is on ur php page i.e. result which may be 1 or 0. SO check if data==1 or data==0 instead of result.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top