Matt
Matt

Reputation: 23

How to use AJAX and PHP to update a webpage

I'm very new to html/css/javascript/php and everything related. I only really know java. Currently, I have a page set up in html (mattrb.com/cs) that posts data to a php page that calls an api and displays some data. The html is:

<!DOCTYPE html>
<html>
  <head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <meta content="#db5945" name="theme-color">
    <!--<link type="text/css" rel="stylesheet" href="layout-styles.css"/>-->
    <title>float check</title>

    <style>
      body {
        background-color: #222222;
        color: #db5945;
      }

      #footer {
        position: fixed;
        left: 0;
        bottom: 0;
        width: 100%;
        text-align: center;
        color: #042E64;
        background-color: #222222;
        height: 18px;
      }
    </style>
  </head>

  <body>
    <form action="apitest.php" method="post">
      <input type="text" name="id" placeholder="id">
      <input type="submit">
    </form>

    <div id="footer">
      <a href="http://steampowered.com">Powered by Steam</a>
    </div>
  </body>
</html>

and the php file called is:

<html>
<head>
  <meta content="#db5945" name="theme-color">
  <style>
    body {
      background-color: #222222;
      color: #db5945;
    }
  </style>
</head>
<body>
<?php
  $apikey = "XXXXXX-STEAM-API-KEY-XXXXX";

  $input = $_POST["id"];
  while (substr($input, strlen($input) - 1) == "/" || substr($input, strlen($input) - 1) == " ") {
    $input = substr($input, 0, strlen($input) - 1);
  }

  $steamid = "";

  function isInteger($input){
    return(ctype_digit(strval($input)));
  }

  if (strpos($input, "/id/") !== false || isInteger(substr($input, strlen($input) - 17)) == false) {
    $pos = 0;
    if (strpos($input, "/id/") !== false) {
      $pos = strrpos($input, "d/") + 2;
    }

    $vanityurl = substr($input, $pos);
    $steamidAPI = "http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key=" . $apikey . "&vanityurl=" . $vanityurl;
    $responseid = json_decode(file_get_contents($steamidAPI));

    $steamid = $responseid->response->steamid;
  } else {
    $steamid = substr($input, strlen($input) - 17);
  }

  echo("steamid: " . $steamid . "<br><br>");

  $playerItemsAPI = "http://api.steampowered.com/IEconItems_730/GetPlayerItems/v0001/?key=" . $apikey . "&SteamID=" . $steamid;

  do {
    $playerItems = json_decode(file_get_contents($playerItemsAPI));
  } while (is_null($playerItems));

  $inventoryAPI = "http://steamcommunity.com/profiles/" . $steamid . "/inventory/json/730/2";
  $inventory = json_decode(file_get_contents($inventoryAPI));

  $names = array();
  $float = array();
  $cases = 0;
  $keys = 0;

  for ($i = 0; $i < count($playerItems->result->items); $i++) {
    $id = $playerItems->result->items[$i]->id;
    $classid = $inventory->rgInventory->$id->classid;
    $instanceid = $inventory->rgInventory->$id->instanceid;
    $combination = $classid . "_" . $instanceid;
    $name = $inventory->rgDescriptions->$combination->market_name;

    if(substr($name, strlen($name) - 3, strlen($name)) == "Key") {
      $keys++;
    } else if (substr($name, strlen($name) - 4, strlen($name)) == "Case") {
      $cases++;
    } else {
      array_push($names, $name);
      if ($playerItems->result->items[$i]->attributes[2]->defindex == 8) {
        array_push($float, $playerItems->result->items[$i]->attributes[2]->float_value);
      } else {
        array_push($float, 0);
      }
    }
  }

  $tab = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";

  for ($j = 0; $j < count($names); $j++) {
    $someOutput = true;
    echo(strtolower($names[$j]) . "<br>");
    if ($float[$j] != 0) {
      echo($tab . $float[$j] . "<br>");
    }
  }

  echo("items: " . (count($names) + $keys + $cases) . "<br>");
  echo("items discounting keys/cases: " . count($names) . "<br>");
  echo("keys: " . $keys . "<br>");
  echo("cases: " . $cases . "<br>");

  echo("<br>if you expected something to<br>show up and nothing did, check<br>your inventory privacy settings");
?>
</body>
</html>

This is everything I have right now. My goal is to use ajax to update the information on the html page with the data from the php file using ajax without refreshing the page. Is this possible? If so, how would I go about it?

Thanks!

Upvotes: 1

Views: 130

Answers (3)

Misunderstood
Misunderstood

Reputation: 5665

If you want to do it correctly.

There is a lot of ground covered here. There are many very small details that are commonly not adhered to. But then that is why the Internet is such a mess. The blind leading the blind. I took the time to do this because you are new to this. May as well get in some good techniques before the blind get at you.

HTML

<form>
  <legend>ID</legend><input id="id" type="text" name="id" placeholder="id">
  <button type="button" onclick="postit()">Submit</button>
</form>

If you do not want to submit the form, you cannot have a submit button.

JAVASCRIPT

Or you could do it in jQuery. And be kept in the dark. And slow your page load time unnecessarily. And have a nightmare being forced into learning jQuery AND javaScript in order to troubleshoot jQuery issues. Or just simply use javaScript.

<script type="text/javascript">//<![CDATA[
var xmlhttp;
function postit(){
  var id=document.getElementById('id').value;
  xmlhttp=null;
  var Url="apitest.php"
  if (window.XMLHttpRequest) {
      xmlhttp=new XMLHttpRequest();
  }
  else if (window.ActiveXObject) { 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (xmlhttp!=null) {
    xmlhttp.onreadystatechange=getResponse;
     xmlhttp.open("POST", Url, true);
     xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
     xmlhttp.send( "id=" + id);  
  } else {
     alert("UNEXPECTED ERROR: XMLHttpRequest not supported");
  }
}
function getResponse(){
  if (xmlhttp.readyState==4){
    if (xmlhttp.status==200){
      var json = JSON.parse(xmlhttp.responseText);
      var items = json['items'];
      var discount= json['discount'];
      var keys= json['keys'];
      var cases= json['cases'];
    }
    else{
      alert("UNEXPECTED AJAX ERROR: : " + xmlhttp.statusText + "HTTP Status: " + xmlhttp.status);
    }
  }
}
//]]>
</script>

var xmlhttp must be global so it can be used in both functions.

PHP RETURN VALUES

Replace:

  echo("items: " . (count($names) + $keys + $cases) . "<br>");
  echo("items discounting keys/cases: " . count($names) . "<br>");
  echo("keys: " . $keys . "<br>");
  echo("cases: " . $cases . "<br>");

With:

$return['items'] = count($names) + $keys + $cases;
$return['discount'] = count($names) ;
$return['keys'] = $keys ;
$return['cases'] = $cases ;
header(header('Content-Type: text/json; charset=utf-8');
echo json_encode($return);

.


OTHER STUFF I NOTICED

Replace:

  while (substr($input, strlen($input) - 1) == "/" || substr($input, strlen($input) - 1) == " ") {
    $input = substr($input, 0, strlen($input) - 1);
  }

with:

$input = rtrim($_POST["id"]," /");

Change

$inventory = json_decode(file_get_contents($inventoryAPI));
$playerItems = json_decode(file_get_contents($playerItemsAPI));

To

$inventory = json_decode(file_get_contents($inventoryAPI),1);
$playerItems = json_decode(file_get_contents($playerItemsAPI),1);

And now $inventory and $playerItems are arrays.

for ($i = 0; $i < count($playerItems->result->items); $i++) {
  $id = $playerItems->result->items[$i]->id;

Becomes

foreach($playerItems['results']['items'] as $id){

Upvotes: 1

Darren
Darren

Reputation: 13128

You're almost there, now all you need to do is harness jQuery and run an ajax request ($.post()):

jQuery(document).ready(function(){
    jQuery(document).on('submit','form#your_form_id',function(e){
        e.preventDefault();

        // send post/ajax request
        jQuery.post( "apitest.php", jQuery(this).serialize(), function( data ) {
            console.log(data);
        });

        return false;
    });
});

Notes

  • The return false; prevents your form form being submitted via it's normal process. (Means there is no redirecting to the page.)
  • You'll need to include the jQuery library into your project, along with the above javascript file.
  • jQuery(this).serialize() simply formats the form elements as the data to be posted off to the supplied url (apitest.php).
  • You'll have to figure out what you want to do with the data that is returned. Right now it will just log to console via the console.log(data);.
    • The general consensus with this is to use $.html() and append the returned data to a <div> somewhere on your document.
    • The majority of people will send JSON back and handle it properly. You could do this too - it'll allow for easier data manipulation.

Upvotes: 2

In the HTML file, you need a Javascript function to use the ajax call to the PHP file, and the result of the echo php file, put it in a Div in the html document. check this link http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first just change the "ajax_info.txt" for the PHP file, but basically thats how you use an ajax call. Here the basics of the function: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

Upvotes: 0

Related Questions