How do I pass an array from PHP to the JavaScript function console.log()
? I'm simulating a DB. I understand that I don't have an array declared in the code. I've tried using the .getJSON() function but it didn't work. Should I do an AJAX call for each element? I was thinking about that but there has to be a better way.
JavaScript code:
$.ajax({
method:"POST",
url:'php.php',
data:"",
dataType:'json',
success:function(data){
var y1=data;
console.log(data.name);
}
});
PHP code:
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//assign vars after formatting to avoid a wrong login with correct
//username and password
$username = trim($_POST["user"]);
$customer_array = array();
$customer1 = array(
'name' => '3',
'city' => 'Houston'
);
$customer_array[] = $customer1;
$customer2 = array(
'name' => '2',
'city' => 'Boston'
);
$customer_array[] = $customer2;
$customer3 = array(
'name' => "1",
'city' => "Bossier City"
);
echo json_encode($customer_array);
}
data[0].name
because it would be in an object like[{"name":"something","city":something"},{"name":"some name","city":something else"}]
, try justconsole.log(data);
see if that comes through as the objectmethod:"POST"
it'stype:"POST"
, right now you are probably sending a$_GET
data
and check for it in the file instead of just checking for a post, especially if you expand upon this script in the future:data:{"action":"get_name_city"}
, then in the PHP it would look likeif(isset($_POST['action']) && $_POST['action'] == 'get_name_city') { etc...
.method:
option was added in jQuery 1.9. It's equivalent totype:
.