简体   繁体   中英

Send variable from PHP to Javascript

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

Javascript

xmlhttp=new XMLHttpRequest();
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {
       document.getElementById("dummy").innerHTML=this.responseText;
    }
  }
  xmlhttp.open("GET","getgames.php?yearFilter="+yearFilter,true);
  xmlhttp.send(null);

php

$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

document.getElementById("iHidden").value;

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

$.ajax({
    url: 'getgames.php',
    type: 'get',
    data: {
        'yearFilter': yearFilter
    },
    dataType: 'json',
    success: function(data){
        $("#dummy").html(data.dummyvariable)
    }
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM