0

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?

1
  • Is your index.php file outputing a json content-type header? If not jquery will default to parsing the returned data as text/html so data will just be a string. Commented Feb 23, 2015 at 11:00

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.