3

scenario: my users have their own profile pages with different background colors and fonts, I want to retrieve the colors for example from a certain user using ajax. i.e.

$.ajax({ 
    type: "POST", 
    data: "id", 
    url: "ajax/css.php", 
    success: function (bg,font) { 
        $('#bg').css('background-color', 'bg');
        $('#font').css('font-color', 'font');
    } 

ajax/css.php page

<?php

//retrieve the background and font data from database for the id(userID).

// this is the bit I'm stuck here, shall I echo the results or return them :~

?>

2 Answers 2

4

JSON would probably be easiest here, like this:

$.ajax({ 
   type: "POST", 
   data: { id: someIDVariable }, 
   url: "ajax/css.php", 
   success: function (result) { 
     $('#bg').css('background-color', result.bg);
     $('#font').css('font-color', result.font);
   } 
});

Or a shorter form using $.getJSON() is GET is an option:

$.getJSON("ajax/css.php", { id: someID }, function (result) { 
  $('#bg').css('background-color', result.bg);
  $('#font').css('font-color', result.font);
});

Then in PHP:

eacho json_encode(array('font'=>$font,'bg'=>$bg));
//which will echo this format: { "font": "Arial", "bg": "#000000" }
Sign up to request clarification or add additional context in comments.

2 Comments

thank you very much exactly what i needed cheers @nick you always save the day, by the way im using this example instead accessing iframes through subdomains its bit a wierd bu i think it will work
@getaway - ahh, good approach, much better than the alternative :) +1 for trying to do it efficiently
0

Just make an action returning a valid JSON with the data you need. For instance if it returns:

{ color: "red", font:"arial"}

You can do:

$.post("user_css_info.json",{id:1234}, function(data){
  alert("Color is" + data.color); 
});

2 Comments

To make your php file return json: in your ajax script (php file), create an array of the data you want to return and then echo json_encode($your_data_array);
thanks for this @harldo thats where i was confused, can you just calrify where the user_css_info.json came from lool

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.