I have a .js file with only javascript in it and my question is; I have separate .php file and .js file. And I want to get the value the .php file echoes/returns. How can I fix this?
I searched around and found that I could use this:
php:
<?php
echo 'name';
?>
js:
var user_name;
$.get('getId.php', function(data) {
user_name = data;
});
// other code
But this didn't work. Or perhaps do I need another js lib included? I don't get what the php file returns, its blank.
use json_encode();
Add jquery library
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
In PHP
<?php
echo json_encode(array('name'));
?>
THEN
<script type="text/javascript">
$(document).ready(function(){
var user_name;
$.get('getId.php', function(data) {
user_name = data;
});
});
</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "anyfile.php",
success: function(data){
alert(data);
}
});
return false;
});
</script>
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.