2

I'm trying to make the URL in the following example contain a php variable like this:

http://api.crunchbase.com/v/1/company/$company.js

This is my jquery code:

$.ajax({
url: "http://api.crunchbase.com/v/1/company/airbnb.js",
dataType: 'jsonp',
success: function(results){
    var number_of_employees = results.number_of_employees;
        }

What do I need to do to achieve this?

Thanks!

dot
  • 2,833
  • 7
  • 37
  • 52

3 Answers3

3

You'll need to output the variable as JavaScript from PHP at some point in the script. This can be done quite easily using json_encode:

var company = <?php echo json_encode($company) ?>;

Note that this will have to be placed in a file that is actually executed by PHP, rather than an inert .js file. One way to achieve this is to put it in an inline <script> in the HTML in your PHP template; e.g.

<script type="text/javascript">
    var company = <?php echo json_encode($company) ?>;
</script>
Will Vousden
  • 31,330
  • 9
  • 80
  • 92
1

Try this:

<script type="text/javascript">
    var company = <?php echo json_encode($company); ?>;
    alert(company);
</script>

You're setting the company variable with the output of $company, you can then use this variable however you please in JavaScript.

$.ajax({
url: "http://api.crunchbase.com/v/1/company/" + company + ".js",
dataType: 'jsonp',
success: function(results){
    var number_of_employees = results.number_of_employees;
}
Ben Everard
  • 13,556
  • 12
  • 65
  • 96
0

Can you try this, assuming you have the company name in the php $company variable:

$.ajax({
url: "http://api.crunchbase.com/v/1/company/<?php echo $company ?>.js",
dataType: 'jsonp',
success: function(results){
    var number_of_employees = results.number_of_employees;
}
Bill the Lizard
  • 386,424
  • 207
  • 554
  • 861
Fabrizio D'Ammassa
  • 4,699
  • 24
  • 32