1

I have an issue when I want to change a background color of my div element via jquery after receiving an ajax respond, it doesn't work.(Code is validated, I tested it by entering a test line in error statement before changing css property and it worked.) Here is the code:

#statusbox {
background-color: #FFFFFF;
width: 15px;
height: 15px;
display:inline-block;
float: left;
position:relative;
left:190px;
top:3px;
border-style: solid;
border-width: 2px;

border-color: black;

}

And the jquery

success: function(msg) {
    if (msg['connected']) {
        $('#statusbox').css("background-color", "#00FF00");
    } else $('#statusbox').css("background-color", "#FF0000");
},
error: function(error_msg) {
    $('#statusbox').css("background-color", "#00FF00");
}
2
  • 2
    you are missing a # Commented Oct 16, 2014 at 7:28
  • And you're missing an opening { after else. Please validate your code first before asking questions — sometimes it all boils down to a typo. Commented Oct 16, 2014 at 7:37

2 Answers 2

3

First, you have (had, in the original post) a tiny CSS syntax error:

$.css({}); takes in an object containing properties as CSS property => value.

In you case, you are assigning 00FF00 to background-color, that would equal to the following CSS definition:

CSS code

#statusbox {
    background-color: 00FF00
}

You forgot the #, use:

Javascript code

$('#statusbox').css("background-color", "#00FF00");

Secondly, the first parameter of the success handler of $.ajax() is the HTML echoed by the script called.

That is, if your PHP script does this:

PHP code

echo 'connected';

You check that the following way:

Javascript code

success: function(msg) {
    if (msg == 'connected') {
        $('#statusbox').css("background-color", "#00FF00");
    } else $('#statusbox').css("background-color", "#FF0000");
}

Make sure you have no rogue whitespaces before or after the actual php code, because that will be echoed as well; or just strip the spaces:

Javascript code

success: function(msg) {
    if (msg.replace(' ', '') == 'connected') {
        $('#statusbox').css("background-color", "#00FF00");
    } else $('#statusbox').css("background-color", "#FF0000");
}
Sign up to request clarification or add additional context in comments.

Comments

0

Everything is fine in your code just use # before you colour code like below

$('#statusbox').css("background-color","#00FF00");}

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.