2

Hi I use an ajax script to get var new_sample_data. In my .php I have an second javascript file included. There I need also the variable new_sample_data to show an tooltip.

First javascript file:

 $.ajax({ 
        type: "POST",                                    
        url: '../assets/includes/geodata1.php',
        data: {datum1: Date.today().add({days: -29}).toString('yyyy-MM-dd'), datum2: Date.today().toString('yyyy-MM-dd')},
        dataType: 'json',
        success: function(data)
        {
        var new_sample_data = data;

But any I do I don't get the values from the var new_sample_data in the second javascript file. Allways 0. I tried to set manual var new_sample_data = "de":"4" in the if(params.showTooltip) and it works for the manual value. But I don't find my error :-)

Code from second java scrpit file:

if (params.showTooltip) {
          map.label.text(mapData.pathes[code].name + " - Öffnungen: " + sample_data[code]);
          jQuery(params.container).trigger(labelShowEvent, [map.label, code]);
TrivoXx
  • 161
  • 3
  • 17
  • 1
    Related question: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – elclanrs Jul 25 '13 at 20:31

2 Answers2

2

Sounds like you have a scope problem.
You need to define var new_sample_data just once and outside any function to make it Global (accessible to other functions).

Add var new_sample_data; after your <script> opening tag and remove the word var from where it is now.

On your second file I don't see a variable called new_sample_data, just sample_data. Can it be also a typo problem?

Sergio
  • 28,539
  • 11
  • 85
  • 132
0

To make a global variable, you can use this:

window.new_sample_data = data;

or initialize the variable with var outside a function scope, for instance at the top of your js file.

You may have issues with timing as well though, since your variable is in a callback. If you want to access the data returned by your ajax request, you'll have to make sure that you don't try to read it until after the data has been returned by the server. Placing the reference in a later file is insufficient, since the function that the variable is set in will be called a synchronously after all of the initial synchronous operations have been completed.

Ben McCormick
  • 25,260
  • 12
  • 52
  • 71