0

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.

2
  • You need to encode the output from PHP in key:value pairs. Use json_encode. Then you can use data.name to access it providing your key in PHP is name. Commented Apr 28, 2014 at 10:24
  • include jQuery api.jquery.com/jQuery.get Commented Apr 28, 2014 at 10:25

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

4 Comments

Do I need to include a lib to use that? Because it didnt work :<
include jQuery und wrap the JS code: learn.jquery.com/using-jquery-core/document-ready
one }); is missing ;)
Yea the thing is that I have a lot of functions in that js file and it seems like $.get('getId.php', function(data) { user_name = data; }); is the problem... I tried to just change user_name = "name"; and ignoring the data that get returned... but nothing.
0
<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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.