Parsing a Separate PHP Array in Javascript - php

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?

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>

Related

how to pass javascript array to php

I want to pass array myWorkout to 'play_workout.php'.
I want 'play_workout.php' to open and display the contents of myWorkout (for this example).
(Once I see that this is working I will parse the data from myWorkout and write it back to a database).
I'm not getting any errors in firebug, but play_workout is not being opened nor is is capturing the array object myWorkout.
I would appreciate a second glance at this.
Thanks as always!
page workout_now.php
<div id="playworkout"><button onClick="playWorkout()">Play Workout</button></div>
JAVASCRIPT
function playWorkout(){
var arr = $("#dropTargetframe > li").map(function(){
return $(this).attr('data-id');}).get();
var myRoutine = arr;
var myWorkout = new Array();
for (var i in myRoutine){
if (myRoutine[i])
myWorkout.push(myRoutine[i]);
}
//array appears like ["4", "5", "1", "4"]
JSON.stringify(myWorkout);
encodeURIComponent(myWorkout);
var url = "http://localhost/RealCardio/play_workout.php";
$.get(url, myWorkout);
page play_workout.php
<?php
...
$arrayWorkout = json_decode($_REQUEST['myWorkout']);
print_r($arrayWorkout);
...
?>
Assuming, that as in your comment the array elements doesn't contain any special chars, just numbers, simply do
var myWorkoutPost=myWorkout.join('x');
Transport this to the server the way you want (form hidden field, AJAX, ..) and in PHP do
$myWorkout=explode('x',$_REQUEST['myWorkoutPost']);
Both PHP and Javascript use JSON encoding so I would say the best way would be to JSON encode the array and then POST it as a hidden field to the PHP page and use JSON decode.
http://www.php.net/manual/en/function.json-decode.php
Encode this array to JSON, send it to php script and recieve it with $_POST.
Finally, decode JSON in php script.
A work flow for almost every structured values 99% of the time it will do.
Use JSON.stringify([1,2,3]) it will give you a string "[1,2,3]".
Encode it with encodeURIComponent("[1,2,3]") you'll have something like this "%5B1%2C2%2C3%5D"
Now it's save to be sent to PHP or any other server side language try to use XMLHttpRequest or better jQuery.get() to send the values to PHP.
In php you'd do this:
- $arrayOfValues = json_decode($_REQUEST['name_of_parameter']);
- print_r($arrayOfValues);
Normally you'd need to include JSON library to support old browsers. More info on JSON.

return a large amount of html (with a couple of variables) via ajax?

I have an ajax function search for keywords in a big database. The php being called simply says "no" if there's nothing, but if there are found records, it goes ahead and creates all of the HTML and returns the html, so that AJAX only needs to put the returned text into the html of a div. My problem is that I'd like to pass along a couple of variables, like the number of records found, etc.
So if I tried to put it in a statement that javascript could eval, I'm afraid that not only is all of the html potentially big enough to cause some sort of variable problems, but it also has a lot of single and double quotes, etc, that could unexpectedly end the variable before it's supposed to. See the following
// (I know I don't have a single quote after data and that will break it. This is just an example
echo "{ status: 'success', total: '".count($relevance)."' data: ";
foreach ($relevance as $re) {
// tons of html is printed here
}
echo " }";
So the question is, how do I most effectively send back a whole gang of html code, along with some variables that can be easily eval'ed by JS?
Use json_encode This will eliminate any errors you might have in trying to create your own json.
$returnArray = array(
'status'=>'success',
'total' => count($relevance),
'data' => ''
);
foreach ($relevance as $re) {
$returnArray['data'] .= $re; // + all long html code
}
echo json_encode($returnArray);
You can encode the data as JSON and then put it in a <script> block that's got a non-JavaScript type. Give the script a class too so your code can look for it easily. You can then get the ".innerHTML" of the <script> element and decode the JSON. Then just add the <script> to the rest of the HTML you're returning.
edit No use #Neal's answer instead; it's a less goofy idea. I've done what I've described but usually that's because for some other (framework) reason it's not easy (or just inconvenient) to get directly at the
response data. Also, I generally generate pages via JSP, so it's much easier to drop JSON into a page than to get the page contents into Java.
To elaborate, a <script> block like this:
<script type='text/json' class='some-data-for-you'>
{ "hello": "world" }
</script>
will be ignored by the browser because the "type" won't be recognized as code. Then your JavaScript code can just look for <script> elements with class "some-data-for-you" in the returned content and then parse the ".innerHTML" with a JSON parser.

Parsing MySQL into JavaScript Arrays through PHP and jQuery

Ultimate Goal: I want to take data I keep in a MySQL Database and put it into an Array of Arrays in JavaScript, so it can be manipulated client side.
So far, I have been able to pull data from my database with this code:
<?php
...
$num=1;
$q = "SELECT blah1, blah2, blah3 WHERE blah4=$num";
$sth = mysqli_query ($database, $q);
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
?>
(from: JSON encode MySQL results)
This is where I am stuck, because I am having trouble getting this data into JavaScript.
One solution I can find is Parsing a Separate PHP Array in Javascript:
<script>
var jsonarray = <?php echo json_encode($array); ?>;
// now you can use jsonarray in your javascript
</script>
But the problem with this implementation is that it would spit out all of the database content I query onto the source-code of the page. If I have to do this, I might as well skip the database and just keep all of the content in javascript.
I am thinking there must be a way with jQuery/AJAX to pass the value of $num to a PHP script, grab this data and put it into a JavaScript Array without having to output all of it to the page.
Any assistance would be appreciated.
Thank you!
This solution you posted:
<script>
var jsonarray = <?php echo json_encode($array); ?>;
// now you can use jsonarray in your javascript
</script>
Is actually a very good approach. Using AJAX is drastically slower (because of network latency).
Unless you really need AJAX for some reason, you should avoid using it. It will add a noticeable split second of load time to the page, often for no benefit at all.
Above all when structuring your page, you want to try and reduce the number of individual network requests between the browser and the server. The less requests the faster your page will be. This is especially true for javascript and ajax, because they are unpredictable and browsers find it very difficult to optimise any part of the page where it's being used.
We're talking about one quarter of a second compared to one millionth of a second, for exactly the same end result.
Making an AJAX call with jQuery is easy enough. Take a look at the documentation: http://api.jquery.com/jQuery.get/
You can also do this without AJAX
var jsonarray = eval(<?php echo json_encode($array); ?>);

AJAX calling a PHP code and getting a response every few minutes

I'm trying to create a very simple message board (author, text, and date written) that will auto-update every few moments to see if a new message has arrived, and if it has, auto load the latest message(s).
I'm proficient in PHP, but my knowledge in AJAX is lacking.
The way I see it, I would have to create a PHP file called get_messages.php that would connect to a database and get through a $_GET variable return all posts beyond date X, and then I would somehow through jquery call this PHP file every few minutes with $_GET=current time?
Does this sound correct?
How would I got about requesting and returning the data to the web page asynchronously?
You're pretty close, you'll need a PHP script that can query the database for your results. Next, you'll want to transfigure those results into an array, and json_encode() them:
$results = getMyResults();
/* Assume this produce the following Array:
Array(
"id" => "128","authorid" => "12","posttime" => "12:53pm",
"comment" => "I completely agree! Stackoverflow FTW!"
);
*/
print json_encode($results);
/* We'll end up with the following JSON:
{
{"id":"128"},{"authorid":"12"},{"posttime":"12:53pm"},
{"comment":"I completely agree! Stackoverflow FTW!"}
}
*/
Once these results are in JSON format, you can better handle them with javascript. Using jQuery's ajax functionality, we can do the following:
setInterval("update()", 10000); /* Call server every 10 seconds */
function update() {
$.get("serverScript.php", {}, function (response) {
/* 'response' is our JSON */
alert(response.comment);
}, "json");
}
Now that you've got your data within javascript ('response'), you are free to use the information from the server.
Ignore the ASP.NET stuff, this link is a good start:
http://www.aspcode.net/Timed-Ajax-calls-with-JQuery-and-ASPNET.aspx
What you're going to use is a javascript function called setTimeout, which asynchronously calls a javascript function on an interval. From there, jQuery has a fancy function called "load" that will load the results of an AJAX call into a DIV or whatever element you're looking for. There are also numerous other ways to get jQuery to do alter the DOM the way you'd like.
There are a hundred ways to do this, but I'd say avoid writing plain Javascript to save yourself the headache of cross-browser functionality when you can.
I suggest you go for the Simple AJAX Code-Kit (SACK) available on Google code.
I've been using it since before it was on Google code. It's very light and straightforward. It's one js file that you have to include. I've seen it being used in online browser games as well.
http://code.google.com/p/tw-sack/
Example for loading page contents from get_messages.php in a div (if you don't care about the page contents from get_messages.php, and simply want to call the php file, simple remove the ajax.element line):
<script type="text/javascript" src="tw-sack.js"></script>
<script>
var ajax = new sack();
ajax.method = "GET"; // Can also be set to POST
ajax.element = 'my_messages'; // Remove to make a simple "ping" type of request
ajax.requestFile = "get_messages.php";
ajax.setVar("user_name","bobby");
ajax.setVar("other_variables","hello world");
ajax.setVar("time",dateObject.getTime());
ajax.onCompleted = whenCompleted;
ajax.runAJAX();
function whenCompleted(){
alert('completed');
}
</script>
<div id="my_messages">Loading...</div>
You don't need to specify an "ajax.element" if you want to do a simple "ping" type of request and ignore the output of the php file. All you have to do to implement your requirements now is to use a "setTimeout" making the ajax calls.
There are also many other options like:
//ajax.onLoading = whenLoading;
//ajax.onLoaded = whenLoaded;
//ajax.onInteractive = whenInteractive;
No need to learn or include huge frameworks. And you'll get started in no time with tw-sack.

Multiple responses from one AJAX request

Not really looking for code examples here, just concepts.
I have three sections on a page now that are being updated via three separate AJAX calls to PHP scripts, which return JSON. What would be the easiest way to condense these three calls into one larger call and receive the responses back on the client in JSON? How would I separate the responses on the client so I can manipulate the response data based on what information is sent back?
I like Cris' method, but think I can provide a little improvement. As you already have 3 seperate entities, to reduce the need for recoding everything, you could do something along the lines of combining you PHP into one file via include 'page.php' and sending an object back via JSON with properties named for what each of them do (lets say "names", "dates", and "fuzzyThings"). Your client code to send the request would then simply have all the arguments your 3 functions sent individually being sent in one request. The returned JSON would then look something like this (put your objects/arrays/whatever in the commented areas):
{
"names" : {/*stuff needed for names goes in here*/},
"dates" : {/*stuff needed for dates goes in here*/},
"fuzzyThings" : {/*all fuzzy things goes in here*/}
}
Once you get this to the client side, as I assume each may already have a function (or set of functions) to deal with it's return data, you should be able to call them in this manner:
function handler(retText) {
var returnedObject = eval(retText);
doStuffWithNames(returnedObject.names);
doStuffWithDates(returnedObject.dates);
playWithFuzzyThings(returnedObject.fuzzyThings);
}
Also, on the PHP end you can make a unified PHP page (without recoding anything hopefully) via:
<?php
echo '{';
echo '"names":{';
include 'names.php';
echo '},';
echo '"dates":{';
include 'dates.php';
echo '},';
echo '"fuzzyThings":{';
include 'fuzzyThings.php';
echo '}';
echo '}';
?>
Note: You may need to edit the 3 php pages so that they will check the $_POST correctly and without interfering with the functionality of the other pages if you have not already, I prefer the method of if(isset($_POST['whatever'])) { ... } to check that everything was sent correctly, this way, you can include as many as you want, and if there is nothing to do with a php file (i.e. you are not using that section on that page), then it will return a blank property, and you simply will not use it (basically making it a "one-size-fits-all" type of thing).
Hope it works for ya!
You can format your JSON like this:
"user" : [ {
"name" : "Harry",
"hobby" : "Skating"
}, {
"name" : "Dave",
"hobby" : "Scuba Diving"
} ],
"news" : [ {
"date" : "3/13/05",
"title" : "Blah",
"postedby" : "Mike",
} ]
And now in your AJAX response:
var data = eval('('+ xhr.responseText +')'); // Ajax response
var user = data.user[0].name; // Harry
var user2 = data.user[1].name; // Dave
var title = data.news[0].title;
You can use a for loop to traverse the data. In the example above you should now see how you can use PHP to format your JSON with multiple categories (user, news, ect.) and return back everything with only one call. If you would like a more elaborate example please refer to this article as well as this.
I think you have to make a JSON format according to those 3 sections on the page, ID them so that after response you can populate them to those sections.
I personally like the json method but if you're new to json or don't feel comfortable working with it for any reasons there's a jQuery plugin designed specifically for this purpose called jQuery Taconite Plugin
In Rails community there's a third way called RJS which is not that much hot nowadays and feels a little obsolete but still has its own fans. I'm curious if anybody has ported RJS to PHP or not?
this is workimg for me
php code:
//for test
$categoryName = "category";
$idcategory = "1";
$json = "{'productcategory':[{'categoryname':'".$categoryName."','idcategory':'".$idcategory."'}]}";
echo $json;
javascript:
var str = xmlhttp.responseText.trim();
var json = JSON.stringify(eval("(" + str + ")"));
var obj = JSON.parse(json);
alert(obj.productcategory[0].idcategory);
alert(obj.productcategory[0].categoryname);

Categories