Combining PHP and JavaScript question

I know I can do something like this:

<script>
	$(function() {
		alert ("I got here");
		<?php echo "alert('And here!');" ?>
	});
</script>

Open in new window


I'm actually generating JavaScript code resulting in two alert() functions in a row that will execute just fine.

But being new to this platform, my question is, is this the only way I can make PHP work with JavaScript? Let's say I had an array of 3 (or could be 300!) elements in PHP, and I somehow wanted it placed into an array in JavaScript. Would my only choice be to generate JavaScript code that would look like this:

 <? php echo 'var a=new Array();'; echo 'a.push(' . phpArray[0] . '); a.push(' . phpArray[1] . '); a.push(' . phpArray[2] . ');' ?>

Open in new window


I didn't actually test the above line, but you get the idea. Is this the only way I can ever get PHP and JavaScript to work together? Because I know PHP scriptlets will work with HTML but not JavaScript. I'm hoping maybe there's an easier way to do this, so does anyone have any suggestions/recommendations?

Thanks.
elepilAsked:
Who is Participating?
 
Ray PaseurCommented:
Let's start with this one.  It shows how to make an array in PHP and turn it into a JSON string.
http://iconoun.com/demo/temp_elepil_1.php
<?php // demo/temp_elepil_1.php

/**
 * Demonstrate JSON for client/server communication
 * See: http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28654282.html
 */
error_reporting(E_ALL);


$thing = [ 'Dave', 'Ray', 'Elepil' ];
$json  = json_encode($thing);

// SHOW THE DATA STRUCTURES
echo '<pre>';
var_dump($thing);
var_dump($json);

Open in new window

0
 
Dave BaldwinFixer of ProblemsCommented:
Everything in an HTML page is just text to PHP.  This is how I would do it.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" >
<title>JS Arrays</title>
</head>
<body>
<h1>JS Arrays</h1>
<script type="text/javascript">
<!--
<?php 
$loc = array();
$loc['downtown'] = array("Alex","Bob","Ray");
$loc['midtown'] = array("Dave");
$loc['uptown'] = array("Cleopatra","Jessica");

echo "var loc = [";
echo '["'.$loc['downtown'][0].'","',$loc['downtown'][1].'","'.$loc['downtown'][2].'"],';
echo '["',$loc['midtown'][0].'"],';
echo '["'.$loc['uptown'][0].'","'.$loc['uptown'][1].'"]';
echo '];';

 ?>

for(i=0;i<loc.length;i++) {
	document.write("loc[" + i +"].length = " + loc[i].length + "<br>");
	}

// -->
</script>
</body>
</html>

Open in new window

0
 
elepilAuthor Commented:
To Dave Baldwin. Thanks for responding.

Hmm... so you pretty much did it the same way as I did -- generating JavaScript ready code for JavaScript to execute on the client side.

Is that the only way? I was hoping there were some convenience functions in PHP or JavaScript that made this easier.
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

 
Dave BaldwinFixer of ProblemsCommented:
"convenience functions"?  Looks pretty basic to me.  Depending on your data, there are other ways to use a loop in PHP to put the values into the javascript array.  But pretty much that what you have to do.  I suppose you could generate a JSON string in PHP but that would still require extra processing in javascript to make use of it.
0
 
elepilAuthor Commented:
To Dave Baldwin.

Well, if there's anything I learned about PHP, it has a lot of unexpected convenience functions, some are even called "magic" functions like __get() and _set(), which I thought were wonderful! PHP even has functions like explode() and implode(), things I normally had to do myself in other languages. But to give another good example, I particularly like file_get_contents($file_name), which does an fopen, gets the filesize of $file_name, then freads all the bytes in, then fclose the file and returns the results. That's many operations all bundled up into one, something I had to create a function for in Java. Even PHP's string functions come with such great diversity I haven't seen in other languages before, like the ucfirst() that capitalizes the first letter or ucwords() that capitalizes every word. If there's anything I've come to realize learning PHP, it has such a plethora of functions, a good number of which simplifies even the smallest thing, repeatedly surprising me because they did very "basic" things.

With PHP, I've been conditioned to always google first for a tedious functionality before coding, hoping there is already some function that would alleviate a cumbersome task. But I couldn't find one pertaining to my question. So I'm here. :)
0
 
Dave BaldwinFixer of ProblemsCommented:
I don't know of any easier way.  I work with a lot of forms that put info into databases.  One I'm working on right now had about 25 fields that have to also be copied in $_SESSION variables so they are available on several other pages.  I often feel that if it wasn't for the special knowledge required, programming would be a secretarial job, cutting, copying, pasting, and editing all day long.
0
 
elepilAuthor Commented:
To Dave Baldwin.

Ah, I've had those. But I simplify it by putting all in some object (e.g. class, array, etc.) and just store the object in the session. First time is tedious, but all subsequent times are just copy/paste.
0
 
Dave BaldwinFixer of ProblemsCommented:
See?  Like I said, we're secretaries with specialized knowledge.  Oh... don't tell anyone else that!
0
 
Ray PaseurCommented:
@Dave: Hahahaha!

@elepil: I have to run some errands now, so it may be a little bit before I can give you an example, but from the sound of things you might want to learn about JSON.  It's how we exchange data between the client (HTML, CSS, JavaScript) and the server (PHP, MySQL).
http://json.org/
http://php.net/manual/en/book.json.php

There are some reasons to avoid storing a PHP object in the PHP session.  It's a long story, but sometimes it does not work out very well.  However you can store JSON with no trouble at all, and you can use JSON directly in JavaScript.
http://php.net/manual/en/function.unserialize.php#112823
0
 
Ray PaseurCommented:
This does something nearly the same, but it casts the array into the form of a PHP object.
http://iconoun.com/demo/temp_elepil_2.php
<?php // demo/temp_elepil_2.php

/**
 * Demonstrate JSON for client/server communication
 * See: http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28654282.html
 */
error_reporting(E_ALL);


$thing = [ 'Dave', 'Ray', 'Elepil' ];
$thing = (object)$thing;
$json  = json_encode($thing);

// SHOW THE DATA STRUCTURES
echo '<pre>';
var_dump($thing);
var_dump($json);

Open in new window

The output of the json_encode() function is a JSON object, and because there are not any named keys, PHP inserts the numeric array indexes, in quotes, to satisfy the requirement for keys.  The JSON array and/or object is exactly the same representation that is used in JavaScript.  If you find that slightly amazing, you're certainly not alone!
0
 
Ray PaseurCommented:
Here is an example of a JSON object with named keys.
http://iconoun.com/demo/temp_elepil_3.php
<?php // demo/temp_elepil_3.php

/**
 * Demonstrate JSON for client/server communication
 * See: http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28654282.html
 */
error_reporting(E_ALL);


$thing = new StdClass;
$thing->Dave   = 'Baldwin';
$thing->Ray    = 'Paseur';
$thing->eeUser = 'Elepil';
$json  = json_encode($thing);

// SHOW THE DATA STRUCTURES
echo '<pre>';
var_dump($thing);
var_dump($json);

Open in new window

0
 
Ray PaseurCommented:
Here, we use the object with the named keys.  We create this JavaScript object inside our PHP script and use PHP's HEREDOC notation to inject the JavaScript object into the HTML string.  Then we write the HTML string to the browser.  When the script runs, it triggers the JS alert().  While we created the JavaScript object in clear text in this example, we could just as well have created it from PHP software, the way we did in the last example.
http://iconoun.com/demo/temp_elepil_4.php
<?php // demo/temp_elepil_4.php

/**
 * Demonstrate JSON for client/server communication
 * See: http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28654282.html
 */
error_reporting(E_ALL);


// CREATE OUR DATA STRUCTURE IN JSON NOTATION
$js_object = <<<EOD
{"Dave":"Baldwin","Ray":"Paseur","eeUser":"Elepil"}
EOD;

// CREATE OUR WEB PAGE IN HTML5 FORMAT
$htm = <<<HTML5
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<meta name="robots" content="noindex, nofollow" />
<title>HTML5 Page With JavaScript Alerts in UTF-8 Encoding</title>
</head>
<body>
<noscript>Your browsing experience will be much better with JavaScript enabled!</noscript>

<script>
var thing = $js_object;
alert( thing.Dave + ' ' + thing.eeUser );
</script>

<span>All Done!</span>

</body>
</html>
HTML5;

// RENDER THE WEB PAGE
echo $htm;

Open in new window

0
 
Ray PaseurCommented:
The next part of the story is a two-part combination using JSON to communicate from the server to the client.  This is the server side of the script.  It expects a GET-method request and returns a JSON response, which as we have seen above, is just a specially formatted string representation of the data.  You can run this standalone to see how it works - just put the URL in a browser address bar.
http://iconoun.com/demo/temp_elepil_5.php?q=Ray
<?php // demo/temp_elepil_5.php

/**
 * Demonstrate JSON for client/server communication
 * See: http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28654282.html
 */
error_reporting(E_ALL);


// RECEIVE THE REQUEST DATA
$q = !empty($_GET['q']) ? trim(strtoupper($_GET['q'])) : 'Empty';

// PREPARE A RESPONSE OBJECT
$t = date('c');
$o = new StdClass;
$o->q = $q;
$o->t = $t;
$r = json_encode($o);
echo $r;

Open in new window

0
 
Ray PaseurCommented:
And here is the client side script that communicates to the server with a GET-method request and receives a JSON response.  The JSON response is parsed by jquery.getJSON() and used in the HTML document as well as in an alert().
http://iconoun.com/demo/temp_elepil_6.php
<?php // demo/temp_elepil_6.php

/**
 * Demonstrate JSON for client/server communication
 * See: http://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28654282.html
 */
error_reporting(E_ALL);


$htm = <<<EOD
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<title>Ajax Example Using jQuery</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

<script>
$(document).ready(function(){
    $("#signal").click(function(){
        indata = $("#xinput").val();
        $.getJSON("temp_elepil_5.php", {q:indata}, function(jsobj){
            $("#output").html("Time: " + jsobj.t + " Name: " + jsobj.q );
            alert( jsobj.q + ' ' + jsobj.t );
        });
    });
});
</script>

</head>
<body>

<input id="xinput" placeholder="Please enter your name here" />
<div   id="signal">...and then click here</div>
<div   id="output">
</div>

</body>
</html>
EOD;

echo $htm;

Open in new window

0
 
elepilAuthor Commented:
Thanks for the help, guys.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.