Passing Result from PHP to JavaScript with AJAX & jQuery

This free HTML JavaScript tutorial guides you how to use AJAX and the JavaScript framework jQuery to pass the return data from PHP to JavaScript. Please go to the full post page for detailed PHP and JavaScript instructions and JavaScript example codes.

Read more HTML JavaScript tutorials about PHP in JavaScript on jsB@nk:
- PHP print_r function in JavaScript


Sampled by © JavaScriptBank.com

One of my readers recently asked how to pass an array or another variable from PHP to JavaScript. This is a question I've seen all over the internet, and the quick and dirty answer is that you can't... at least not directly. This is because PHP is run on the server-side, and JavaScript is run on the client side (except in rare, experimental cases). You cannot call a JavaScript function, or access a JavaScript variable directly from PHP because they run in completely different locations (among other reasons).

That said, here's what you can do to share data between PHP and JavaScript:

  • Generate the JavaScript using PHP, just like you do HTML
  • Use AJAX to send data from JavaScript to PHP and vice versa

Neither of these methods fully qualifies as "passing variables" like you would when calling a function with parameters, but they do involve sending and retrieving data, which can be created from and/or parsed into variables for any given language.

Generate the JavaScript with PHP

<script>

  var my_number = <?php echo 123; ?>;
  var my_string  = "<?php echo "foo"; ?>";
  var my_array  = <?php echo json_encode( array( "foo", "bar", "baz" ) ); ?>;
  var my_object = <?php echo json_encode( array( "foo" => "bar" ) ); ?>;
</script>

The code above generates JavaScript variables using PHP. This is the easiest way to control JavaScript using PHP. Numbers and strings are pretty simple. For more complex variables, like arrays, the json_encode function can help. It basically converts a PHP data structure into JavaScript code. This use case isn't exactly what it was intended for (more on that later), but it's quite handy in this circumstance.

The php code above will generate the following JavaScript code when executed:

<script>

  var my_number = 123;
  var my_string  = "foo";
  var my_array  = [ "foo", "bar", "baz" ];
  var my_object = { "foo": "bar" };
</script>

As you can see, you now have four JavaScript variables created from data contained in your php script. All you have to do is make sure that you convert your data into valid JavaScript code!

AJAX / Forms / Links

The other (usually better) way to share data between PHP and JavaScript is by using HTTP Requests to send and retrieve information from the web server. Whenever you click a link or submit a form on a web site, a request is sent from the client to the server, and the server sends a response back to the client. Thus, you can send data on a request and receive data from the response. Back in the day, this was done with links and forms only, but now we have AJAX. AJAX is not so much a feature of JavaScript as it is a technique of using the XMLHttpRequest object to send and retrieve data from the server. Basically the idea is that you can send a request using JavaScript, the server sends a response, and the response text is then handed back to the JavaScript code. For more information on AJAX, I highly recommend reviewing the AJAX Tutorial at w3schools.com.

Here's a sample PHP script that returns a random number between 0 and 100:

<?php echo rand(0,100); ?>

And here's some JavaScript code that makes a request to the PHP script on the web server (using the jQuery library's "get" function):

<script>

  // Note: this script sample uses the jQuery library for simplification
  jQuery.get( 'random.php', function ( data ) {
    alert( "here's a random number: " + data );
  });
</script>

The code above makes a GET request to the web server for the random.php script, which is then executed by the server and the response is sent from server to client. When the response is received, the anonymous function is called and passed the response text, which in this case is simply a random number from 0 to 100.

Note: PHP is not the only language these techniques apply to. Any language that can be executed on the server-side applies, my personal favorite being Perl. In addition, there are many formats for data transfer, the most notable being plain text, XML, and JSON.

Language
Translate this page to English Translate this page to French Translate this page to Vietnamese

Recent articles
How to open a car sharing service
Vue developer as a vital part of every software team
Vue.js developers: hire them, use them and get ahead of the competition
3 Reasons Why Java is so Popular
Migrate to Angular: why and how you should do it
The Possible Working Methods of Python Ideology
JavaScript Research Paper: 6 Writing Tips to Craft a Masterpiece
Learning How to Make Use of New Marketing Trends
5 Important Elements of an E-commerce Website
How To Create A Successful Prototype For Your PCB


Top view articles
Top 10 Beautiful Christmas Countdown Timers
Adding JavaScript to WordPress Effectively with JavaScript Localization feature
65 Free JavaScript Photo Gallery Solutions
16 Free Code Syntax Highlighters by Javascript For Better Programming
Best Free Linux Web Programming Editors
Top 10 Best JavaScript eBooks that Beginners should Learn
Top 50 Most Addictive and Popular Facebook mini games
More 30 Excellent JavaScript/AJAX based Photo Galleries to Boost your Sites
Top 10 Free Web Chat box Plug-ins and Add-ons
The Ultimate JavaScript Tutorial in Web Design


Free JavaScript Tutorials & Articles
at www.JavaScriptBank.com