1

I have css.php file which will generate dynamically styles in every ajax call but how to effect with front end without page load. For example inside css.php ( .class1{color:#ddd;} .class2{color:#eee;} ) actually it will generated by php loop and creating class from combination of key and value. so it is possible to load css content from php using ajax or jquery if yes then how ?

1
  • Yes, but that is a loaded question. You need to get the basics of down of using jQuery/Ajax and .CSS() first with some sample things you've tried specific to your scenario. Commented Jan 9, 2015 at 18:32

1 Answer 1

1

Yes, this is possible. You just need to either:

  • Append this style into your page <head> section into <style></style> block
  • Add <link rel="stylesheet" type="text/css" href="css_script.php">

For example, the 1st variant (using jQuery):

$.ajax({
    url: 'css_script.php',
    success: function(data) {
        $('#ajax-css').remove(); // Remove previous CSS
                                 // received by AJAX (if exists)

        var $styleElement = $('<style/>');
        $styleElement.attr('type', 'text/css');
        $styleElement.attr('id', 'ajax-css'); // ...so that we can find
                                              // and replace this element later
        $styleElement.html(data);
        $styleElement.appendTo($('head'));
    }
});

Here's the Fiddle.

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

2 Comments

actually i am using WordPress so in href it shows an error Fatal error: Call to undefined function get_option()
after add some my own logic and some part of yours its working Thanks

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.