3

I'm looking to make an object containing latitudes and longitudes of various places such as [["Second Event",19.0554748,72.8497017],["Demo Event",19.2097381,72.8737017]].

I'm successful of making this in php by using json_encode() function. How do I retrieve it in the callback function. I've tried the following:

$.post('maps1.php',{},function(data){
    alert(data);
    markers=JSON.stringify(data);
},"json");
alert(markers);

However this doesn't seems to work. What should I do?

JAAulde
  • 19,250
  • 5
  • 52
  • 63
ashish
  • 31
  • 1
  • 1
  • 2
  • 2
    Can you explain "this doesn't seems to work"? Are you getting any errors? – Ravi Y Dec 18 '12 at 06:08
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – JAAulde May 30 '14 at 14:38

3 Answers3

3

You have the scope for the variable markers inside the post method, try doing it like this:

var markers = '';

$.post('maps1.php', {}, function (data) {
    alert(data);
    markers = JSON.stringify(data);
}, "json");

alert(markers)
PhearOfRayne
  • 4,990
  • 3
  • 31
  • 44
  • @user1911914 Are you getting the alert for the data to appear? – PhearOfRayne Dec 18 '12 at 05:58
  • @user1911914 To make sure your browser supports JSON parsing you can visit http://caniuse.com/json – PhearOfRayne Dec 18 '12 at 06:01
  • the browser does support json...and im not getting the alert – ashish Dec 18 '12 at 06:16
  • @user1911914 If your not getting the alert, you need to start there. I'd recommend using Chromes inspector and opening the network tab to see if your getting a ny errors. – PhearOfRayne Dec 18 '12 at 06:19
  • Its difficult to monitor using firebug since Im working on google maps api which takes a lot of data.. – ashish Dec 18 '12 at 06:23
  • // php code and jquery code ![enter image description here][1] ![enter image description here][2] [1]: http://i.stack.imgur.com/pZRNt.jpg [2]: http://i.stack.imgur.com/SwOZ4.jpg These are the screenshots.. – ashish Dec 18 '12 at 06:31
0

$.ajax should do this way:

     var marker;
     $.ajax({
        url:'maps1.php',
        data:{},
        type:'POST',
        dataType:'json',
        success:function(data){
            alert(data);
            marker = JSON.stringify(data);
        },
        complete:{
            alert(marker);
        }
   });

and $.POST should be like this:

   $.post('maps1.php',{},function(data){
       alert(data);
   },"json").done(function(data){
       markers=JSON.stringify(data);
       alert(markers);
   });

but i prefer to use $.ajax()

Jai
  • 74,255
  • 12
  • 74
  • 103
0

ajax string syntax below:

 var marker;
 $.ajax({
    url:'maps1.php',
    data:{},
    type:'POST',
    dataType:'json',
    success:function(data){
        alert(data);
        marker = JSON.stringify(data);
    },
    complete:{
        alert(marker);
    }
});
Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162
gokul
  • 1