Javasscript Array returned from AJAX

I am currently trying to implement an AJAX request:

$("form").submit(function() {
  $.ajax({
    type: "POST",
    url: "user_locator.php",
    data: $("form").serialize(), // serializes the form's elements.
    success: function(data) {
      //save userdata
      var userdata = data;
      console.log(userdata);
      var lat_u = userdata["location"]["lat"];
      var lng_u = userdata[1][1];
      console.log(lat_u);
      console.log(lng_u);
      //make a marker                             
      var usermarker = new google.maps.Marker({
        position: new google.maps.LatLng(lat_u, lng_u),
        map: map,
      });
    }
  });
  // avoid to execute the actual submit of the form.
  return false;
});

This request returns an array:

[Log] Array (index.php, line 177) (
  [range] => 5
  [location] => Array (
    [lat] => 50.73743
    [lng] => 7.0982068
  )
)

However, when I try to access the returned value with:

`Var lat_u = userdata["location"]["lat"];`

I get the error code:

[Error] TypeError: undefined is not an object (evaluating 'userdata["location"]["lat"]')

this is my php file:

<?php
    // configuration
    require("../includes/config.php");

    //if ajax is submitted
    if(isset($_POST['range']) && !empty($_POST['location'])) 
    {
        //save data
        $location["range"] = $_POST["range"];

        //calculate latlng
        $location["location"] = convert($_POST["location"]);
        print_r($location);
    }


?>

When i try to use: var userdata = JSON.parse(data); i get the error: SyntaxError: JSON Parse error: Unexpected identifier "Array"

Does anyone know what my mistake is?

Upvotes: 0

Views: 91

Answers (1)

Johann-S
Johann-S

Reputation: 1291

You have to display your array as a string with json_encode in PHP and after you'll be able to do a JSON.parse or $.parseJSON in Javascript.

Or you can send JSON headers :

header('Content-Type: application/json');
echo json_encode($data);

And you wont have to use JSON.parse or $.parseJSON to get a JavaScript array.

Upvotes: 1

Related Questions