-1

both can be divided into separate arrays formatted JSON string returned by the php script? my JS code

function GetData(id){
    $.ajax({
        url: 'list.php',
        data: 'id=' + id,
        type: 'POST',
        success: function(data){
            alert(data)
            console.log(data)
        }
    })
}

my list.php

<?php
$id = $_POST['id'];
$connect = mysql_connect("localhost", "admin", "118326") or die(mysql_errno());
$db = mysql_select_db("flabers", $connect) or die(mysql_error());
$result = mysql_query("SELECT * FROM list WHERE id = '$id'") or die(mysql_error());
$array = mysql_fetch_assoc($result) or die(mysql_errno());
echo json_encode($array);
?>

return json string

{"id":"88","country":"Korea, Japan, USA","brand":"Samsung, Sony, HTC"} 

how to get the two arrays country and brand?

Dima
  • 7
  • 5
  • 2
    `data.country`? That's not an array though, just a string. – deceze Oct 30 '12 at 09:25
  • You are using [an obsolete database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). You are also exposing yourself to [SQL injection attacks](http://bobby-tables.com/) that a modern API would make it easier to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Oct 30 '12 at 09:29
  • I know, I just could not create a problem with the array, because that has already been (but it does not apply to the topic) – Dima Oct 30 '12 at 09:35

3 Answers3

1

user dataType:'json'

 $.ajax({
    url: 'list.php',
    data: 'id=' + id,
    contentType: 'application/json',
    type: 'POST',
    dataType: 'json',
    success: function(data){
        alert(data)
        console.log(data) //access it like data.id, data.country etc
    }
})
Pragnesh Chauhan
  • 8,363
  • 9
  • 42
  • 53
0

The PHP should inform the client that it is sending JSON and not HTML (which it does by default).

header('Content-Type: application/json');

jQuery will then parse it into a JavaScript object automatically.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

Parse json in the below way.

//var obj = JSON.parse(jsonstring); //javascript way

var obj = jQuery.parseJSON(jsonstring); //jquery way

alert(obj.country + " : " + obj.brand);
Abhishek Saha
  • 2,564
  • 1
  • 19
  • 29
  • That's a very long way around that bypasses the pollyfill built into jQuery. It's a very bad approach to the problem. – Quentin Oct 30 '12 at 09:30
  • That is still an extra step. The jQuery way is the method described in my answer and in Pragnesh Chauhan's answer. – Quentin Oct 30 '12 at 09:37