Changing background color via jQuery AJAx?

scenario: my users have a dash of their own profile pages with different background colors and fonts, I want to get colors for exmaple from a specific 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 im stuck here, shall i echo the reuslts or return them :~

?>

An example would be great thanks guys :))

+3
source share
2 answers

JSON will probably be the easiest here:

$.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 the GET 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" }
+4
source

Just do the action returning valid JSON with the data you need. For example, if it returns:

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

You can do:

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

Source: https://habr.com/ru/post/1778090/


All Articles