Send variable from PHP to Javascript

I have the following code in two separate files, one of them javascript and the other php:


xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {


$yearFilter = (int)$_REQUEST["yearFilter"];
$dummyvariable = 123245;

I have been using the javascript file to pass variables to php but I cannot figure out how to send a variable (such as the dummyvariable example) from php BACK to the javascript file. I know that result should end up in "this.responseText" but I don't know what code to put in the php file in order to send it there. Can anyone help me with this? I am relatively new to these languages so I would appreciate if examples be as simple as possible.



Place a <input type="hidden" id="iHidden" value="" />

echo your PHP var to this input value and retrieve it in Javascript with


The approach that you are using could work but I don't recommend it because not always you need to pass just a variable, sometimes could be an array or a object, who knows. I will show you how to do it but with jQuery it's been a while since I use pure javascript for an ajax call so if you can't use jQuery you need to translate it :)

PHP Part

$data = [
    'dummyvariable' => '12345'
echo json_encode($data);

Javascript Part

    url: 'getgames.php',
    type: 'get',
    data: {
        'yearFilter': yearFilter
    dataType: 'json',
    success: function(data){

This way you can pass a lot more of variable, and it will be more organized, you can also do the php like you post it and in that case you can just use the data variable.

Also the name of the variable data in PHP and Javascript it doesn't has to be data it just the first name that occurs me.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.