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,823
  • 7
  • 38
  • 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
  • 32,488
  • 9
  • 84
  • 95
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,652
  • 14
  • 67
  • 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
  • 398,270
  • 210
  • 566
  • 880
Fabrizio D'Ammassa
  • 4,729
  • 25
  • 32