0

I've been struggling with converting an Array of objects to JSON, or any other PHP readable format so I can send it over AJAX.

I'm using localStorage and I save an object into it, I save it using

JSON.stringify(data)

Now when I loop through all the localStorage data, I add it to an array using the following code

var locations = new Array();
for(var i = 0; i < localStorage.length; i++){
    locations[i] = JSON.parse(localStorage.getItem(localStorage.key(i)));
}

The end result looks like this.

enter image description here

This is my $.ajax request

$.ajax({
    type: "POST",  
    url: "store.php",
    dataType: "json", 
    data: locations,
    success: function(data) {
        console.log(data);
    }
});

The only problem is that I can't seem to convert it to a readable format to send to PHP

Any clues? Thanks!

11
  • 1
    What does your PHP look like? Data in that form should be readable. Commented Feb 12, 2015 at 7:53
  • I'm currently only printing out the full post request for testing. I'll add the ajax request Commented Feb 12, 2015 at 7:53
  • How do you print your data from PHP? Commented Feb 12, 2015 at 8:02
  • I'm trying print_r($_POST); but it's not showing anything. Commented Feb 12, 2015 at 8:02
  • Maybe you should put your locations to an object. ` $.ajax({ type: "POST", url: "store.php", dataType: "json", data: {location: locations}, success: function(data) { console.log(data); } }); ` Then on your PHP, print($_POST["location"]); Commented Feb 12, 2015 at 8:04

4 Answers 4

1

Make your post data an object.

$.ajax({
    type: "POST",  
    url: "store.php",
    dataType: "json", 
    data: {location: locations},
    success: function(data) {
        console.log(data);
    }
});

Then on your PHP: print($_POST['location']);

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

Comments

1

You can also simplify like this.

$.post('store.php', {location: locations}, function(data) {
    console.log(data);
});

Comments

0

You should also be able to pass the content directly from localStorage -- no need to build an array from it.

Data formed with JSON.stringify() can be sent through $.ajax and interpreted by PHP.

Comments

0

You can use PHP's input stream to read your data:

$json = file_get_contents('php://input');
$array = json_decode($json);

For more info on PHP's I/O streams, see http://php.net/manual/en/wrappers.php.php

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.