1

This should be really simple but for some reason I'm stumped on this...

I'm trying to set the position of an element on page load from ajax data

like so:

$.ajax({
    url: "session_data.php",
    type: 'POST',
    async: false,
    success: function (data) {
        $('#dragable_box').css( data );
        console.log("Stored Session Data: " + data);
    }
});

the data variable returns a correct result as I can see it in the console and I tried copying in the result as a test and it positioned the element as expected. It just wont work with data...

I tried with and without async: false

What am I doing wrong or not doing?

4
  • If you are expecting a json result try to add the dataType: 'json' to ajax options. Commented Mar 3, 2011 at 2:50
  • @Šime it is an echo response from PHP so I presume just a text string? Commented Mar 3, 2011 at 2:52
  • 1
    if you pass in a string into the css method, then jQuery tries to read the value of the CSS property which name is the string that you passed in. That's why it doesn't work for you. Commented Mar 3, 2011 at 2:55
  • Yep just figured that out, I have now made sure It is properly formatted json, declared it with dataType: 'json' and it works. Thanks Commented Mar 3, 2011 at 2:58

1 Answer 1

1

A couple things about css():
.css() with one string parameter like .css('font-size') will return the font size of the matched element.
.css('font-size', '1.1em') will set the font size of the matched element to 1.1em.
.css({'font-size':'1.1em'}) will also set the font size of the matched element to 1.1em.

Also, if you are meaning data to be an object literal like {'text-color':red} you probably need to add the dataType:'json' parameter to your .ajax() call. It is most likely a string that looks like an object literal when you print it to the console. Declaring your return type to be json will cause jQuery to evaluate the result and give you an object literal that you can pass to .css().

Sign up to request clarification or add additional context in comments.

6 Comments

@offex What do you mean by dictionary? An object?
Yes, JavaScript "dictionaries" are objects. Updated to reflect that.
@offex I guess you mean object literal. JSON string: '{ "foo": 1 }', object literal: { 'foo': 1 }
Yes this is what I was trying to do. Thanks for your help. Also worth noting I had to use double quotes, not single quotes for properly formatted json ;-)
Nice job figuring it out. Although, I would think single quotes or double quotes would work since both are valid in JavaScript.
|

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.