-1

I was looking at this question: Return true/false to javascript from php file

But is not what I'm looking for, as I don't need to return text/strings in JSON.

What I want is to return true or false statements from loaded php file to jQuery.

jQuery: (How I think it could work)

if($("#lvlupann").load("/templ/checknlvl.php") == true){
                        $("#lvlupann").addClass("nlvlann"); 
                    }

And the mighty php file : (checknlvl.php)

if(1 == 1){
        return true;    
    }

But obviously it doesn't return true/false, and class is not added... I know I'm going probably wrong on it, but don't know what to overwrite...

Any help would be appreciated.

2
  • Try this: if($("#lvlupann").load("/templ/checknlvl.php") == "true"){ $("#lvlupann").addClass("nlvlann"); } Commented Mar 11, 2016 at 21:09
  • It would be best to just make a helper function and turn the response into either true or false. Commented Mar 11, 2016 at 21:12

1 Answer 1

3

You are doing it wrong.

The .load() method is asynchronous and does not return the value from the server (it returns the element that it was called on: $("#lvlupann")), so using the returned value in an if statement does not make sense.

You have to wait for the request to finish before you can use the value, like so:

$("#lvlupann").load("/templ/checknlvl.php", function (value) {
    if (value == true) {
        $("#lvlupann").addClass("nlvlann");
    }
});

As for the PHP file, the return true; will just stop the script. It does not send anything to the client. In order to send two or more things from PHP to the client you need to package the output in some fashion.

The $.get method would be useful:

$.get('/templ/checknlvl.php').done(function (data) {
    $("#lvlupann").html(data.content);
    if (data.success) {
        $("#lvlupann").addClass("nlvlann");
    }
});

<?php
echo json_encode([
    'content' => '<strong>Some content...</strong>',
    'success' => true,
]);
die;

If all you want to do is get a boolean value from the PHP script then something like this would do it:

$.get('/templ/checknlvl.php').done(function (value) {
    if (value === "true") {
        $("#lvlupann").addClass("nlvlann");
    }
});

<?php
if (1 == 1) {
    echo 'true';
} else {
    echo 'false';
}
die;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.