Author Topic: JSON and php.. hmm  (Read 961 times)

Offline GreenLantern

  • Level 2
  • *
  • Posts: 5
  • Reputation: +0/-0
    • View Profile
JSON and php.. hmm
« on: June 19, 2011, 07:41:27 AM »
Right, basically im wanting to make something along the lines of this for a crimes page as such, but im wondering how it would work with the php?
Any ideas?

I find it quite alot different to normal stuff id do in php which is why i need help.. if i could implement something like this into my game, it will make my game more smooth as such..  :)

Code: [Select]
 <script>
  if($.cookie("css")) {
    $("link").attr("href",$.cookie("css"));
  }
  
  function addCommas(nStr) {
   nStr += '';
   x = nStr.split('.');
   x1 = x[0];
   x2 = x.length > 1 ? '.' + x[1] : '';
   var rgx = /(\d+)(\d{3})/;
   while (rgx.test(x1)) {
   x1 = x1.replace(rgx, '$1' + ',' + '$2');
   }
   return x1 + x2;
  }
  
  $(document).ready(function(){
    
    var hash = "206D9255B0407F2BF0994293C87DD5C0";
    
    $(".load").ajaxStart(function(){
      $(this).html("Loading...");
      $(this).show();
    });
      
    $(".load").ajaxStop(function(){
      $(this).html("Loaded");
      $(this).fadeOut(1000);
    });
    
    $(".clickMe").click(function(){
      
      $(".clickMe").children("td").removeClass("active");
      $(".clickMe").children("td").addClass("content");
    
      $(this).children("td").removeClass("content");
      $(this).children("td").addClass("active");
      
      var c_id = $(this).attr('id');
      
      $.getJSON("../game/crime.php", { json: "1", crime: c_id, hash: hash }, function(j) {
        
        if(j.error == '1'){
          $("#jData").html("Invalid Selection, Debug: " + j.option);
          $("#jData").css("border","1px solid #fa6c6c");
        } else if(j.error == '2'){
          $("#jData").html("You can not perform another crime yet");
          $("#jData").css("border","1px solid #fa6c6c");
        } else if(j.error == '3'){
          $("#jData").html("You have not unlocked this crime yet");
          $("#jData").css("border","1px solid #fa6c6c");
        } else if(j.error == '4'){
          $("#jData").html("Hash error, please try again");
          $("#jData").css("border","1px solid #fa6c6c");
        } else {
          
          if(j.result == '1'){
            $("#jData").html("<table class='default' style='width: 100%' align='center'><tr><td style='text-align: center;' colspan='2'><img src='" + j.image + "' /></td></tr><tr><td colspan='2'>" + j.text + "</td></tr><td style='width: 50%; text-align: center;'><img src='../images/icons/crime[up].png' />" + j.percent + "% Rank</td><td style='width: 50%; text-align: center;'><img src='../images/icons/crime[up].png' /> $" + addCommas(j.cash) + " <span style='color: #6afcb5'>(+$" + addCommas(j.bonus) + " Bonus)</span></td></tr></table>");
            $("#jData").css("border","1px solid #6afcb5");
          } else {
            $("#jData").html("<table class='default' style='width: 100%' align='center'><tr><td style='text-align: center;' colspan='2'><img src='" + j.image + "' /></td></tr><tr><td colspan='2'>" + j.text + "<br />" + j.jail + "</td></tr><td style='width: 50%; text-align: center;'><img src='../images/icons/crime[up].png' />" + j.percent + "% Rank</td><td style='width: 50%; text-align: center;'><img src='../images/icons/crime[up].png' /> $" + addCommas(j.cash) + " <span style='color: #6afcb5'>(+$" + addCommas(j.bonus) + " Bonus)</span></td></tr></table>");
            $("#jData").css("border","1px solid #fa6c6c");
          }
          
          
          
        }
        
        
      });
      
    });
    
    
    $("#j_crime").click(function(){
      
      $.getJSON("../game/crime.php", { json: "2" }, function(j) {
        
        if(j.crimeType == '1'){
          $("#j_crime").css("border","1px solid #fa6c6c");
          $("#j_crime").html('Use Old Crime Style');
          $("#showNew").fadeIn("slow").css("display","");
          $("#showOld").fadeOut("slow").css("display","none");;
        } else{
          $("#j_crime").css("border","1px solid #6afcb5");
          $("#j_crime").html('Use Default Crime Style');
          $("#showOld").fadeIn("slow").css("display","");
          $("#showNew").fadeOut("slow").css("display","none");;
        }
        
      });
      
      
      
    });
    
    
  });
  </script>

If someone could explain, how bits work on it aswell that would be great!

Cheers!  ;D

Offline CygnusX

  • Level 24
  • *
  • Posts: 303
  • Reputation: +3/-2
    • View Profile
    • Lords of Midnight
Re: JSON and php.. hmm
« Reply #1 on: June 25, 2011, 12:04:56 PM »
I'm not quite sure what you're asking.  Is this code something you wrote, but isn't working as intended, or code you pulled off another page that you want an explanation for how it works?

Offline GreenLantern

  • Level 2
  • *
  • Posts: 5
  • Reputation: +0/-0
    • View Profile
Re: JSON and php.. hmm
« Reply #2 on: June 25, 2011, 05:01:28 PM »
Code i pulled off another page so i can get an explanation how it would work, and how it would with php, if possible?
So yeah, the second bit of what you said :)

Offline CygnusX

  • Level 24
  • *
  • Posts: 303
  • Reputation: +3/-2
    • View Profile
    • Lords of Midnight
Re: JSON and php.. hmm
« Reply #3 on: June 25, 2011, 05:40:20 PM »
Well, this is all javascript.  Specifically, it is jquery, a sort of plugin for your site written in javascript.  If you're not familiar with it, I'd suggest you study a few JS and jQuery tutotials. 

To give you the basics, Javascript works locally.  This is valuable because it sheds load from the server onto the user's pc.  As a result, you save server power and can perform the function more quickly... a win win for everyone.  From here, jQuery is a plugin which adds lots of nice effects and allows you to write nice looking features much more quickly.  The $('.class'), for example, is equivilant to saying document.getelementbyID(.class).  The .click is a jQuery function that says 'when the user clicks this class, do the following {  } .  So, basically:

 $(document).ready(function(){   // when the document is loaded


 $(".clickMe").click(function(){   //when the user clicks class .clickME (after the page is loaded)

 $.getJSON("../game/crime.php", { json: "1", crime: c_id, hash: hash }, function(j) {  //send the following info to my php script

$("#jData").html("Invalid Selection, Debug: " + j.option);   // insert into class jData the text "invalid....." etc

the last big has some extra spice to it.  The getJSON call to the crime.php script will take data from the script and store it in the variable j.  From php, there is an echo json_encode($MyPHPArray); at the end of the code.  This formats the data in your $MyPHPArray as JSON syntax, allowing jQuery to access it via j.Var1, j.Var2, j.MyVar6, etc.

enjoy.

Offline Harkins

  • Level 28
  • **
  • Posts: 424
  • Reputation: +11/-2
  • Coder, blogger, entrepreneur.
    • View Profile
    • Push CX - Blog
Re: JSON and php.. hmm
« Reply #4 on: June 26, 2011, 05:50:35 PM »
http://jqfundamentals.com/ is a good way to learn JavaScript and jQuery.

Visit #bbg on irc.freenode.net to talk browser games anytime.

Offline GreenLantern

  • Level 2
  • *
  • Posts: 5
  • Reputation: +0/-0
    • View Profile
Re: JSON and php.. hmm
« Reply #5 on: July 17, 2011, 05:27:31 AM »
Well, this is all javascript.  Specifically, it is jquery, a sort of plugin for your site written in javascript.  If you're not familiar with it, I'd suggest you study a few JS and jQuery tutotials. 

To give you the basics, Javascript works locally.  This is valuable because it sheds load from the server onto the user's pc.  As a result, you save server power and can perform the function more quickly... a win win for everyone.  From here, jQuery is a plugin which adds lots of nice effects and allows you to write nice looking features much more quickly.  The $('.class'), for example, is equivilant to saying document.getelementbyID(.class).  The .click is a jQuery function that says 'when the user clicks this class, do the following {  } .  So, basically:

 $(document).ready(function(){   // when the document is loaded


 $(".clickMe").click(function(){   //when the user clicks class .clickME (after the page is loaded)

 $.getJSON("../game/crime.php", { json: "1", crime: c_id, hash: hash }, function(j) {  //send the following info to my php script

$("#jData").html("Invalid Selection, Debug: " + j.option);   // insert into class jData the text "invalid....." etc

the last big has some extra spice to it.  The getJSON call to the crime.php script will take data from the script and store it in the variable j.  From php, there is an echo json_encode($MyPHPArray); at the end of the code.  This formats the data in your $MyPHPArray as JSON syntax, allowing jQuery to access it via j.Var1, j.Var2, j.MyVar6, etc.

enjoy.


Yeah what i dont get is how its getting the Infomation, i know its fetching it from the JSON in the page,
i understand most of the JQuery bit, but what i dont get, is that most people use $_GET and will have it like ?crime=1 or something?

how does this one work? im actually quite interested in learning about JSON, i see it can be very useful, but i haven't yet found a webpage that explains these sorts of bits..

Offline Nox

  • Level 35
  • **
  • Posts: 767
  • Reputation: +12/-2
    • View Profile
Re: JSON and php.. hmm
« Reply #6 on: July 17, 2011, 08:54:44 AM »
It seems to me you're rather having problems with AJAX then JSON... JSON is just a data format like CSV, XML etc.

AJAX is actually *very* simple: When you browse websites in your browser, the browser makes requests for websites. Here instead you clicking/using address bar it's the JS that sends a request and the website contents (the output, what you see in "Show source" in context menu in browser) is passed into JS variable

The getJSON only does that - it expects the output not to be a page but a string in JSON format and it parses it for you
($.getJSON is only a shorthand for a function $.ajax with certain settings - see the manual)

Simple example:
getPlayers.php
Code: [Select]
<?php
$players 
= array( array("name" => "Nox""hp" => 100), array("name" => "foo""hp" => 1));

echo 
json_encode($players); /* accessing this file would not output a normal page, just a blank screen with this text,
the $players array formatted to JSON */
page.js
Code: [Select]
$("#refreshPlayers").click(function(){
  $.getJSON(
    "./get_players.php", // here we'll request the page above and get the string
    function(data) { // when the request is successful
      var string = "";

      for(var i in data)
         string += "<b>"+data[i].name+"<b> ("+data[i].hp+")<br>";

      $(this).find("p").text( string );
    }
});
Meet us at an IRC irc.freenode.net #bbg as well
https://vimeo.com/36579366 (a must-watch) | Join BOINC - no longer a hype, but you can help never the less

Offline GreenLantern

  • Level 2
  • *
  • Posts: 5
  • Reputation: +0/-0
    • View Profile
Re: JSON and php.. hmm
« Reply #7 on: July 17, 2011, 09:05:38 AM »
It seems to me you're rather having problems with AJAX then JSON... JSON is just a data format like CSV, XML etc.

AJAX is actually *very* simple: When you browse websites in your browser, the browser makes requests for websites. Here instead you clicking/using address bar it's the JS that sends a request and the website contents (the output, what you see in "Show source" in context menu in browser) is passed into JS variable

The getJSON only does that - it expects the output not to be a page but a string in JSON format and it parses it for you
($.getJSON is only a shorthand for a function $.ajax with certain settings - see the manual)

Simple example:
getPlayers.php
Code: [Select]
<?php
$players 
= array( array("name" => "Nox""hp" => 100), array("name" => "foo""hp" => 1));

echo 
json_encode($players); /* accessing this file would not output a normal page, just a blank screen with this text,
the $players array formatted to JSON */
page.js
Code: [Select]
$("#refreshPlayers").click(function(){
  $.getJSON(
    "./get_players.php", // here we'll request the page above and get the string
    function(data) { // when the request is successful
      var string = "";

      for(var i in data)
         string += "<b>"+data[i].name+"<b> ("+data[i].hp+")<br>";

      $(this).find("p").text( string );
    }
});

Yeah i get that,

its just certain bits i dont get, like the bold bits { json: "1", crime: c_id, hash: hash }, function(j)
I can kind of see how it works though, and plus is there a way of not echo'ing it, but the page just getting what it needs from the JSON?

And the way the errors are shown, how will they be done? im guessing like php, with json bits to it?

Offline Nox

  • Level 35
  • **
  • Posts: 767
  • Reputation: +12/-2
    • View Profile
Re: JSON and php.. hmm
« Reply #8 on: July 17, 2011, 09:58:31 AM »
1)
1st is data = "Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests."
2nd is the success handler with data as argument (here it's just stupidly named "j") - function triggered on successful data acquisition

2)
given this question 'm not all that sure you get that... JS gets what PHP echoes (or other HTML content if it's present), what you can see when you access the file via browser yourself

3)
if you mean PHP errors being output... yea you have to handle it the way that errors are not output but logged into a file
Meet us at an IRC irc.freenode.net #bbg as well
https://vimeo.com/36579366 (a must-watch) | Join BOINC - no longer a hype, but you can help never the less

Offline GreenLantern

  • Level 2
  • *
  • Posts: 5
  • Reputation: +0/-0
    • View Profile
Re: JSON and php.. hmm
« Reply #9 on: July 17, 2011, 10:40:54 AM »
1)
1st is data = "Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests."
2nd is the success handler with data as argument (here it's just stupidly named "j") - function triggered on successful data acquisition

2)
given this question 'm not all that sure you get that... JS gets what PHP echoes (or other HTML content if it's present), what you can see when you access the file via browser yourself

3)
if you mean PHP errors being output... yea you have to handle it the way that errors are not output but logged into a file

Is there a way of not echoing it out for the public to see the info if they have any type of web development experience?
Like just using some kind of error handler in the PHP, then using the JQuery to show it?

And could you show me a way of doing this? :)

Offline Nox

  • Level 35
  • **
  • Posts: 767
  • Reputation: +12/-2
    • View Profile
Re: JSON and php.. hmm
« Reply #10 on: July 17, 2011, 12:43:29 PM »
All the common authentication and authorization procedures done should have been done before the execution reaches this file ... and any other PHP file accessible from outside (which when using frameworks is usually just one file - index.php)
=> therefore only a user authorized to see them can see them and he should see only the data availible to him... no harm done if accessed directly via browser

@errors: Recoverable errors should just be logged to file (use set_error_handler, set_exception_handler), on an unrecoverable error you should probably return HTTP error code, probably 500, via header()

edited: typo
Meet us at an IRC irc.freenode.net #bbg as well
https://vimeo.com/36579366 (a must-watch) | Join BOINC - no longer a hype, but you can help never the less

 


SimplePortal 2.3.3 © 2008-2010, SimplePortal