Jump to content

Array to json is giving me trouble, help please...


Rita_Ruah

Recommended Posts

Hello, I have an array with this structure:

array (size=2)
  0 => 
    array (size=2)
      'name' => string 'MR A' (length=4)
      'location' => string 'A LAND' (length=6)
  1 => 
    array (size=2)
      'name' => string 'MR B' (length=4)
      'location' => string 'B LAND' (length=6)

I am trying to send it via Ajax converting the $array with json_encode($array) which results into:

[{ name:"MR A", location:"A LAND" }, { name: "MR B", location: "B LAND" }] 

.

But it's giving me an error... each time i make a var_dump from the other file, I find myself stuck with a "undefined". 

 

Is the array bad?

 

How should I proceed?

 

Tks

 

EDIT: Please move to the right section (PHP Questions).


<body>
<?php
$array = array();

for($i = 0; $i < 2; $i++){
$array[$i]['name'] = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
$array[$i]['location'] = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
}

$array = json_encode($array);
?>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script>
var data = <?php echo $array; ?>;
$.ajax({
type: "POST",
url: "process.php",
data: data,
success: function (msg) {
console.log(msg);
}
});
</script>
</body>

 

  On 1/23/2014 at 9:17 PM, Barand said:

 

Shouldn't data be string value ie in quotes

var data = "<?php echo $array; ?>";

It gives me an error :(

Btw, here's how it looks when running:

 

var data = [{"name":"fspvo","location":"e6x3p"},{"name":"bx85i","location":"rlxf9"}];

I've had the most success with the following:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script>
//var data = <?php echo $array; ?>;
var data = <?php echo htmlspecialchars(json_encode($array), ENT_NOQUOTES); ?>;
   $.ajax({
      type: "POST",
      url: "process.php",
	  data: data,
      success: function (msg) {
		console.log(msg);
	  }
	  });
</script>

Where array is a PHP array, not encoded.

BTW, you can turn on Firebug and see the POST data in the console log under the AJAX entry.

The data parameter to the ajax function needs to be either a string or an object of name/value pairs. What you need to do is create an object with a property and stick your encoded json as the value of the property.

 

For example:

var data = {
   array: <?php echo htmlspecialchars(json_encode($array), ENT_NOQUOTES); ?>
};
$.ajax({
      type: "POST",
      url: "process.php",
      data: data,
      success: function (msg) {
		console.log(msg);
	  }
});

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.