Communication between PHP and Javascript

Communication between PHP and Javascript

Communication between PHP and Javascript seems to be simple. But in my practice I’ve met many solutions and just few of them seem to be a good practice.
Back end and front end have to cooperate somehow by exchanging data. So let’s consider the situation that we need to send an ajax query or just redirect our page with Javascript. In this example we’ll use JQuery

$(function() {
	$.ajax({
		method: "POST",
		url: someurl,
		data: somedata,
	}).done(function( msg ) {
		alert("Data sent!");
		document.location.href = someurl2
	});
});

To make this example work, we need someurl, somedata and someurl2. We need a way to put some text data in html sticking to such rules:

  1. the html code must be valid for browsers, and for search engines as well,
  2. the data must be easily readable for javascript

Data container

We can add to our HTML a container

<div id="js_data_container" style="display:none;">
	<span class="js-data-someurl">someurl</span>
	<span class="js-data-somedata">somedata</span>
	<span class="js-data-someurl2">someurl2</span>
</div>

and then read those values

$(function() {
	var someurl = $('#js_data_container .js-data-someurl').text();
});

Hidden inputs

The better solution are hidden inputs. There’s no need of using any additional container. It’s important to have a unique class name or other attribute making it easy to handle.

<input class="js-data-someurl" type="hidden" value="someurl" />
<input class="js-data-somedata" type="hidden" value="somedata" />
<input class="js-data-someurl2" type="hidden" value="someurl2" />
$(function() {
	var someurl = $('.js-data-someurl').val();
});

data attribute

Using data attribute is safe for HTML validation. It’s convenient way to describe many similar objects on one page.

<img src="flower.jpg" data-id="12" data-category="plants" />
<img src="wheel.jpg" data-id="32" data-category="cars" />
<img src="shirt.jpg" data-id="634" data-category="clothes" />

JQuery gives a easy interface to read and modify those values

$(function() {
	var category = $('img[data-id="32"]').data('category');
	console.log(category);
});

The sample code above will give an output cars in console. We first select the object with data-id=”32″ and we read its category with a special function $.data(), which works in both ways – as a getter and a setter. Moreover the data attribute is fully valid within HTML5 so there’s no fear to using it.

One Reply to “Communication between PHP and Javascript”

  1. Jade Gardner

    Thank you a bunch for sharing this with all of us you actually recognise what you’re talking about! You can visit our site: http://hirephpdeveloper.co.uk/

Leave a comment

Your email address will not be published. Required fields are marked *