0

So, as sort of an exercise in learning, I am trying to port a site I was working on for someone, written in PHP, MySQL and CSS, over to Ajax (Specifically, really, just adding Javascript so that the page is dynamic instead of needing to constantly reload).

Unfortunately, I have some scripts I'd like to keep as PHP (for instance, a script to update a database given an array of victims) because I need it to interact with a database, and this means that the array must stay as PHP (I think).

So, given this file,

<?php

$victims = array(

    // Animals
    "chickens",
    "horses",
    "cows",

    // Supernatural
    "werewolves",
    "zombies",
    "vampires",
    "phantoms",

    // Human
    "U.S. Congressmen",
    "performance artists",

    // Inanimate, non-mechanical
    "pieces of fencepost",
    "barnhouses",

    // Mechanical
    "robots",
    "cyborgs"

);

?>

is there a way to reach into that file using Javascript an extract a value?

Or, come to think of it, would it be better to store the list of victims as an XML file so both the PHP and Javascript can read it? Or even, how would I go about doing that?

Andy
  • 3,132
  • 4
  • 36
  • 68
  • You cannot port "PHP to AJAX", they're two different technologies with no overlap in functionality. AJAX, or specifically JavaScript, doesn't "reach into files"; it can only make requests. It's up to your server-side language (PHP) to output data in a form JavaScript can understand, such as XML or JSON. – user229044 Aug 26 '10 at 13:50
  • I'm sorry, I phrased it incorrectly. I'm implementing ajax on my site. I just happen to be rewriting the entire thing. – Andy Aug 26 '10 at 13:53

1 Answers1

4

Read up JSON and check out json_encode() for PHP5.

You can convert a PHP array into JSON, this is a string. Then print that string out into your page and use it with your Javascript

<script>
     var jsonarray = <?php echo json_encode($array); ?>;
     // now you can use jsonarray in your javascript
</script>

This is especially useful when returning data for an Ajax request

<script>
     var jsonarray = <?php echo json_encode(array("status" => "success", "message" => "Something was completed OK")); ?>;
</script>
Jake N
  • 10,535
  • 11
  • 66
  • 112